blob: c0f5754d0c48f92fefd879a43ee6f14cfaec2cec [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 */
10#include <stdio.h>
11
12#include <algorithm>
13#include <deque>
14#include <map>
15#include <vector>
16
17#include "testing/gtest/include/gtest/gtest.h"
18
19#include "webrtc/base/checks.h"
20#include "webrtc/base/format_macros.h"
21#include "webrtc/base/scoped_ptr.h"
22#include "webrtc/call.h"
23#include "webrtc/common_video/libyuv/include/webrtc_libyuv.h"
24#include "webrtc/modules/rtp_rtcp/interface/rtp_header_parser.h"
25#include "webrtc/system_wrappers/interface/cpu_info.h"
26#include "webrtc/test/layer_filtering_transport.h"
27#include "webrtc/test/run_loop.h"
28#include "webrtc/test/statistics.h"
29#include "webrtc/test/testsupport/fileutils.h"
30#include "webrtc/test/video_renderer.h"
31#include "webrtc/video/video_quality_test.h"
32
33namespace webrtc {
34
Erik Språng6b8d3552015-09-24 15:06:57 +020035static const int kTransportSeqExtensionId =
36 VideoQualityTest::kAbsSendTimeExtensionId + 1;
ivica5d6a06c2015-09-17 05:30:24 -070037static const int kSendStatsPollingIntervalMs = 1000;
38static const int kPayloadTypeVP8 = 123;
39static const int kPayloadTypeVP9 = 124;
40
41class VideoAnalyzer : public PacketReceiver,
pbos2d566682015-09-28 09:59:31 -070042 public Transport,
ivica5d6a06c2015-09-17 05:30:24 -070043 public VideoRenderer,
44 public VideoCaptureInput,
ivica8d15bd62015-10-07 02:43:12 -070045 public EncodedFrameObserver,
46 public EncodingTimeObserver {
ivica5d6a06c2015-09-17 05:30:24 -070047 public:
ivica8d15bd62015-10-07 02:43:12 -070048 VideoAnalyzer(Transport* transport,
ivica5d6a06c2015-09-17 05:30:24 -070049 const std::string& test_label,
50 double avg_psnr_threshold,
51 double avg_ssim_threshold,
52 int duration_frames,
53 FILE* graph_data_output_file)
ivica8d15bd62015-10-07 02:43:12 -070054 : input_(nullptr),
ivica5d6a06c2015-09-17 05:30:24 -070055 transport_(transport),
56 receiver_(nullptr),
57 send_stream_(nullptr),
58 test_label_(test_label),
59 graph_data_output_file_(graph_data_output_file),
60 frames_to_process_(duration_frames),
61 frames_recorded_(0),
62 frames_processed_(0),
63 dropped_frames_(0),
64 last_render_time_(0),
65 rtp_timestamp_delta_(0),
66 avg_psnr_threshold_(avg_psnr_threshold),
67 avg_ssim_threshold_(avg_ssim_threshold),
68 comparison_available_event_(EventWrapper::Create()),
69 done_(EventWrapper::Create()) {
70 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
71
72 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
73 // so that we don't accidentally starve "real" worker threads (codec etc).
74 // Also, don't allocate more than kMaxComparisonThreads, even if there are
75 // spare cores.
76
77 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
78 RTC_DCHECK_GE(num_cores, 1u);
79 static const uint32_t kMinCoresLeft = 4;
80 static const uint32_t kMaxComparisonThreads = 8;
81
82 if (num_cores <= kMinCoresLeft) {
83 num_cores = 1;
84 } else {
85 num_cores -= kMinCoresLeft;
86 num_cores = std::min(num_cores, kMaxComparisonThreads);
87 }
88
89 for (uint32_t i = 0; i < num_cores; ++i) {
90 rtc::scoped_ptr<ThreadWrapper> thread =
91 ThreadWrapper::CreateThread(&FrameComparisonThread, this, "Analyzer");
92 EXPECT_TRUE(thread->Start());
93 comparison_thread_pool_.push_back(thread.release());
94 }
95
96 stats_polling_thread_ =
97 ThreadWrapper::CreateThread(&PollStatsThread, this, "StatsPoller");
98 EXPECT_TRUE(stats_polling_thread_->Start());
99 }
100
101 ~VideoAnalyzer() {
102 for (ThreadWrapper* thread : comparison_thread_pool_) {
103 EXPECT_TRUE(thread->Stop());
104 delete thread;
105 }
106 }
107
108 virtual void SetReceiver(PacketReceiver* receiver) { receiver_ = receiver; }
109
110 DeliveryStatus DeliverPacket(MediaType media_type,
111 const uint8_t* packet,
112 size_t length,
113 const PacketTime& packet_time) override {
114 rtc::scoped_ptr<RtpHeaderParser> parser(RtpHeaderParser::Create());
115 RTPHeader header;
116 parser->Parse(packet, length, &header);
117 {
118 rtc::CritScope lock(&crit_);
119 recv_times_[header.timestamp - rtp_timestamp_delta_] =
120 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
121 }
122
123 return receiver_->DeliverPacket(media_type, packet, length, packet_time);
124 }
125
ivica8d15bd62015-10-07 02:43:12 -0700126 // EncodingTimeObserver.
127 void OnReportEncodedTime(int64_t ntp_time_ms, int encode_time_ms) override {
128 rtc::CritScope crit(&comparison_lock_);
129 samples_encode_time_ms_[ntp_time_ms] = encode_time_ms;
130 }
131
ivica5d6a06c2015-09-17 05:30:24 -0700132 void IncomingCapturedFrame(const VideoFrame& video_frame) override {
133 VideoFrame copy = video_frame;
134 copy.set_timestamp(copy.ntp_time_ms() * 90);
135
136 {
137 rtc::CritScope lock(&crit_);
138 if (first_send_frame_.IsZeroSize() && rtp_timestamp_delta_ == 0)
139 first_send_frame_ = copy;
140
141 frames_.push_back(copy);
142 }
143
144 input_->IncomingCapturedFrame(video_frame);
145 }
146
stefan1d8a5062015-10-02 03:39:33 -0700147 bool SendRtp(const uint8_t* packet,
148 size_t length,
149 const PacketOptions& options) override {
ivica5d6a06c2015-09-17 05:30:24 -0700150 rtc::scoped_ptr<RtpHeaderParser> parser(RtpHeaderParser::Create());
151 RTPHeader header;
152 parser->Parse(packet, length, &header);
153
154 {
155 rtc::CritScope lock(&crit_);
156 if (rtp_timestamp_delta_ == 0) {
157 rtp_timestamp_delta_ = header.timestamp - first_send_frame_.timestamp();
158 first_send_frame_.Reset();
159 }
160 uint32_t timestamp = header.timestamp - rtp_timestamp_delta_;
161 send_times_[timestamp] =
162 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
163 encoded_frame_sizes_[timestamp] +=
164 length - (header.headerLength + header.paddingLength);
165 }
166
stefan1d8a5062015-10-02 03:39:33 -0700167 return transport_->SendRtp(packet, length, options);
ivica5d6a06c2015-09-17 05:30:24 -0700168 }
169
170 bool SendRtcp(const uint8_t* packet, size_t length) override {
171 return transport_->SendRtcp(packet, length);
172 }
173
174 void EncodedFrameCallback(const EncodedFrame& frame) override {
175 rtc::CritScope lock(&comparison_lock_);
176 if (frames_recorded_ < frames_to_process_)
177 encoded_frame_size_.AddSample(frame.length_);
178 }
179
180 void RenderFrame(const VideoFrame& video_frame,
181 int time_to_render_ms) override {
182 int64_t render_time_ms =
183 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
184 uint32_t send_timestamp = video_frame.timestamp() - rtp_timestamp_delta_;
185
186 rtc::CritScope lock(&crit_);
187
188 while (frames_.front().timestamp() < send_timestamp) {
189 AddFrameComparison(frames_.front(), last_rendered_frame_, true,
190 render_time_ms);
191 frames_.pop_front();
192 }
193
194 VideoFrame reference_frame = frames_.front();
195 frames_.pop_front();
196 assert(!reference_frame.IsZeroSize());
197 EXPECT_EQ(reference_frame.timestamp(), send_timestamp);
198 assert(reference_frame.timestamp() == send_timestamp);
199
200 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
201
202 last_rendered_frame_ = video_frame;
203 }
204
205 bool IsTextureSupported() const override { return false; }
206
207 void Wait() {
208 // Frame comparisons can be very expensive. Wait for test to be done, but
209 // at time-out check if frames_processed is going up. If so, give it more
210 // time, otherwise fail. Hopefully this will reduce test flakiness.
211
212 int last_frames_processed = -1;
213 EventTypeWrapper eventType;
214 int iteration = 0;
215 while ((eventType = done_->Wait(VideoQualityTest::kDefaultTimeoutMs)) !=
216 kEventSignaled) {
217 int frames_processed;
218 {
219 rtc::CritScope crit(&comparison_lock_);
220 frames_processed = frames_processed_;
221 }
222
223 // Print some output so test infrastructure won't think we've crashed.
224 const char* kKeepAliveMessages[3] = {
225 "Uh, I'm-I'm not quite dead, sir.",
226 "Uh, I-I think uh, I could pull through, sir.",
227 "Actually, I think I'm all right to come with you--"};
228 printf("- %s\n", kKeepAliveMessages[iteration++ % 3]);
229
230 if (last_frames_processed == -1) {
231 last_frames_processed = frames_processed;
232 continue;
233 }
234 ASSERT_GT(frames_processed, last_frames_processed)
235 << "Analyzer stalled while waiting for test to finish.";
236 last_frames_processed = frames_processed;
237 }
238
239 if (iteration > 0)
240 printf("- Farewell, sweet Concorde!\n");
241
242 // Signal stats polling thread if that is still waiting and stop it now,
243 // since it uses the send_stream_ reference that might be reclaimed after
244 // returning from this method.
245 done_->Set();
246 EXPECT_TRUE(stats_polling_thread_->Stop());
247 }
248
249 VideoCaptureInput* input_;
250 Transport* transport_;
251 PacketReceiver* receiver_;
252 VideoSendStream* send_stream_;
253
254 private:
255 struct FrameComparison {
256 FrameComparison()
257 : dropped(false),
258 send_time_ms(0),
259 recv_time_ms(0),
260 render_time_ms(0),
261 encoded_frame_size(0) {}
262
263 FrameComparison(const VideoFrame& reference,
264 const VideoFrame& render,
265 bool dropped,
266 int64_t send_time_ms,
267 int64_t recv_time_ms,
268 int64_t render_time_ms,
269 size_t encoded_frame_size)
270 : reference(reference),
271 render(render),
272 dropped(dropped),
273 send_time_ms(send_time_ms),
274 recv_time_ms(recv_time_ms),
275 render_time_ms(render_time_ms),
276 encoded_frame_size(encoded_frame_size) {}
277
278 VideoFrame reference;
279 VideoFrame render;
280 bool dropped;
281 int64_t send_time_ms;
282 int64_t recv_time_ms;
283 int64_t render_time_ms;
284 size_t encoded_frame_size;
285 };
286
287 struct Sample {
ivica8d15bd62015-10-07 02:43:12 -0700288 Sample(int dropped,
289 int64_t input_time_ms,
290 int64_t send_time_ms,
291 int64_t recv_time_ms,
292 int64_t render_time_ms,
293 size_t encoded_frame_size,
ivica5d6a06c2015-09-17 05:30:24 -0700294 double psnr,
ivica8d15bd62015-10-07 02:43:12 -0700295 double ssim)
ivica5d6a06c2015-09-17 05:30:24 -0700296 : dropped(dropped),
297 input_time_ms(input_time_ms),
298 send_time_ms(send_time_ms),
299 recv_time_ms(recv_time_ms),
ivica8d15bd62015-10-07 02:43:12 -0700300 render_time_ms(render_time_ms),
ivica5d6a06c2015-09-17 05:30:24 -0700301 encoded_frame_size(encoded_frame_size),
302 psnr(psnr),
ivica8d15bd62015-10-07 02:43:12 -0700303 ssim(ssim) {}
ivica5d6a06c2015-09-17 05:30:24 -0700304
ivica8d15bd62015-10-07 02:43:12 -0700305 int dropped;
306 int64_t input_time_ms;
307 int64_t send_time_ms;
308 int64_t recv_time_ms;
309 int64_t render_time_ms;
310 size_t encoded_frame_size;
ivica5d6a06c2015-09-17 05:30:24 -0700311 double psnr;
312 double ssim;
ivica5d6a06c2015-09-17 05:30:24 -0700313 };
314
315 void AddFrameComparison(const VideoFrame& reference,
316 const VideoFrame& render,
317 bool dropped,
318 int64_t render_time_ms)
319 EXCLUSIVE_LOCKS_REQUIRED(crit_) {
320 int64_t send_time_ms = send_times_[reference.timestamp()];
321 send_times_.erase(reference.timestamp());
322 int64_t recv_time_ms = recv_times_[reference.timestamp()];
323 recv_times_.erase(reference.timestamp());
324
325 size_t encoded_size = encoded_frame_sizes_[reference.timestamp()];
326 encoded_frame_sizes_.erase(reference.timestamp());
327
328 VideoFrame reference_copy;
329 VideoFrame render_copy;
330 reference_copy.CopyFrame(reference);
331 render_copy.CopyFrame(render);
332
333 rtc::CritScope crit(&comparison_lock_);
334 comparisons_.push_back(FrameComparison(reference_copy, render_copy, dropped,
335 send_time_ms, recv_time_ms,
336 render_time_ms, encoded_size));
337 comparison_available_event_->Set();
338 }
339
340 static bool PollStatsThread(void* obj) {
341 return static_cast<VideoAnalyzer*>(obj)->PollStats();
342 }
343
344 bool PollStats() {
345 switch (done_->Wait(kSendStatsPollingIntervalMs)) {
346 case kEventSignaled:
347 case kEventError:
348 done_->Set(); // Make sure main thread is also signaled.
349 return false;
350 case kEventTimeout:
351 break;
352 default:
353 RTC_NOTREACHED();
354 }
355
356 VideoSendStream::Stats stats = send_stream_->GetStats();
357
358 rtc::CritScope crit(&comparison_lock_);
359 encode_frame_rate_.AddSample(stats.encode_frame_rate);
360 encode_time_ms.AddSample(stats.avg_encode_time_ms);
361 encode_usage_percent.AddSample(stats.encode_usage_percent);
362 media_bitrate_bps.AddSample(stats.media_bitrate_bps);
363
364 return true;
365 }
366
367 static bool FrameComparisonThread(void* obj) {
368 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
369 }
370
371 bool CompareFrames() {
372 if (AllFramesRecorded())
373 return false;
374
375 VideoFrame reference;
376 VideoFrame render;
377 FrameComparison comparison;
378
379 if (!PopComparison(&comparison)) {
380 // Wait until new comparison task is available, or test is done.
381 // If done, wake up remaining threads waiting.
382 comparison_available_event_->Wait(1000);
383 if (AllFramesRecorded()) {
384 comparison_available_event_->Set();
385 return false;
386 }
387 return true; // Try again.
388 }
389
390 PerformFrameComparison(comparison);
391
392 if (FrameProcessed()) {
393 PrintResults();
394 if (graph_data_output_file_)
395 PrintSamplesToFile();
396 done_->Set();
397 comparison_available_event_->Set();
398 return false;
399 }
400
401 return true;
402 }
403
404 bool PopComparison(FrameComparison* comparison) {
405 rtc::CritScope crit(&comparison_lock_);
406 // If AllFramesRecorded() is true, it means we have already popped
407 // frames_to_process_ frames from comparisons_, so there is no more work
408 // for this thread to be done. frames_processed_ might still be lower if
409 // all comparisons are not done, but those frames are currently being
410 // worked on by other threads.
411 if (comparisons_.empty() || AllFramesRecorded())
412 return false;
413
414 *comparison = comparisons_.front();
415 comparisons_.pop_front();
416
417 FrameRecorded();
418 return true;
419 }
420
421 // Increment counter for number of frames received for comparison.
422 void FrameRecorded() {
423 rtc::CritScope crit(&comparison_lock_);
424 ++frames_recorded_;
425 }
426
427 // Returns true if all frames to be compared have been taken from the queue.
428 bool AllFramesRecorded() {
429 rtc::CritScope crit(&comparison_lock_);
430 assert(frames_recorded_ <= frames_to_process_);
431 return frames_recorded_ == frames_to_process_;
432 }
433
434 // Increase count of number of frames processed. Returns true if this was the
435 // last frame to be processed.
436 bool FrameProcessed() {
437 rtc::CritScope crit(&comparison_lock_);
438 ++frames_processed_;
439 assert(frames_processed_ <= frames_to_process_);
440 return frames_processed_ == frames_to_process_;
441 }
442
443 void PrintResults() {
444 rtc::CritScope crit(&comparison_lock_);
445 PrintResult("psnr", psnr_, " dB");
446 PrintResult("ssim", ssim_, "");
447 PrintResult("sender_time", sender_time_, " ms");
448 printf("RESULT dropped_frames: %s = %d frames\n", test_label_.c_str(),
449 dropped_frames_);
450 PrintResult("receiver_time", receiver_time_, " ms");
451 PrintResult("total_delay_incl_network", end_to_end_, " ms");
452 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
453 PrintResult("encoded_frame_size", encoded_frame_size_, " bytes");
454 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
455 PrintResult("encode_time", encode_time_ms, " ms");
456 PrintResult("encode_usage_percent", encode_usage_percent, " percent");
457 PrintResult("media_bitrate", media_bitrate_bps, " bps");
458
459 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
460 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
461 }
462
463 void PerformFrameComparison(const FrameComparison& comparison) {
464 // Perform expensive psnr and ssim calculations while not holding lock.
465 double psnr = I420PSNR(&comparison.reference, &comparison.render);
466 double ssim = I420SSIM(&comparison.reference, &comparison.render);
467
468 int64_t input_time_ms = comparison.reference.ntp_time_ms();
469
470 rtc::CritScope crit(&comparison_lock_);
471 if (graph_data_output_file_) {
472 samples_.push_back(
473 Sample(comparison.dropped, input_time_ms, comparison.send_time_ms,
ivica8d15bd62015-10-07 02:43:12 -0700474 comparison.recv_time_ms, comparison.render_time_ms,
475 comparison.encoded_frame_size, psnr, ssim));
ivica5d6a06c2015-09-17 05:30:24 -0700476 }
477 psnr_.AddSample(psnr);
478 ssim_.AddSample(ssim);
479
480 if (comparison.dropped) {
481 ++dropped_frames_;
482 return;
483 }
484 if (last_render_time_ != 0)
485 rendered_delta_.AddSample(comparison.render_time_ms - last_render_time_);
486 last_render_time_ = comparison.render_time_ms;
487
488 sender_time_.AddSample(comparison.send_time_ms - input_time_ms);
489 receiver_time_.AddSample(comparison.render_time_ms -
490 comparison.recv_time_ms);
491 end_to_end_.AddSample(comparison.render_time_ms - input_time_ms);
492 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
493 }
494
495 void PrintResult(const char* result_type,
496 test::Statistics stats,
497 const char* unit) {
498 printf("RESULT %s: %s = {%f, %f}%s\n",
499 result_type,
500 test_label_.c_str(),
501 stats.Mean(),
502 stats.StandardDeviation(),
503 unit);
504 }
505
506 void PrintSamplesToFile(void) {
507 FILE* out = graph_data_output_file_;
508 rtc::CritScope crit(&comparison_lock_);
509 std::sort(samples_.begin(), samples_.end(),
510 [](const Sample& A, const Sample& B) -> bool {
511 return A.input_time_ms < B.input_time_ms;
512 });
513
514 fprintf(out, "%s\n", test_label_.c_str());
515 fprintf(out, "%" PRIuS "\n", samples_.size());
516 fprintf(out,
517 "dropped "
518 "input_time_ms "
519 "send_time_ms "
520 "recv_time_ms "
ivica8d15bd62015-10-07 02:43:12 -0700521 "render_time_ms "
ivica5d6a06c2015-09-17 05:30:24 -0700522 "encoded_frame_size "
523 "psnr "
524 "ssim "
ivica8d15bd62015-10-07 02:43:12 -0700525 "encode_time_ms\n");
526 int missing_encode_time_samples = 0;
ivica5d6a06c2015-09-17 05:30:24 -0700527 for (const Sample& sample : samples_) {
ivica8d15bd62015-10-07 02:43:12 -0700528 auto it = samples_encode_time_ms_.find(sample.input_time_ms);
529 int encode_time_ms;
530 if (it != samples_encode_time_ms_.end()) {
531 encode_time_ms = it->second;
532 } else {
533 ++missing_encode_time_samples;
534 encode_time_ms = -1;
535 }
536 fprintf(out, "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
537 " %lf %lf %d\n",
538 sample.dropped, sample.input_time_ms, sample.send_time_ms,
539 sample.recv_time_ms, sample.render_time_ms,
ivica5d6a06c2015-09-17 05:30:24 -0700540 sample.encoded_frame_size, sample.psnr, sample.ssim,
ivica8d15bd62015-10-07 02:43:12 -0700541 encode_time_ms);
542 }
543 if (missing_encode_time_samples) {
544 fprintf(stderr,
545 "Warning: Missing encode_time_ms samples for %d frame(s).\n",
546 missing_encode_time_samples);
ivica5d6a06c2015-09-17 05:30:24 -0700547 }
548 }
549
550 const std::string test_label_;
551 FILE* const graph_data_output_file_;
552 std::vector<Sample> samples_ GUARDED_BY(comparison_lock_);
ivica8d15bd62015-10-07 02:43:12 -0700553 std::map<int64_t, int> samples_encode_time_ms_ GUARDED_BY(comparison_lock_);
ivica5d6a06c2015-09-17 05:30:24 -0700554 test::Statistics sender_time_ GUARDED_BY(comparison_lock_);
555 test::Statistics receiver_time_ GUARDED_BY(comparison_lock_);
556 test::Statistics psnr_ GUARDED_BY(comparison_lock_);
557 test::Statistics ssim_ GUARDED_BY(comparison_lock_);
558 test::Statistics end_to_end_ GUARDED_BY(comparison_lock_);
559 test::Statistics rendered_delta_ GUARDED_BY(comparison_lock_);
560 test::Statistics encoded_frame_size_ GUARDED_BY(comparison_lock_);
561 test::Statistics encode_frame_rate_ GUARDED_BY(comparison_lock_);
562 test::Statistics encode_time_ms GUARDED_BY(comparison_lock_);
563 test::Statistics encode_usage_percent GUARDED_BY(comparison_lock_);
564 test::Statistics media_bitrate_bps GUARDED_BY(comparison_lock_);
565
566 const int frames_to_process_;
567 int frames_recorded_;
568 int frames_processed_;
569 int dropped_frames_;
570 int64_t last_render_time_;
571 uint32_t rtp_timestamp_delta_;
572
573 rtc::CriticalSection crit_;
574 std::deque<VideoFrame> frames_ GUARDED_BY(crit_);
575 VideoFrame last_rendered_frame_ GUARDED_BY(crit_);
576 std::map<uint32_t, int64_t> send_times_ GUARDED_BY(crit_);
577 std::map<uint32_t, int64_t> recv_times_ GUARDED_BY(crit_);
578 std::map<uint32_t, size_t> encoded_frame_sizes_ GUARDED_BY(crit_);
579 VideoFrame first_send_frame_ GUARDED_BY(crit_);
580 const double avg_psnr_threshold_;
581 const double avg_ssim_threshold_;
582
583 rtc::CriticalSection comparison_lock_;
584 std::vector<ThreadWrapper*> comparison_thread_pool_;
585 rtc::scoped_ptr<ThreadWrapper> stats_polling_thread_;
586 const rtc::scoped_ptr<EventWrapper> comparison_available_event_;
587 std::deque<FrameComparison> comparisons_ GUARDED_BY(comparison_lock_);
588 const rtc::scoped_ptr<EventWrapper> done_;
589};
590
591VideoQualityTest::VideoQualityTest() : clock_(Clock::GetRealTimeClock()) {}
592
593void VideoQualityTest::ValidateParams(const Params& params) {
594 RTC_CHECK_GE(params.common.max_bitrate_bps, params.common.target_bitrate_bps);
595 RTC_CHECK_GE(params.common.target_bitrate_bps, params.common.min_bitrate_bps);
596 RTC_CHECK_LT(params.common.tl_discard_threshold,
597 params.common.num_temporal_layers);
598}
599
600void VideoQualityTest::TestBody() {}
601
602void VideoQualityTest::SetupFullStack(const Params& params,
pbos2d566682015-09-28 09:59:31 -0700603 Transport* send_transport,
604 Transport* recv_transport) {
ivica5d6a06c2015-09-17 05:30:24 -0700605 if (params.logs)
606 trace_to_stderr_.reset(new test::TraceToStderr);
607
608 CreateSendConfig(1, send_transport);
609
610 int payload_type;
611 if (params.common.codec == "VP8") {
612 encoder_.reset(VideoEncoder::Create(VideoEncoder::kVp8));
613 payload_type = kPayloadTypeVP8;
614 } else if (params.common.codec == "VP9") {
615 encoder_.reset(VideoEncoder::Create(VideoEncoder::kVp9));
616 payload_type = kPayloadTypeVP9;
617 } else {
618 RTC_NOTREACHED() << "Codec not supported!";
619 return;
620 }
621 send_config_.encoder_settings.encoder = encoder_.get();
622 send_config_.encoder_settings.payload_name = params.common.codec;
623 send_config_.encoder_settings.payload_type = payload_type;
624
625 send_config_.rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
626 send_config_.rtp.rtx.ssrcs.push_back(kSendRtxSsrcs[0]);
627 send_config_.rtp.rtx.payload_type = kSendRtxPayloadType;
628
Erik Språng6b8d3552015-09-24 15:06:57 +0200629 send_config_.rtp.extensions.clear();
630 if (params.common.send_side_bwe) {
631 send_config_.rtp.extensions.push_back(RtpExtension(
632 RtpExtension::kTransportSequenceNumber, kTransportSeqExtensionId));
633 } else {
634 send_config_.rtp.extensions.push_back(
635 RtpExtension(RtpExtension::kAbsSendTime, kAbsSendTimeExtensionId));
636 }
637
ivica5d6a06c2015-09-17 05:30:24 -0700638 // Automatically fill out streams[0] with params.
639 VideoStream* stream = &encoder_config_.streams[0];
640 stream->width = params.common.width;
641 stream->height = params.common.height;
642 stream->min_bitrate_bps = params.common.min_bitrate_bps;
643 stream->target_bitrate_bps = params.common.target_bitrate_bps;
644 stream->max_bitrate_bps = params.common.max_bitrate_bps;
645 stream->max_framerate = static_cast<int>(params.common.fps);
646
647 stream->temporal_layer_thresholds_bps.clear();
648 if (params.common.num_temporal_layers > 1) {
649 stream->temporal_layer_thresholds_bps.push_back(stream->target_bitrate_bps);
650 }
651
652 CreateMatchingReceiveConfigs(recv_transport);
653
654 receive_configs_[0].rtp.nack.rtp_history_ms = kNackRtpHistoryMs;
655 receive_configs_[0].rtp.rtx[kSendRtxPayloadType].ssrc = kSendRtxSsrcs[0];
656 receive_configs_[0].rtp.rtx[kSendRtxPayloadType].payload_type =
657 kSendRtxPayloadType;
658
659 encoder_config_.min_transmit_bitrate_bps = params.common.min_transmit_bps;
660}
661
662void VideoQualityTest::SetupScreenshare(const Params& params) {
663 RTC_CHECK(params.screenshare.enabled);
664
665 // Fill out codec settings.
666 encoder_config_.content_type = VideoEncoderConfig::ContentType::kScreen;
667 if (params.common.codec == "VP8") {
668 codec_settings_.VP8 = VideoEncoder::GetDefaultVp8Settings();
669 codec_settings_.VP8.denoisingOn = false;
670 codec_settings_.VP8.frameDroppingOn = false;
671 codec_settings_.VP8.numberOfTemporalLayers =
672 static_cast<unsigned char>(params.common.num_temporal_layers);
673 encoder_config_.encoder_specific_settings = &codec_settings_.VP8;
674 } else if (params.common.codec == "VP9") {
675 codec_settings_.VP9 = VideoEncoder::GetDefaultVp9Settings();
676 codec_settings_.VP9.denoisingOn = false;
677 codec_settings_.VP9.frameDroppingOn = false;
678 codec_settings_.VP9.numberOfTemporalLayers =
679 static_cast<unsigned char>(params.common.num_temporal_layers);
680 encoder_config_.encoder_specific_settings = &codec_settings_.VP9;
681 }
682
683 // Setup frame generator.
684 const size_t kWidth = 1850;
685 const size_t kHeight = 1110;
686 std::vector<std::string> slides;
687 slides.push_back(test::ResourcePath("web_screenshot_1850_1110", "yuv"));
688 slides.push_back(test::ResourcePath("presentation_1850_1110", "yuv"));
689 slides.push_back(test::ResourcePath("photo_1850_1110", "yuv"));
690 slides.push_back(test::ResourcePath("difficult_photo_1850_1110", "yuv"));
691
692 if (params.screenshare.scroll_duration == 0) {
693 // Cycle image every slide_change_interval seconds.
694 frame_generator_.reset(test::FrameGenerator::CreateFromYuvFile(
695 slides, kWidth, kHeight,
696 params.screenshare.slide_change_interval * params.common.fps));
697 } else {
698 RTC_CHECK_LE(params.common.width, kWidth);
699 RTC_CHECK_LE(params.common.height, kHeight);
700 RTC_CHECK_GT(params.screenshare.slide_change_interval, 0);
701 const int kPauseDurationMs = (params.screenshare.slide_change_interval -
702 params.screenshare.scroll_duration) * 1000;
703 RTC_CHECK_LE(params.screenshare.scroll_duration,
704 params.screenshare.slide_change_interval);
705
ivicad4818e72015-09-22 05:47:27 -0700706 if (params.screenshare.scroll_duration) {
707 frame_generator_.reset(
708 test::FrameGenerator::CreateScrollingInputFromYuvFiles(
709 clock_, slides, kWidth, kHeight, params.common.width,
710 params.common.height, params.screenshare.scroll_duration * 1000,
711 kPauseDurationMs));
712 } else {
713 frame_generator_.reset(test::FrameGenerator::CreateFromYuvFile(
714 slides, kWidth, kHeight,
715 params.screenshare.slide_change_interval * params.common.fps));
716 }
ivica5d6a06c2015-09-17 05:30:24 -0700717 }
718}
719
720void VideoQualityTest::CreateCapturer(const Params& params,
721 VideoCaptureInput* input) {
722 if (params.screenshare.enabled) {
ivica2d4e6c52015-09-23 01:57:06 -0700723 test::FrameGeneratorCapturer *frame_generator_capturer =
724 new test::FrameGeneratorCapturer(
725 clock_, input, frame_generator_.release(), params.common.fps);
726 EXPECT_TRUE(frame_generator_capturer->Init());
727 capturer_.reset(frame_generator_capturer);
ivica5d6a06c2015-09-17 05:30:24 -0700728 } else {
729 if (params.video.clip_name.empty()) {
ivica2d4e6c52015-09-23 01:57:06 -0700730 capturer_.reset(test::VideoCapturer::Create(
ivica5d6a06c2015-09-17 05:30:24 -0700731 input, params.common.width, params.common.height, params.common.fps,
732 clock_));
ivica5d6a06c2015-09-17 05:30:24 -0700733 } else {
ivica2d4e6c52015-09-23 01:57:06 -0700734 capturer_.reset(test::FrameGeneratorCapturer::CreateFromYuvFile(
735 input, test::ResourcePath(params.video.clip_name, "yuv"),
736 params.common.width, params.common.height, params.common.fps,
737 clock_));
738 ASSERT_TRUE(capturer_.get() != nullptr)
ivica5d6a06c2015-09-17 05:30:24 -0700739 << "Could not create capturer for " << params.video.clip_name
740 << ".yuv. Is this resource file present?";
741 }
742 }
743}
744
745void VideoQualityTest::RunWithAnalyzer(const Params& params) {
746 // TODO(ivica): Merge with RunWithRenderer and use a flag / argument to
747 // differentiate between the analyzer and the renderer case.
748 ValidateParams(params);
749
750 FILE* graph_data_output_file = nullptr;
751 if (!params.analyzer.graph_data_output_filename.empty()) {
752 graph_data_output_file =
753 fopen(params.analyzer.graph_data_output_filename.c_str(), "w");
754 RTC_CHECK(graph_data_output_file != nullptr)
755 << "Can't open the file "
756 << params.analyzer.graph_data_output_filename << "!";
757 }
758
759 test::LayerFilteringTransport send_transport(
760 params.pipe, kPayloadTypeVP8, kPayloadTypeVP9,
761 static_cast<uint8_t>(params.common.tl_discard_threshold), 0);
762 test::DirectTransport recv_transport(params.pipe);
763 VideoAnalyzer analyzer(
ivica8d15bd62015-10-07 02:43:12 -0700764 &send_transport, params.analyzer.test_label,
ivica5d6a06c2015-09-17 05:30:24 -0700765 params.analyzer.avg_psnr_threshold, params.analyzer.avg_ssim_threshold,
766 params.analyzer.test_durations_secs * params.common.fps,
767 graph_data_output_file);
768
769 Call::Config call_config;
770 call_config.bitrate_config = params.common.call_bitrate_config;
771 CreateCalls(call_config, call_config);
772
773 analyzer.SetReceiver(receiver_call_->Receiver());
774 send_transport.SetReceiver(&analyzer);
775 recv_transport.SetReceiver(sender_call_->Receiver());
776
777 SetupFullStack(params, &analyzer, &recv_transport);
ivica8d15bd62015-10-07 02:43:12 -0700778 send_config_.encoding_time_observer = &analyzer;
ivica5d6a06c2015-09-17 05:30:24 -0700779 receive_configs_[0].renderer = &analyzer;
780 for (auto& config : receive_configs_)
781 config.pre_decode_callback = &analyzer;
782
783 if (params.screenshare.enabled)
784 SetupScreenshare(params);
785
786 CreateCapturer(params, &analyzer);
787
788 CreateStreams();
789 analyzer.input_ = send_stream_->Input();
790 analyzer.send_stream_ = send_stream_;
791
ivica2d4e6c52015-09-23 01:57:06 -0700792 send_stream_->Start();
793 for (size_t i = 0; i < receive_streams_.size(); ++i)
794 receive_streams_[i]->Start();
795 capturer_->Start();
ivica5d6a06c2015-09-17 05:30:24 -0700796
797 analyzer.Wait();
798
799 send_transport.StopSending();
800 recv_transport.StopSending();
801
ivica2d4e6c52015-09-23 01:57:06 -0700802 capturer_->Stop();
803 for (size_t i = 0; i < receive_streams_.size(); ++i)
804 receive_streams_[i]->Stop();
805 send_stream_->Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700806
807 DestroyStreams();
808
809 if (graph_data_output_file)
810 fclose(graph_data_output_file);
811}
812
813void VideoQualityTest::RunWithVideoRenderer(const Params& params) {
814 ValidateParams(params);
815
816 rtc::scoped_ptr<test::VideoRenderer> local_preview(
817 test::VideoRenderer::Create("Local Preview", params.common.width,
818 params.common.height));
819 rtc::scoped_ptr<test::VideoRenderer> loopback_video(
820 test::VideoRenderer::Create("Loopback Video", params.common.width,
821 params.common.height));
822
823 // TODO(ivica): Remove bitrate_config and use the default Call::Config(), to
824 // match the full stack tests.
825 Call::Config call_config;
826 call_config.bitrate_config = params.common.call_bitrate_config;
827 rtc::scoped_ptr<Call> call(Call::Create(call_config));
828
829 test::LayerFilteringTransport transport(
830 params.pipe, kPayloadTypeVP8, kPayloadTypeVP9,
831 static_cast<uint8_t>(params.common.tl_discard_threshold), 0);
832 // TODO(ivica): Use two calls to be able to merge with RunWithAnalyzer or at
833 // least share as much code as possible. That way this test would also match
834 // the full stack tests better.
835 transport.SetReceiver(call->Receiver());
836
837 SetupFullStack(params, &transport, &transport);
838 send_config_.local_renderer = local_preview.get();
839 receive_configs_[0].renderer = loopback_video.get();
840
841 if (params.screenshare.enabled)
842 SetupScreenshare(params);
843
844 send_stream_ = call->CreateVideoSendStream(send_config_, encoder_config_);
845 CreateCapturer(params, send_stream_->Input());
846
847 VideoReceiveStream* receive_stream =
848 call->CreateVideoReceiveStream(receive_configs_[0]);
849
850 receive_stream->Start();
851 send_stream_->Start();
ivica2d4e6c52015-09-23 01:57:06 -0700852 capturer_->Start();
ivica5d6a06c2015-09-17 05:30:24 -0700853
854 test::PressEnterToContinue();
855
ivica2d4e6c52015-09-23 01:57:06 -0700856 capturer_->Stop();
ivica5d6a06c2015-09-17 05:30:24 -0700857 send_stream_->Stop();
858 receive_stream->Stop();
859
860 call->DestroyVideoReceiveStream(receive_stream);
861 call->DestroyVideoSendStream(send_stream_);
862
863 transport.StopSending();
864}
865
866} // namespace webrtc