blob: 1df648bf04ec0f67f629e7d7544848ca5dc5d989 [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,
ilnike67c59e2017-02-09 04:08:56 -0800136 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);
ilnike67c59e2017-02-09 04:08:56 -0800229 if (!IsFlexfec(header.payloadType)) {
brandtr504b95e2016-12-21 02:54:35 -0800230 // 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_);
ilnike67c59e2017-02-09 04:08:56 -0800250 if (!first_send_timestamp_ && rtp_timestamp_delta_ == 0) {
pbos14fe7082016-04-20 06:35:56 -0700251 while (frames_.front().timestamp() != video_frame.timestamp()) {
252 ++dropped_frames_before_first_encode_;
253 frames_.pop_front();
254 RTC_CHECK(!frames_.empty());
255 }
ilnike67c59e2017-02-09 04:08:56 -0800256 first_send_timestamp_ = rtc::Optional<uint32_t>(video_frame.timestamp());
pbos14fe7082016-04-20 06:35:56 -0700257 }
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_);
ilnik5f471262017-02-03 02:02:17 -0800272
ilnike67c59e2017-02-09 04:08:56 -0800273 if (rtp_timestamp_delta_ == 0) {
274 rtp_timestamp_delta_ = header.timestamp - *first_send_timestamp_;
275 first_send_timestamp_ = rtc::Optional<uint32_t>();
276 }
277 if (!IsFlexfec(header.payloadType)) {
brandtr504b95e2016-12-21 02:54:35 -0800278 // 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_;
kthelgason2bc68642017-02-07 07:02:22 -0800317 } else {
318 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
319 render_time_ms);
pbos14fe7082016-04-20 06:35:56 -0700320 }
ivica5d6a06c2015-09-17 05:30:24 -0700321 frames_.pop_front();
pbos14fe7082016-04-20 06:35:56 -0700322 RTC_DCHECK(!frames_.empty());
ivica5d6a06c2015-09-17 05:30:24 -0700323 }
324
325 VideoFrame reference_frame = frames_.front();
326 frames_.pop_front();
sprang16daaa52016-03-09 01:30:24 -0800327 int64_t reference_timestamp =
328 wrap_handler_.Unwrap(reference_frame.timestamp());
329 if (send_timestamp == reference_timestamp - 1) {
sprangce4aef12015-11-02 07:23:20 -0800330 // TODO(ivica): Make this work for > 2 streams.
Peter Boströme4499152016-02-05 11:13:28 +0100331 // Look at RTPSender::BuildRTPHeader.
sprangce4aef12015-11-02 07:23:20 -0800332 ++send_timestamp;
333 }
sprang16daaa52016-03-09 01:30:24 -0800334 ASSERT_EQ(reference_timestamp, send_timestamp);
ivica5d6a06c2015-09-17 05:30:24 -0700335
336 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
337
nisse97f0b932016-05-26 09:44:40 -0700338 last_rendered_frame_ = rtc::Optional<VideoFrame>(video_frame);
ivica5d6a06c2015-09-17 05:30:24 -0700339 }
340
ivica5d6a06c2015-09-17 05:30:24 -0700341 void Wait() {
342 // Frame comparisons can be very expensive. Wait for test to be done, but
343 // at time-out check if frames_processed is going up. If so, give it more
344 // time, otherwise fail. Hopefully this will reduce test flakiness.
345
Peter Boström8c38e8b2015-11-26 17:45:47 +0100346 stats_polling_thread_.Start();
sprangce4aef12015-11-02 07:23:20 -0800347
ivica5d6a06c2015-09-17 05:30:24 -0700348 int last_frames_processed = -1;
ivica5d6a06c2015-09-17 05:30:24 -0700349 int iteration = 0;
Peter Boström5811a392015-12-10 13:02:50 +0100350 while (!done_.Wait(VideoQualityTest::kDefaultTimeoutMs)) {
ivica5d6a06c2015-09-17 05:30:24 -0700351 int frames_processed;
352 {
353 rtc::CritScope crit(&comparison_lock_);
354 frames_processed = frames_processed_;
355 }
356
357 // Print some output so test infrastructure won't think we've crashed.
358 const char* kKeepAliveMessages[3] = {
359 "Uh, I'm-I'm not quite dead, sir.",
360 "Uh, I-I think uh, I could pull through, sir.",
361 "Actually, I think I'm all right to come with you--"};
362 printf("- %s\n", kKeepAliveMessages[iteration++ % 3]);
363
364 if (last_frames_processed == -1) {
365 last_frames_processed = frames_processed;
366 continue;
367 }
Peter Boströmdd45eb62016-01-19 15:22:32 +0100368 if (frames_processed == last_frames_processed) {
369 EXPECT_GT(frames_processed, last_frames_processed)
370 << "Analyzer stalled while waiting for test to finish.";
371 done_.Set();
372 break;
373 }
ivica5d6a06c2015-09-17 05:30:24 -0700374 last_frames_processed = frames_processed;
375 }
376
377 if (iteration > 0)
378 printf("- Farewell, sweet Concorde!\n");
379
Peter Boström8c38e8b2015-11-26 17:45:47 +0100380 stats_polling_thread_.Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700381 }
382
pbos14fe7082016-04-20 06:35:56 -0700383 rtc::VideoSinkInterface<VideoFrame>* pre_encode_proxy() {
384 return &pre_encode_proxy_;
385 }
Peter Boströme4499152016-02-05 11:13:28 +0100386 EncodedFrameObserver* encode_timing_proxy() { return &encode_timing_proxy_; }
387
sprangce4aef12015-11-02 07:23:20 -0800388 test::LayerFilteringTransport* const transport_;
ivica5d6a06c2015-09-17 05:30:24 -0700389 PacketReceiver* receiver_;
ivica5d6a06c2015-09-17 05:30:24 -0700390
391 private:
392 struct FrameComparison {
393 FrameComparison()
394 : dropped(false),
nissedf2ceb82016-12-15 06:29:53 -0800395 input_time_ms(0),
ivica5d6a06c2015-09-17 05:30:24 -0700396 send_time_ms(0),
397 recv_time_ms(0),
398 render_time_ms(0),
399 encoded_frame_size(0) {}
400
401 FrameComparison(const VideoFrame& reference,
402 const VideoFrame& render,
403 bool dropped,
nissedf2ceb82016-12-15 06:29:53 -0800404 int64_t input_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700405 int64_t send_time_ms,
406 int64_t recv_time_ms,
407 int64_t render_time_ms,
408 size_t encoded_frame_size)
409 : reference(reference),
410 render(render),
411 dropped(dropped),
nissedf2ceb82016-12-15 06:29:53 -0800412 input_time_ms(input_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700413 send_time_ms(send_time_ms),
414 recv_time_ms(recv_time_ms),
415 render_time_ms(render_time_ms),
416 encoded_frame_size(encoded_frame_size) {}
417
nissedf2ceb82016-12-15 06:29:53 -0800418 FrameComparison(bool dropped,
419 int64_t input_time_ms,
420 int64_t send_time_ms,
421 int64_t recv_time_ms,
422 int64_t render_time_ms,
423 size_t encoded_frame_size)
424 : dropped(dropped),
425 input_time_ms(input_time_ms),
426 send_time_ms(send_time_ms),
427 recv_time_ms(recv_time_ms),
428 render_time_ms(render_time_ms),
429 encoded_frame_size(encoded_frame_size) {}
430
431 rtc::Optional<VideoFrame> reference;
432 rtc::Optional<VideoFrame> render;
ivica5d6a06c2015-09-17 05:30:24 -0700433 bool dropped;
nissedf2ceb82016-12-15 06:29:53 -0800434 int64_t input_time_ms;
ivica5d6a06c2015-09-17 05:30:24 -0700435 int64_t send_time_ms;
436 int64_t recv_time_ms;
437 int64_t render_time_ms;
438 size_t encoded_frame_size;
439 };
440
441 struct Sample {
ivica8d15bd62015-10-07 02:43:12 -0700442 Sample(int dropped,
443 int64_t input_time_ms,
444 int64_t send_time_ms,
445 int64_t recv_time_ms,
446 int64_t render_time_ms,
447 size_t encoded_frame_size,
ivica5d6a06c2015-09-17 05:30:24 -0700448 double psnr,
ivica8d15bd62015-10-07 02:43:12 -0700449 double ssim)
ivica5d6a06c2015-09-17 05:30:24 -0700450 : dropped(dropped),
451 input_time_ms(input_time_ms),
452 send_time_ms(send_time_ms),
453 recv_time_ms(recv_time_ms),
ivica8d15bd62015-10-07 02:43:12 -0700454 render_time_ms(render_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700455 encoded_frame_size(encoded_frame_size),
456 psnr(psnr),
ivica8d15bd62015-10-07 02:43:12 -0700457 ssim(ssim) {}
ivica5d6a06c2015-09-17 05:30:24 -0700458
ivica8d15bd62015-10-07 02:43:12 -0700459 int dropped;
460 int64_t input_time_ms;
461 int64_t send_time_ms;
462 int64_t recv_time_ms;
463 int64_t render_time_ms;
464 size_t encoded_frame_size;
ivica5d6a06c2015-09-17 05:30:24 -0700465 double psnr;
466 double ssim;
ivica5d6a06c2015-09-17 05:30:24 -0700467 };
468
Peter Boströme4499152016-02-05 11:13:28 +0100469 // This class receives the send-side OnEncodeTiming and is provided to not
470 // conflict with the receiver-side pre_decode_callback.
471 class OnEncodeTimingProxy : public EncodedFrameObserver {
472 public:
473 explicit OnEncodeTimingProxy(VideoAnalyzer* parent) : parent_(parent) {}
474
475 void OnEncodeTiming(int64_t ntp_time_ms, int encode_time_ms) override {
476 parent_->MeasuredEncodeTiming(ntp_time_ms, encode_time_ms);
477 }
ilnike67c59e2017-02-09 04:08:56 -0800478 void EncodedFrameCallback(const EncodedFrame& frame) override {}
Peter Boströme4499152016-02-05 11:13:28 +0100479
480 private:
481 VideoAnalyzer* const parent_;
482 };
483
pbos14fe7082016-04-20 06:35:56 -0700484 // This class receives the send-side OnFrame callback and is provided to not
485 // conflict with the receiver-side renderer callback.
486 class PreEncodeProxy : public rtc::VideoSinkInterface<VideoFrame> {
487 public:
488 explicit PreEncodeProxy(VideoAnalyzer* parent) : parent_(parent) {}
489
490 void OnFrame(const VideoFrame& video_frame) override {
491 parent_->PreEncodeOnFrame(video_frame);
492 }
493
494 private:
495 VideoAnalyzer* const parent_;
496 };
497
ivica5d6a06c2015-09-17 05:30:24 -0700498 void AddFrameComparison(const VideoFrame& reference,
499 const VideoFrame& render,
500 bool dropped,
501 int64_t render_time_ms)
502 EXCLUSIVE_LOCKS_REQUIRED(crit_) {
sprange1f2f1f2016-02-01 02:04:52 -0800503 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
504 int64_t send_time_ms = send_times_[reference_timestamp];
505 send_times_.erase(reference_timestamp);
506 int64_t recv_time_ms = recv_times_[reference_timestamp];
507 recv_times_.erase(reference_timestamp);
ivica5d6a06c2015-09-17 05:30:24 -0700508
sprangce4aef12015-11-02 07:23:20 -0800509 // TODO(ivica): Make this work for > 2 streams.
sprange1f2f1f2016-02-01 02:04:52 -0800510 auto it = encoded_frame_sizes_.find(reference_timestamp);
sprangce4aef12015-11-02 07:23:20 -0800511 if (it == encoded_frame_sizes_.end())
sprange1f2f1f2016-02-01 02:04:52 -0800512 it = encoded_frame_sizes_.find(reference_timestamp - 1);
sprangce4aef12015-11-02 07:23:20 -0800513 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
514 if (it != encoded_frame_sizes_.end())
515 encoded_frame_sizes_.erase(it);
ivica5d6a06c2015-09-17 05:30:24 -0700516
ivica5d6a06c2015-09-17 05:30:24 -0700517 rtc::CritScope crit(&comparison_lock_);
stefanb1797672016-08-11 07:00:57 -0700518 if (comparisons_.size() < kMaxComparisons) {
nissedf2ceb82016-12-15 06:29:53 -0800519 comparisons_.push_back(FrameComparison(reference, render, dropped,
520 reference.ntp_time_ms(),
521 send_time_ms, recv_time_ms,
522 render_time_ms, encoded_size));
stefanb1797672016-08-11 07:00:57 -0700523 } else {
nissedf2ceb82016-12-15 06:29:53 -0800524 comparisons_.push_back(FrameComparison(dropped,
525 reference.ntp_time_ms(),
526 send_time_ms, recv_time_ms,
527 render_time_ms, encoded_size));
stefanb1797672016-08-11 07:00:57 -0700528 }
Peter Boström5811a392015-12-10 13:02:50 +0100529 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700530 }
531
532 static bool PollStatsThread(void* obj) {
533 return static_cast<VideoAnalyzer*>(obj)->PollStats();
534 }
535
536 bool PollStats() {
Peter Boströmdd45eb62016-01-19 15:22:32 +0100537 if (done_.Wait(kSendStatsPollingIntervalMs))
Peter Boström5811a392015-12-10 13:02:50 +0100538 return false;
ivica5d6a06c2015-09-17 05:30:24 -0700539
ivica5d6a06c2015-09-17 05:30:24 -0700540 rtc::CritScope crit(&comparison_lock_);
philipelfd870db2017-01-23 03:22:15 -0800541
542 VideoSendStream::Stats send_stats = send_stream_->GetStats();
Peter Boströmb1eaa8d2016-02-23 17:30:49 +0100543 // It's not certain that we yet have estimates for any of these stats. Check
544 // that they are positive before mixing them in.
philipelfd870db2017-01-23 03:22:15 -0800545 if (send_stats.encode_frame_rate > 0)
546 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
547 if (send_stats.avg_encode_time_ms > 0)
548 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
549 if (send_stats.encode_usage_percent > 0)
550 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
551 if (send_stats.media_bitrate_bps > 0)
552 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
553
554 if (receive_stream_ != nullptr) {
555 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
556 if (receive_stats.decode_ms > 0)
557 decode_time_ms_.AddSample(receive_stats.decode_ms);
558 if (receive_stats.max_decode_ms > 0)
559 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
560 }
ivica5d6a06c2015-09-17 05:30:24 -0700561
562 return true;
563 }
564
565 static bool FrameComparisonThread(void* obj) {
566 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
567 }
568
569 bool CompareFrames() {
570 if (AllFramesRecorded())
571 return false;
572
ivica5d6a06c2015-09-17 05:30:24 -0700573 FrameComparison comparison;
574
575 if (!PopComparison(&comparison)) {
576 // Wait until new comparison task is available, or test is done.
577 // If done, wake up remaining threads waiting.
Peter Boström5811a392015-12-10 13:02:50 +0100578 comparison_available_event_.Wait(1000);
ivica5d6a06c2015-09-17 05:30:24 -0700579 if (AllFramesRecorded()) {
Peter Boström5811a392015-12-10 13:02:50 +0100580 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700581 return false;
582 }
583 return true; // Try again.
584 }
585
586 PerformFrameComparison(comparison);
587
588 if (FrameProcessed()) {
589 PrintResults();
590 if (graph_data_output_file_)
591 PrintSamplesToFile();
Peter Boström5811a392015-12-10 13:02:50 +0100592 done_.Set();
593 comparison_available_event_.Set();
ivica5d6a06c2015-09-17 05:30:24 -0700594 return false;
595 }
596
597 return true;
598 }
599
600 bool PopComparison(FrameComparison* comparison) {
601 rtc::CritScope crit(&comparison_lock_);
602 // If AllFramesRecorded() is true, it means we have already popped
603 // frames_to_process_ frames from comparisons_, so there is no more work
604 // for this thread to be done. frames_processed_ might still be lower if
605 // all comparisons are not done, but those frames are currently being
606 // worked on by other threads.
607 if (comparisons_.empty() || AllFramesRecorded())
608 return false;
609
610 *comparison = comparisons_.front();
611 comparisons_.pop_front();
612
613 FrameRecorded();
614 return true;
615 }
616
617 // Increment counter for number of frames received for comparison.
618 void FrameRecorded() {
619 rtc::CritScope crit(&comparison_lock_);
620 ++frames_recorded_;
621 }
622
623 // Returns true if all frames to be compared have been taken from the queue.
624 bool AllFramesRecorded() {
625 rtc::CritScope crit(&comparison_lock_);
626 assert(frames_recorded_ <= frames_to_process_);
627 return frames_recorded_ == frames_to_process_;
628 }
629
630 // Increase count of number of frames processed. Returns true if this was the
631 // last frame to be processed.
632 bool FrameProcessed() {
633 rtc::CritScope crit(&comparison_lock_);
634 ++frames_processed_;
635 assert(frames_processed_ <= frames_to_process_);
636 return frames_processed_ == frames_to_process_;
637 }
638
639 void PrintResults() {
640 rtc::CritScope crit(&comparison_lock_);
641 PrintResult("psnr", psnr_, " dB");
tnakamura3123cbc2016-02-10 11:21:51 -0800642 PrintResult("ssim", ssim_, " score");
ivica5d6a06c2015-09-17 05:30:24 -0700643 PrintResult("sender_time", sender_time_, " ms");
ivica5d6a06c2015-09-17 05:30:24 -0700644 PrintResult("receiver_time", receiver_time_, " ms");
645 PrintResult("total_delay_incl_network", end_to_end_, " ms");
646 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
647 PrintResult("encoded_frame_size", encoded_frame_size_, " bytes");
648 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
philipelfd870db2017-01-23 03:22:15 -0800649 PrintResult("encode_time", encode_time_ms_, " ms");
650 PrintResult("encode_usage_percent", encode_usage_percent_, " percent");
651 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
652
653 if (receive_stream_ != nullptr) {
654 PrintResult("decode_time", decode_time_ms_, " ms");
655 PrintResult("decode_time_max", decode_time_max_ms_, " ms");
656 }
ivica5d6a06c2015-09-17 05:30:24 -0700657
pbos14fe7082016-04-20 06:35:56 -0700658 printf("RESULT dropped_frames: %s = %d frames\n", test_label_.c_str(),
659 dropped_frames_);
660 printf("RESULT dropped_frames_before_first_encode: %s = %d frames\n",
661 test_label_.c_str(), dropped_frames_before_first_encode_);
662 printf("RESULT dropped_frames_before_rendering: %s = %d frames\n",
663 test_label_.c_str(), dropped_frames_before_rendering_);
664
ivica5d6a06c2015-09-17 05:30:24 -0700665 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
666 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
667 }
668
669 void PerformFrameComparison(const FrameComparison& comparison) {
670 // Perform expensive psnr and ssim calculations while not holding lock.
stefanb1797672016-08-11 07:00:57 -0700671 double psnr = -1.0;
672 double ssim = -1.0;
nissedf2ceb82016-12-15 06:29:53 -0800673 if (comparison.reference) {
674 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
675 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
stefanb1797672016-08-11 07:00:57 -0700676 }
ivica5d6a06c2015-09-17 05:30:24 -0700677
ivica5d6a06c2015-09-17 05:30:24 -0700678 rtc::CritScope crit(&comparison_lock_);
679 if (graph_data_output_file_) {
nissedf2ceb82016-12-15 06:29:53 -0800680 samples_.push_back(Sample(
681 comparison.dropped, comparison.input_time_ms, comparison.send_time_ms,
682 comparison.recv_time_ms, comparison.render_time_ms,
683 comparison.encoded_frame_size, psnr, ssim));
ivica5d6a06c2015-09-17 05:30:24 -0700684 }
stefanb1797672016-08-11 07:00:57 -0700685 if (psnr >= 0.0)
686 psnr_.AddSample(psnr);
687 if (ssim >= 0.0)
688 ssim_.AddSample(ssim);
ivica5d6a06c2015-09-17 05:30:24 -0700689
690 if (comparison.dropped) {
691 ++dropped_frames_;
692 return;
693 }
694 if (last_render_time_ != 0)
695 rendered_delta_.AddSample(comparison.render_time_ms - last_render_time_);
696 last_render_time_ = comparison.render_time_ms;
697
nissedf2ceb82016-12-15 06:29:53 -0800698 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
brandtr504b95e2016-12-21 02:54:35 -0800699 if (comparison.recv_time_ms > 0) {
700 // If recv_time_ms == 0, this frame consisted of a packets which were all
701 // lost in the transport. Since we were able to render the frame, however,
702 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
703 // happens internally in Call, and we can therefore here not know which
704 // FEC packets that protected the lost media packets. Consequently, we
705 // were not able to record a meaningful recv_time_ms. We therefore skip
706 // this sample.
707 //
708 // The reasoning above does not hold for ULPFEC and RTX, as for those
709 // strategies the timestamp of the received packets is set to the
710 // timestamp of the protected/retransmitted media packet. I.e., then
711 // recv_time_ms != 0, even though the media packets were lost.
712 receiver_time_.AddSample(comparison.render_time_ms -
713 comparison.recv_time_ms);
714 }
nissedf2ceb82016-12-15 06:29:53 -0800715 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
ivica5d6a06c2015-09-17 05:30:24 -0700716 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
717 }
718
719 void PrintResult(const char* result_type,
720 test::Statistics stats,
721 const char* unit) {
722 printf("RESULT %s: %s = {%f, %f}%s\n",
723 result_type,
724 test_label_.c_str(),
725 stats.Mean(),
726 stats.StandardDeviation(),
727 unit);
728 }
729
730 void PrintSamplesToFile(void) {
731 FILE* out = graph_data_output_file_;
732 rtc::CritScope crit(&comparison_lock_);
733 std::sort(samples_.begin(), samples_.end(),
734 [](const Sample& A, const Sample& B) -> bool {
735 return A.input_time_ms < B.input_time_ms;
736 });
737
sprangce4aef12015-11-02 07:23:20 -0800738 fprintf(out, "%s\n", graph_title_.c_str());
ivica5d6a06c2015-09-17 05:30:24 -0700739 fprintf(out, "%" PRIuS "\n", samples_.size());
740 fprintf(out,
741 "dropped "
742 "input_time_ms "
743 "send_time_ms "
744 "recv_time_ms "
ivica8d15bd62015-10-07 02:43:12 -0700745 "render_time_ms "
ivica5d6a06c2015-09-17 05:30:24 -0700746 "encoded_frame_size "
747 "psnr "
748 "ssim "
ivica8d15bd62015-10-07 02:43:12 -0700749 "encode_time_ms\n");
750 int missing_encode_time_samples = 0;
ivica5d6a06c2015-09-17 05:30:24 -0700751 for (const Sample& sample : samples_) {
ivica8d15bd62015-10-07 02:43:12 -0700752 auto it = samples_encode_time_ms_.find(sample.input_time_ms);
753 int encode_time_ms;
754 if (it != samples_encode_time_ms_.end()) {
755 encode_time_ms = it->second;
756 } else {
757 ++missing_encode_time_samples;
758 encode_time_ms = -1;
759 }
760 fprintf(out, "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
761 " %lf %lf %d\n",
762 sample.dropped, sample.input_time_ms, sample.send_time_ms,
763 sample.recv_time_ms, sample.render_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700764 sample.encoded_frame_size, sample.psnr, sample.ssim,
ivica8d15bd62015-10-07 02:43:12 -0700765 encode_time_ms);
766 }
767 if (missing_encode_time_samples) {
768 fprintf(stderr,
769 "Warning: Missing encode_time_ms samples for %d frame(s).\n",
770 missing_encode_time_samples);
ivica5d6a06c2015-09-17 05:30:24 -0700771 }
772 }
773
perkja49cbd32016-09-16 07:53:41 -0700774 // Implements VideoSinkInterface to receive captured frames from a
775 // FrameGeneratorCapturer. Implements VideoSourceInterface to be able to act
776 // as a source to VideoSendStream.
777 // It forwards all input frames to the VideoAnalyzer for later comparison and
778 // forwards the captured frames to the VideoSendStream.
779 class CapturedFrameForwarder : public rtc::VideoSinkInterface<VideoFrame>,
780 public rtc::VideoSourceInterface<VideoFrame> {
781 public:
782 explicit CapturedFrameForwarder(VideoAnalyzer* analyzer)
783 : analyzer_(analyzer), send_stream_input_(nullptr) {}
784
785 private:
786 void OnFrame(const VideoFrame& video_frame) override {
787 VideoFrame copy = video_frame;
788 copy.set_timestamp(copy.ntp_time_ms() * 90);
ilnike67c59e2017-02-09 04:08:56 -0800789
790 analyzer_->AddCapturedFrameForComparison(video_frame);
perkja49cbd32016-09-16 07:53:41 -0700791 rtc::CritScope lock(&crit_);
792 if (send_stream_input_)
793 send_stream_input_->OnFrame(video_frame);
794 }
795
796 // Called when |send_stream_.SetSource()| is called.
797 void AddOrUpdateSink(rtc::VideoSinkInterface<VideoFrame>* sink,
798 const rtc::VideoSinkWants& wants) override {
799 rtc::CritScope lock(&crit_);
800 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
801 send_stream_input_ = sink;
802 }
803
804 // Called by |send_stream_| when |send_stream_.SetSource()| is called.
805 void RemoveSink(rtc::VideoSinkInterface<VideoFrame>* sink) override {
806 rtc::CritScope lock(&crit_);
807 RTC_DCHECK(sink == send_stream_input_);
808 send_stream_input_ = nullptr;
809 }
810
811 VideoAnalyzer* const analyzer_;
812 rtc::CriticalSection crit_;
813 rtc::VideoSinkInterface<VideoFrame>* send_stream_input_ GUARDED_BY(crit_);
814 };
815
816 void AddCapturedFrameForComparison(const VideoFrame& video_frame) {
817 rtc::CritScope lock(&crit_);
ilnike67c59e2017-02-09 04:08:56 -0800818 RTC_DCHECK_EQ(0, video_frame.timestamp());
819 // Frames from the capturer does not have a rtp timestamp. Create one so it
820 // can be used for comparison.
821 VideoFrame copy = video_frame;
822 copy.set_timestamp(copy.ntp_time_ms() * 90);
823 frames_.push_back(copy);
perkja49cbd32016-09-16 07:53:41 -0700824 }
825
826 VideoSendStream* send_stream_;
philipelfd870db2017-01-23 03:22:15 -0800827 VideoReceiveStream* receive_stream_;
perkja49cbd32016-09-16 07:53:41 -0700828 CapturedFrameForwarder captured_frame_forwarder_;
ivica5d6a06c2015-09-17 05:30:24 -0700829 const std::string test_label_;
830 FILE* const graph_data_output_file_;
sprangce4aef12015-11-02 07:23:20 -0800831 const std::string graph_title_;
832 const uint32_t ssrc_to_analyze_;
pbos14fe7082016-04-20 06:35:56 -0700833 PreEncodeProxy pre_encode_proxy_;
Peter Boströme4499152016-02-05 11:13:28 +0100834 OnEncodeTimingProxy encode_timing_proxy_;
ivica5d6a06c2015-09-17 05:30:24 -0700835 std::vector<Sample> samples_ GUARDED_BY(comparison_lock_);
ivica8d15bd62015-10-07 02:43:12 -0700836 std::map<int64_t, int> samples_encode_time_ms_ GUARDED_BY(comparison_lock_);
ivica5d6a06c2015-09-17 05:30:24 -0700837 test::Statistics sender_time_ GUARDED_BY(comparison_lock_);
838 test::Statistics receiver_time_ GUARDED_BY(comparison_lock_);
839 test::Statistics psnr_ GUARDED_BY(comparison_lock_);
840 test::Statistics ssim_ GUARDED_BY(comparison_lock_);
841 test::Statistics end_to_end_ GUARDED_BY(comparison_lock_);
842 test::Statistics rendered_delta_ GUARDED_BY(comparison_lock_);
843 test::Statistics encoded_frame_size_ GUARDED_BY(comparison_lock_);
844 test::Statistics encode_frame_rate_ GUARDED_BY(comparison_lock_);
philipelfd870db2017-01-23 03:22:15 -0800845 test::Statistics encode_time_ms_ GUARDED_BY(comparison_lock_);
846 test::Statistics encode_usage_percent_ GUARDED_BY(comparison_lock_);
847 test::Statistics decode_time_ms_ GUARDED_BY(comparison_lock_);
848 test::Statistics decode_time_max_ms_ GUARDED_BY(comparison_lock_);
849 test::Statistics media_bitrate_bps_ GUARDED_BY(comparison_lock_);
ivica5d6a06c2015-09-17 05:30:24 -0700850
851 const int frames_to_process_;
852 int frames_recorded_;
853 int frames_processed_;
854 int dropped_frames_;
pbos14fe7082016-04-20 06:35:56 -0700855 int dropped_frames_before_first_encode_;
856 int dropped_frames_before_rendering_;
ivica5d6a06c2015-09-17 05:30:24 -0700857 int64_t last_render_time_;
858 uint32_t rtp_timestamp_delta_;
859
860 rtc::CriticalSection crit_;
861 std::deque<VideoFrame> frames_ GUARDED_BY(crit_);
nisse97f0b932016-05-26 09:44:40 -0700862 rtc::Optional<VideoFrame> last_rendered_frame_ GUARDED_BY(crit_);
sprange1f2f1f2016-02-01 02:04:52 -0800863 rtc::TimestampWrapAroundHandler wrap_handler_ GUARDED_BY(crit_);
864 std::map<int64_t, int64_t> send_times_ GUARDED_BY(crit_);
865 std::map<int64_t, int64_t> recv_times_ GUARDED_BY(crit_);
866 std::map<int64_t, size_t> encoded_frame_sizes_ GUARDED_BY(crit_);
ilnike67c59e2017-02-09 04:08:56 -0800867 rtc::Optional<uint32_t> first_send_timestamp_ GUARDED_BY(crit_);
ivica5d6a06c2015-09-17 05:30:24 -0700868 const double avg_psnr_threshold_;
869 const double avg_ssim_threshold_;
870
871 rtc::CriticalSection comparison_lock_;
Peter Boström8c38e8b2015-11-26 17:45:47 +0100872 std::vector<rtc::PlatformThread*> comparison_thread_pool_;
873 rtc::PlatformThread stats_polling_thread_;
Peter Boström5811a392015-12-10 13:02:50 +0100874 rtc::Event comparison_available_event_;
ivica5d6a06c2015-09-17 05:30:24 -0700875 std::deque<FrameComparison> comparisons_ GUARDED_BY(comparison_lock_);
Peter Boström5811a392015-12-10 13:02:50 +0100876 rtc::Event done_;
ivica5d6a06c2015-09-17 05:30:24 -0700877};
878
palmkviste75f2042016-09-28 06:19:48 -0700879VideoQualityTest::VideoQualityTest()
880 : clock_(Clock::GetRealTimeClock()), receive_logs_(0), send_logs_(0) {}
ivica5d6a06c2015-09-17 05:30:24 -0700881
minyue626bc952016-10-31 05:47:02 -0700882VideoQualityTest::Params::Params()
883 : call({false, Call::Config::BitrateConfig()}),
884 video({false, 640, 480, 30, 50, 800, 800, false, "VP8", 1, -1, 0, false,
brandtr1293aca2016-11-16 22:47:29 -0800885 false, "", ""}),
minyue626bc952016-10-31 05:47:02 -0700886 audio({false, false}),
887 screenshare({false, 10, 0}),
888 analyzer({"", 0.0, 0.0, 0, "", ""}),
889 pipe(),
890 logs(false),
891 ss({std::vector<VideoStream>(), 0, 0, -1, std::vector<SpatialLayer>()}) {}
892
893VideoQualityTest::Params::~Params() = default;
894
ivica5d6a06c2015-09-17 05:30:24 -0700895void VideoQualityTest::TestBody() {}
896
sprangce4aef12015-11-02 07:23:20 -0800897std::string VideoQualityTest::GenerateGraphTitle() const {
898 std::stringstream ss;
minyue626bc952016-10-31 05:47:02 -0700899 ss << params_.video.codec;
900 ss << " (" << params_.video.target_bitrate_bps / 1000 << "kbps";
901 ss << ", " << params_.video.fps << " FPS";
sprangce4aef12015-11-02 07:23:20 -0800902 if (params_.screenshare.scroll_duration)
903 ss << ", " << params_.screenshare.scroll_duration << "s scroll";
904 if (params_.ss.streams.size() > 1)
905 ss << ", Stream #" << params_.ss.selected_stream;
906 if (params_.ss.num_spatial_layers > 1)
907 ss << ", Layer #" << params_.ss.selected_sl;
908 ss << ")";
909 return ss.str();
910}
911
912void VideoQualityTest::CheckParams() {
stefan7de8d642017-02-07 07:14:08 -0800913 if (!params_.video.enabled)
914 return;
sprangce4aef12015-11-02 07:23:20 -0800915 // 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;
brandtr14742122017-01-27 04:53:07 -08001127 video_receive_configs_[i].rtp.rtx_ssrc = kSendRtxSsrcs[i];
1128 video_receive_configs_[i].rtp.rtx_payload_types[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;
kthelgason2bc68642017-02-07 07:02:22 -08001182 degradation_preference_ =
1183 VideoSendStream::DegradationPreference::kMaintainResolution;
minyue626bc952016-10-31 05:47:02 -07001184 if (params_.video.codec == "VP8") {
kthelgason29a44e32016-09-27 03:52:02 -07001185 VideoCodecVP8 vp8_settings = VideoEncoder::GetDefaultVp8Settings();
1186 vp8_settings.denoisingOn = false;
1187 vp8_settings.frameDroppingOn = false;
1188 vp8_settings.numberOfTemporalLayers =
minyue626bc952016-10-31 05:47:02 -07001189 static_cast<unsigned char>(params_.video.num_temporal_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001190 video_encoder_config_.encoder_specific_settings = new rtc::RefCountedObject<
1191 VideoEncoderConfig::Vp8EncoderSpecificSettings>(vp8_settings);
minyue626bc952016-10-31 05:47:02 -07001192 } else if (params_.video.codec == "VP9") {
kthelgason29a44e32016-09-27 03:52:02 -07001193 VideoCodecVP9 vp9_settings = VideoEncoder::GetDefaultVp9Settings();
1194 vp9_settings.denoisingOn = false;
1195 vp9_settings.frameDroppingOn = false;
1196 vp9_settings.numberOfTemporalLayers =
minyue626bc952016-10-31 05:47:02 -07001197 static_cast<unsigned char>(params_.video.num_temporal_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001198 vp9_settings.numberOfSpatialLayers =
sprangce4aef12015-11-02 07:23:20 -08001199 static_cast<unsigned char>(params_.ss.num_spatial_layers);
kthelgason29a44e32016-09-27 03:52:02 -07001200 video_encoder_config_.encoder_specific_settings = new rtc::RefCountedObject<
1201 VideoEncoderConfig::Vp9EncoderSpecificSettings>(vp9_settings);
ivica5d6a06c2015-09-17 05:30:24 -07001202 }
1203
1204 // Setup frame generator.
1205 const size_t kWidth = 1850;
1206 const size_t kHeight = 1110;
1207 std::vector<std::string> slides;
1208 slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
1209 slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
1210 slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
1211 slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));
1212
sprangce4aef12015-11-02 07:23:20 -08001213 if (params_.screenshare.scroll_duration == 0) {
ivica5d6a06c2015-09-17 05:30:24 -07001214 // Cycle image every slide_change_interval seconds.
1215 frame_generator_.reset(test::FrameGenerator::CreateFromYuvFile(
1216 slides, kWidth, kHeight,
minyue626bc952016-10-31 05:47:02 -07001217 params_.screenshare.slide_change_interval * params_.video.fps));
ivica5d6a06c2015-09-17 05:30:24 -07001218 } else {
minyue626bc952016-10-31 05:47:02 -07001219 RTC_CHECK_LE(params_.video.width, kWidth);
1220 RTC_CHECK_LE(params_.video.height, kHeight);
sprangce4aef12015-11-02 07:23:20 -08001221 RTC_CHECK_GT(params_.screenshare.slide_change_interval, 0);
1222 const int kPauseDurationMs = (params_.screenshare.slide_change_interval -
1223 params_.screenshare.scroll_duration) *
1224 1000;
1225 RTC_CHECK_LE(params_.screenshare.scroll_duration,
1226 params_.screenshare.slide_change_interval);
ivica5d6a06c2015-09-17 05:30:24 -07001227
sprangce4aef12015-11-02 07:23:20 -08001228 frame_generator_.reset(
1229 test::FrameGenerator::CreateScrollingInputFromYuvFiles(
minyue626bc952016-10-31 05:47:02 -07001230 clock_, slides, kWidth, kHeight, params_.video.width,
1231 params_.video.height, params_.screenshare.scroll_duration * 1000,
sprangce4aef12015-11-02 07:23:20 -08001232 kPauseDurationMs));
ivica5d6a06c2015-09-17 05:30:24 -07001233 }
1234}
1235
perkja49cbd32016-09-16 07:53:41 -07001236void VideoQualityTest::CreateCapturer() {
sprangce4aef12015-11-02 07:23:20 -08001237 if (params_.screenshare.enabled) {
1238 test::FrameGeneratorCapturer* frame_generator_capturer =
perkja49cbd32016-09-16 07:53:41 -07001239 new test::FrameGeneratorCapturer(clock_, frame_generator_.release(),
minyue626bc952016-10-31 05:47:02 -07001240 params_.video.fps);
ivica2d4e6c52015-09-23 01:57:06 -07001241 EXPECT_TRUE(frame_generator_capturer->Init());
minyuea27172d2016-11-01 05:59:29 -07001242 video_capturer_.reset(frame_generator_capturer);
ivica5d6a06c2015-09-17 05:30:24 -07001243 } else {
sprangce4aef12015-11-02 07:23:20 -08001244 if (params_.video.clip_name.empty()) {
minyuea27172d2016-11-01 05:59:29 -07001245 video_capturer_.reset(test::VcmCapturer::Create(
minyue626bc952016-10-31 05:47:02 -07001246 params_.video.width, params_.video.height, params_.video.fps));
sprang1bed2e42017-01-23 08:46:51 -08001247 if (!video_capturer_) {
1248 // Failed to get actual camera, use chroma generator as backup.
1249 video_capturer_.reset(test::FrameGeneratorCapturer::Create(
1250 params_.video.width, params_.video.height, params_.video.fps,
1251 clock_));
1252 }
ivica5d6a06c2015-09-17 05:30:24 -07001253 } else {
minyuea27172d2016-11-01 05:59:29 -07001254 video_capturer_.reset(test::FrameGeneratorCapturer::CreateFromYuvFile(
perkja49cbd32016-09-16 07:53:41 -07001255 test::ResourcePath(params_.video.clip_name, "yuv"),
minyue626bc952016-10-31 05:47:02 -07001256 params_.video.width, params_.video.height, params_.video.fps,
ivica2d4e6c52015-09-23 01:57:06 -07001257 clock_));
minyuea27172d2016-11-01 05:59:29 -07001258 ASSERT_TRUE(video_capturer_) << "Could not create capturer for "
1259 << params_.video.clip_name
1260 << ".yuv. Is this resource file present?";
ivica5d6a06c2015-09-17 05:30:24 -07001261 }
1262 }
sprang1bed2e42017-01-23 08:46:51 -08001263 RTC_DCHECK(video_capturer_.get());
ivica5d6a06c2015-09-17 05:30:24 -07001264}
1265
sprang7a975f72015-10-12 06:33:21 -07001266void VideoQualityTest::RunWithAnalyzer(const Params& params) {
sprangce4aef12015-11-02 07:23:20 -08001267 params_ = params;
1268
minyue626bc952016-10-31 05:47:02 -07001269 RTC_CHECK(!params_.audio.enabled);
ivica5d6a06c2015-09-17 05:30:24 -07001270 // TODO(ivica): Merge with RunWithRenderer and use a flag / argument to
1271 // differentiate between the analyzer and the renderer case.
sprangce4aef12015-11-02 07:23:20 -08001272 CheckParams();
ivica5d6a06c2015-09-17 05:30:24 -07001273
1274 FILE* graph_data_output_file = nullptr;
sprangce4aef12015-11-02 07:23:20 -08001275 if (!params_.analyzer.graph_data_output_filename.empty()) {
ivica5d6a06c2015-09-17 05:30:24 -07001276 graph_data_output_file =
sprangce4aef12015-11-02 07:23:20 -08001277 fopen(params_.analyzer.graph_data_output_filename.c_str(), "w");
Peter Boström74f6e9e2016-04-04 17:56:10 +02001278 RTC_CHECK(graph_data_output_file)
sprangce4aef12015-11-02 07:23:20 -08001279 << "Can't open the file " << params_.analyzer.graph_data_output_filename
1280 << "!";
ivica87f83a92015-10-08 05:13:32 -07001281 }
sprang7a975f72015-10-12 06:33:21 -07001282
skvlad11a9cbf2016-10-07 11:53:05 -07001283 webrtc::RtcEventLogNullImpl event_log;
1284 Call::Config call_config(&event_log_);
minyue626bc952016-10-31 05:47:02 -07001285 call_config.bitrate_config = params.call.call_bitrate_config;
stefanf116bd02015-10-27 08:29:42 -07001286 CreateCalls(call_config, call_config);
1287
ivica87f83a92015-10-08 05:13:32 -07001288 test::LayerFilteringTransport send_transport(
minyue626bc952016-10-31 05:47:02 -07001289 params_.pipe, sender_call_.get(), kPayloadTypeVP8, kPayloadTypeVP9,
1290 params_.video.selected_tl, params_.ss.selected_sl);
1291 test::DirectTransport recv_transport(params_.pipe, receiver_call_.get());
stefanf116bd02015-10-27 08:29:42 -07001292
sprangce4aef12015-11-02 07:23:20 -08001293 std::string graph_title = params_.analyzer.graph_title;
1294 if (graph_title.empty())
1295 graph_title = VideoQualityTest::GenerateGraphTitle();
1296
1297 // In the case of different resolutions, the functions calculating PSNR and
1298 // SSIM return -1.0, instead of a positive value as usual. VideoAnalyzer
1299 // aborts if the average psnr/ssim are below the given threshold, which is
1300 // 0.0 by default. Setting the thresholds to -1.1 prevents the unnecessary
1301 // abort.
1302 VideoStream& selected_stream = params_.ss.streams[params_.ss.selected_stream];
1303 int selected_sl = params_.ss.selected_sl != -1
1304 ? params_.ss.selected_sl
1305 : params_.ss.num_spatial_layers - 1;
1306 bool disable_quality_check =
minyue626bc952016-10-31 05:47:02 -07001307 selected_stream.width != params_.video.width ||
1308 selected_stream.height != params_.video.height ||
sprangce4aef12015-11-02 07:23:20 -08001309 (!params_.ss.spatial_layers.empty() &&
1310 params_.ss.spatial_layers[selected_sl].scaling_factor_num !=
1311 params_.ss.spatial_layers[selected_sl].scaling_factor_den);
1312 if (disable_quality_check) {
1313 fprintf(stderr,
1314 "Warning: Calculating PSNR and SSIM for downsized resolution "
ilnike67c59e2017-02-09 04:08:56 -08001315 "not implemented yet! Skipping PSNR and SSIM calculations!");
sprangce4aef12015-11-02 07:23:20 -08001316 }
1317
ivica5d6a06c2015-09-17 05:30:24 -07001318 VideoAnalyzer analyzer(
sprangce4aef12015-11-02 07:23:20 -08001319 &send_transport, params_.analyzer.test_label,
1320 disable_quality_check ? -1.1 : params_.analyzer.avg_psnr_threshold,
1321 disable_quality_check ? -1.1 : params_.analyzer.avg_ssim_threshold,
minyue626bc952016-10-31 05:47:02 -07001322 params_.analyzer.test_durations_secs * params_.video.fps,
sprangce4aef12015-11-02 07:23:20 -08001323 graph_data_output_file, graph_title,
ilnike67c59e2017-02-09 04:08:56 -08001324 kVideoSendSsrcs[params_.ss.selected_stream]);
ivica5d6a06c2015-09-17 05:30:24 -07001325
ivica5d6a06c2015-09-17 05:30:24 -07001326 analyzer.SetReceiver(receiver_call_->Receiver());
1327 send_transport.SetReceiver(&analyzer);
1328 recv_transport.SetReceiver(sender_call_->Receiver());
1329
minyuea27172d2016-11-01 05:59:29 -07001330 SetupVideo(&analyzer, &recv_transport);
stefanff483612015-12-21 03:14:00 -08001331 video_receive_configs_[params_.ss.selected_stream].renderer = &analyzer;
pbos14fe7082016-04-20 06:35:56 -07001332 video_send_config_.pre_encode_callback = analyzer.pre_encode_proxy();
stefanff483612015-12-21 03:14:00 -08001333 for (auto& config : video_receive_configs_)
ivica5d6a06c2015-09-17 05:30:24 -07001334 config.pre_decode_callback = &analyzer;
Peter Boströme4499152016-02-05 11:13:28 +01001335 RTC_DCHECK(!video_send_config_.post_encode_callback);
1336 video_send_config_.post_encode_callback = analyzer.encode_timing_proxy();
ivica5d6a06c2015-09-17 05:30:24 -07001337
sprangce4aef12015-11-02 07:23:20 -08001338 if (params_.screenshare.enabled)
1339 SetupScreenshare();
ivica5d6a06c2015-09-17 05:30:24 -07001340
brandtr1293aca2016-11-16 22:47:29 -08001341 CreateFlexfecStreams();
Stefan Holmer9fea80f2016-01-07 17:43:18 +01001342 CreateVideoStreams();
perkja49cbd32016-09-16 07:53:41 -07001343 analyzer.SetSendStream(video_send_stream_);
philipelfd870db2017-01-23 03:22:15 -08001344 if (video_receive_streams_.size() == 1)
1345 analyzer.SetReceiveStream(video_receive_streams_[0]);
kthelgason2bc68642017-02-07 07:02:22 -08001346
1347 video_send_stream_->SetSource(analyzer.OutputInterface(),
1348 degradation_preference_);
ivica5d6a06c2015-09-17 05:30:24 -07001349
perkja49cbd32016-09-16 07:53:41 -07001350 CreateCapturer();
1351 rtc::VideoSinkWants wants;
minyuea27172d2016-11-01 05:59:29 -07001352 video_capturer_->AddOrUpdateSink(analyzer.InputInterface(), wants);
ivicac1cc8542015-10-08 03:44:06 -07001353
palmkviste75f2042016-09-28 06:19:48 -07001354 StartEncodedFrameLogs(video_send_stream_);
1355 StartEncodedFrameLogs(video_receive_streams_[0]);
stefanff483612015-12-21 03:14:00 -08001356 video_send_stream_->Start();
1357 for (VideoReceiveStream* receive_stream : video_receive_streams_)
1358 receive_stream->Start();
brandtr1293aca2016-11-16 22:47:29 -08001359 for (FlexfecReceiveStream* receive_stream : flexfec_receive_streams_)
1360 receive_stream->Start();
minyuea27172d2016-11-01 05:59:29 -07001361 video_capturer_->Start();
ivica5d6a06c2015-09-17 05:30:24 -07001362
1363 analyzer.Wait();
1364
1365 send_transport.StopSending();
1366 recv_transport.StopSending();
1367
minyuea27172d2016-11-01 05:59:29 -07001368 video_capturer_->Stop();
brandtr1293aca2016-11-16 22:47:29 -08001369 for (FlexfecReceiveStream* receive_stream : flexfec_receive_streams_)
1370 receive_stream->Stop();
stefanff483612015-12-21 03:14:00 -08001371 for (VideoReceiveStream* receive_stream : video_receive_streams_)
1372 receive_stream->Stop();
1373 video_send_stream_->Stop();
ivica5d6a06c2015-09-17 05:30:24 -07001374
1375 DestroyStreams();
1376
1377 if (graph_data_output_file)
1378 fclose(graph_data_output_file);
1379}
1380
minyuea27172d2016-11-01 05:59:29 -07001381void VideoQualityTest::SetupAudio(int send_channel_id,
1382 int receive_channel_id,
1383 Call* call,
1384 Transport* transport,
1385 AudioReceiveStream** audio_receive_stream) {
1386 audio_send_config_ = AudioSendStream::Config(transport);
1387 audio_send_config_.voe_channel_id = send_channel_id;
1388 audio_send_config_.rtp.ssrc = kAudioSendSsrc;
1389
1390 // Add extension to enable audio send side BWE, and allow audio bit rate
1391 // adaptation.
1392 audio_send_config_.rtp.extensions.clear();
1393 if (params_.call.send_side_bwe) {
1394 audio_send_config_.rtp.extensions.push_back(
1395 webrtc::RtpExtension(webrtc::RtpExtension::kTransportSequenceNumberUri,
1396 test::kTransportSequenceNumberExtensionId));
minyue10cbb462016-11-07 09:29:22 -08001397 audio_send_config_.min_bitrate_bps = kOpusMinBitrateBps;
1398 audio_send_config_.max_bitrate_bps = kOpusBitrateFbBps;
minyuea27172d2016-11-01 05:59:29 -07001399 }
1400 audio_send_config_.send_codec_spec.codec_inst =
1401 CodecInst{120, "OPUS", 48000, 960, 2, 64000};
1402
1403 audio_send_stream_ = call->CreateAudioSendStream(audio_send_config_);
1404
1405 AudioReceiveStream::Config audio_config;
1406 audio_config.rtp.local_ssrc = kReceiverLocalAudioSsrc;
1407 audio_config.rtcp_send_transport = transport;
1408 audio_config.voe_channel_id = receive_channel_id;
1409 audio_config.rtp.remote_ssrc = audio_send_config_.rtp.ssrc;
1410 audio_config.rtp.transport_cc = params_.call.send_side_bwe;
1411 audio_config.rtp.extensions = audio_send_config_.rtp.extensions;
1412 audio_config.decoder_factory = decoder_factory_;
1413 if (params_.video.enabled && params_.audio.sync_video)
1414 audio_config.sync_group = kSyncGroup;
1415
1416 *audio_receive_stream = call->CreateAudioReceiveStream(audio_config);
1417}
1418
minyue73208662016-08-18 06:28:55 -07001419void VideoQualityTest::RunWithRenderers(const Params& params) {
sprangce4aef12015-11-02 07:23:20 -08001420 params_ = params;
1421 CheckParams();
ivica5d6a06c2015-09-17 05:30:24 -07001422
ivica5d6a06c2015-09-17 05:30:24 -07001423 // TODO(ivica): Remove bitrate_config and use the default Call::Config(), to
1424 // match the full stack tests.
skvlad11a9cbf2016-10-07 11:53:05 -07001425 webrtc::RtcEventLogNullImpl event_log;
1426 Call::Config call_config(&event_log_);
minyue626bc952016-10-31 05:47:02 -07001427 call_config.bitrate_config = params_.call.call_bitrate_config;
minyue73208662016-08-18 06:28:55 -07001428
1429 ::VoiceEngineState voe;
minyue626bc952016-10-31 05:47:02 -07001430 if (params_.audio.enabled) {
minyue73208662016-08-18 06:28:55 -07001431 CreateVoiceEngine(&voe, decoder_factory_);
1432 AudioState::Config audio_state_config;
1433 audio_state_config.voice_engine = voe.voice_engine;
aleloi10111bc2016-11-17 06:48:48 -08001434 audio_state_config.audio_mixer = AudioMixerImpl::Create();
minyue73208662016-08-18 06:28:55 -07001435 call_config.audio_state = AudioState::Create(audio_state_config);
1436 }
1437
kwiberg27f982b2016-03-01 11:52:33 -08001438 std::unique_ptr<Call> call(Call::Create(call_config));
ivica5d6a06c2015-09-17 05:30:24 -07001439
minyuea27172d2016-11-01 05:59:29 -07001440 // TODO(minyue): consider if this is a good transport even for audio only
1441 // calls.
ivica5d6a06c2015-09-17 05:30:24 -07001442 test::LayerFilteringTransport transport(
stefanf116bd02015-10-27 08:29:42 -07001443 params.pipe, call.get(), kPayloadTypeVP8, kPayloadTypeVP9,
minyue626bc952016-10-31 05:47:02 -07001444 params.video.selected_tl, params_.ss.selected_sl);
ivica5d6a06c2015-09-17 05:30:24 -07001445 // TODO(ivica): Use two calls to be able to merge with RunWithAnalyzer or at
1446 // least share as much code as possible. That way this test would also match
1447 // the full stack tests better.
1448 transport.SetReceiver(call->Receiver());
1449
minyuea27172d2016-11-01 05:59:29 -07001450 VideoReceiveStream* video_receive_stream = nullptr;
brandtr1293aca2016-11-16 22:47:29 -08001451 FlexfecReceiveStream* flexfec_receive_stream = nullptr;
minyuea27172d2016-11-01 05:59:29 -07001452 std::unique_ptr<test::VideoRenderer> local_preview;
1453 std::unique_ptr<test::VideoRenderer> loopback_video;
1454 if (params_.video.enabled) {
1455 // Create video renderers.
1456 local_preview.reset(test::VideoRenderer::Create(
1457 "Local Preview", params_.video.width, params_.video.height));
ivica87f83a92015-10-08 05:13:32 -07001458
minyuea27172d2016-11-01 05:59:29 -07001459 size_t stream_id = params_.ss.selected_stream;
1460 std::string title = "Loopback Video";
1461 if (params_.ss.streams.size() > 1) {
1462 std::ostringstream s;
1463 s << stream_id;
1464 title += " - Stream #" + s.str();
1465 }
sprangce4aef12015-11-02 07:23:20 -08001466
minyuea27172d2016-11-01 05:59:29 -07001467 loopback_video.reset(test::VideoRenderer::Create(
1468 title.c_str(), params_.ss.streams[stream_id].width,
1469 params_.ss.streams[stream_id].height));
mflodman48a4beb2016-07-01 13:03:59 +02001470
minyuea27172d2016-11-01 05:59:29 -07001471 SetupVideo(&transport, &transport);
minyuea27172d2016-11-01 05:59:29 -07001472 video_send_config_.pre_encode_callback = local_preview.get();
1473 video_receive_configs_[stream_id].renderer = loopback_video.get();
1474 if (params_.audio.enabled && params_.audio.sync_video)
1475 video_receive_configs_[stream_id].sync_group = kSyncGroup;
1476
minyuea27172d2016-11-01 05:59:29 -07001477 if (params_.screenshare.enabled)
1478 SetupScreenshare();
1479
1480 video_send_stream_ = call->CreateVideoSendStream(
1481 video_send_config_.Copy(), video_encoder_config_.Copy());
brandtr1293aca2016-11-16 22:47:29 -08001482 if (params_.video.flexfec) {
1483 RTC_DCHECK(!flexfec_receive_configs_.empty());
1484 flexfec_receive_stream =
1485 call->CreateFlexfecReceiveStream(flexfec_receive_configs_[0]);
1486 }
minyuea27172d2016-11-01 05:59:29 -07001487 video_receive_stream = call->CreateVideoReceiveStream(
1488 video_receive_configs_[stream_id].Copy());
1489 CreateCapturer();
kthelgason2bc68642017-02-07 07:02:22 -08001490 video_send_stream_->SetSource(video_capturer_.get(),
1491 degradation_preference_);
philipel274c1dc2016-05-04 06:21:01 -07001492 }
1493
minyue73208662016-08-18 06:28:55 -07001494 AudioReceiveStream* audio_receive_stream = nullptr;
minyue626bc952016-10-31 05:47:02 -07001495 if (params_.audio.enabled) {
minyuea27172d2016-11-01 05:59:29 -07001496 SetupAudio(voe.send_channel_id, voe.receive_channel_id, call.get(),
1497 &transport, &audio_receive_stream);
minyue73208662016-08-18 06:28:55 -07001498 }
1499
palmkviste75f2042016-09-28 06:19:48 -07001500 StartEncodedFrameLogs(video_receive_stream);
1501 StartEncodedFrameLogs(video_send_stream_);
1502
minyue73208662016-08-18 06:28:55 -07001503 // Start sending and receiving video.
minyuea27172d2016-11-01 05:59:29 -07001504 if (params_.video.enabled) {
brandtr1293aca2016-11-16 22:47:29 -08001505 if (flexfec_receive_stream)
1506 flexfec_receive_stream->Start();
minyuea27172d2016-11-01 05:59:29 -07001507 video_receive_stream->Start();
1508 video_send_stream_->Start();
1509 video_capturer_->Start();
1510 }
ivica5d6a06c2015-09-17 05:30:24 -07001511
minyue626bc952016-10-31 05:47:02 -07001512 if (params_.audio.enabled) {
minyue73208662016-08-18 06:28:55 -07001513 // Start receiving audio.
1514 audio_receive_stream->Start();
1515 EXPECT_EQ(0, voe.base->StartPlayout(voe.receive_channel_id));
minyue73208662016-08-18 06:28:55 -07001516
1517 // Start sending audio.
1518 audio_send_stream_->Start();
1519 EXPECT_EQ(0, voe.base->StartSend(voe.send_channel_id));
1520 }
1521
ivica5d6a06c2015-09-17 05:30:24 -07001522 test::PressEnterToContinue();
1523
minyue626bc952016-10-31 05:47:02 -07001524 if (params_.audio.enabled) {
minyue73208662016-08-18 06:28:55 -07001525 // Stop sending audio.
1526 EXPECT_EQ(0, voe.base->StopSend(voe.send_channel_id));
1527 audio_send_stream_->Stop();
1528
1529 // Stop receiving audio.
minyue73208662016-08-18 06:28:55 -07001530 EXPECT_EQ(0, voe.base->StopPlayout(voe.receive_channel_id));
1531 audio_receive_stream->Stop();
minyuea27172d2016-11-01 05:59:29 -07001532 call->DestroyAudioSendStream(audio_send_stream_);
1533 call->DestroyAudioReceiveStream(audio_receive_stream);
minyue73208662016-08-18 06:28:55 -07001534 }
1535
1536 // Stop receiving and sending video.
minyuea27172d2016-11-01 05:59:29 -07001537 if (params_.video.enabled) {
1538 video_capturer_->Stop();
1539 video_send_stream_->Stop();
1540 video_receive_stream->Stop();
brandtr1293aca2016-11-16 22:47:29 -08001541 if (flexfec_receive_stream) {
1542 flexfec_receive_stream->Stop();
1543 call->DestroyFlexfecReceiveStream(flexfec_receive_stream);
1544 }
minyuea27172d2016-11-01 05:59:29 -07001545 call->DestroyVideoReceiveStream(video_receive_stream);
1546 call->DestroyVideoSendStream(video_send_stream_);
minyue73208662016-08-18 06:28:55 -07001547 }
1548
ivica5d6a06c2015-09-17 05:30:24 -07001549 transport.StopSending();
minyue626bc952016-10-31 05:47:02 -07001550 if (params_.audio.enabled)
minyue73208662016-08-18 06:28:55 -07001551 DestroyVoiceEngine(&voe);
ivica5d6a06c2015-09-17 05:30:24 -07001552}
1553
palmkviste75f2042016-09-28 06:19:48 -07001554void VideoQualityTest::StartEncodedFrameLogs(VideoSendStream* stream) {
minyue626bc952016-10-31 05:47:02 -07001555 if (!params_.video.encoded_frame_base_path.empty()) {
palmkviste75f2042016-09-28 06:19:48 -07001556 std::ostringstream str;
1557 str << send_logs_++;
1558 std::string prefix =
minyue626bc952016-10-31 05:47:02 -07001559 params_.video.encoded_frame_base_path + "." + str.str() + ".send.";
palmkviste75f2042016-09-28 06:19:48 -07001560 stream->EnableEncodedFrameRecording(
1561 std::vector<rtc::PlatformFile>(
1562 {rtc::CreatePlatformFile(prefix + "1.ivf"),
1563 rtc::CreatePlatformFile(prefix + "2.ivf"),
1564 rtc::CreatePlatformFile(prefix + "3.ivf")}),
1565 10000000);
1566 }
1567}
1568void VideoQualityTest::StartEncodedFrameLogs(VideoReceiveStream* stream) {
minyue626bc952016-10-31 05:47:02 -07001569 if (!params_.video.encoded_frame_base_path.empty()) {
palmkviste75f2042016-09-28 06:19:48 -07001570 std::ostringstream str;
1571 str << receive_logs_++;
1572 std::string path =
minyue626bc952016-10-31 05:47:02 -07001573 params_.video.encoded_frame_base_path + "." + str.str() + ".recv.ivf";
palmkviste75f2042016-09-28 06:19:48 -07001574 stream->EnableEncodedFrameRecording(rtc::CreatePlatformFile(path),
1575 10000000);
1576 }
1577}
1578
ivica5d6a06c2015-09-17 05:30:24 -07001579} // namespace webrtc