blob: 66c4db6de3a30d56b1d679c9f47ae688c12fe0c5 [file] [log] [blame]
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001/*
2 * Copyright 2018 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 "video/video_analyzer.h"
11
12#include <algorithm>
13#include <utility>
14
15#include "modules/rtp_rtcp/source/rtp_format.h"
16#include "modules/rtp_rtcp/source/rtp_utility.h"
17#include "rtc_base/cpu_time.h"
18#include "rtc_base/flags.h"
19#include "rtc_base/format_macros.h"
20#include "rtc_base/memory_usage.h"
21#include "rtc_base/pathutils.h"
22#include "system_wrappers/include/cpu_info.h"
23#include "test/call_test.h"
24#include "test/testsupport/frame_writer.h"
25#include "test/testsupport/perf_test.h"
26#include "test/testsupport/test_artifacts.h"
27
28DEFINE_bool(save_worst_frame,
29 false,
30 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
31 "test_artifacts_dir");
32
33namespace webrtc {
34namespace {
35constexpr int kSendStatsPollingIntervalMs = 1000;
36constexpr size_t kMaxComparisons = 10;
37
38bool IsFlexfec(int payload_type) {
39 return payload_type == test::CallTest::kFlexfecPayloadType;
40}
41} // namespace
42
43VideoAnalyzer::VideoAnalyzer(test::LayerFilteringTransport* transport,
44 const std::string& test_label,
45 double avg_psnr_threshold,
46 double avg_ssim_threshold,
47 int duration_frames,
48 FILE* graph_data_output_file,
49 const std::string& graph_title,
50 uint32_t ssrc_to_analyze,
51 uint32_t rtx_ssrc_to_analyze,
52 size_t selected_stream,
53 int selected_sl,
54 int selected_tl,
55 bool is_quick_test_enabled,
56 Clock* clock,
57 std::string rtp_dump_name)
58 : transport_(transport),
59 receiver_(nullptr),
60 call_(nullptr),
61 send_stream_(nullptr),
62 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 14:10:56 +020063 audio_receive_stream_(nullptr),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020064 captured_frame_forwarder_(this, clock),
65 test_label_(test_label),
66 graph_data_output_file_(graph_data_output_file),
67 graph_title_(graph_title),
68 ssrc_to_analyze_(ssrc_to_analyze),
69 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
70 selected_stream_(selected_stream),
71 selected_sl_(selected_sl),
72 selected_tl_(selected_tl),
73 pre_encode_proxy_(this),
74 last_fec_bytes_(0),
75 frames_to_process_(duration_frames),
76 frames_recorded_(0),
77 frames_processed_(0),
78 dropped_frames_(0),
79 dropped_frames_before_first_encode_(0),
80 dropped_frames_before_rendering_(0),
81 last_render_time_(0),
82 last_render_delta_ms_(0),
83 last_unfreeze_time_ms_(0),
84 rtp_timestamp_delta_(0),
85 total_media_bytes_(0),
86 first_sending_time_(0),
87 last_sending_time_(0),
88 cpu_time_(0),
89 wallclock_time_(0),
90 avg_psnr_threshold_(avg_psnr_threshold),
91 avg_ssim_threshold_(avg_ssim_threshold),
92 is_quick_test_enabled_(is_quick_test_enabled),
93 stats_polling_thread_(&PollStatsThread, this, "StatsPoller"),
94 comparison_available_event_(false, false),
95 done_(true, false),
96 clock_(clock),
97 start_ms_(clock->TimeInMilliseconds()) {
98 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
99
100 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
101 // so that we don't accidentally starve "real" worker threads (codec etc).
102 // Also, don't allocate more than kMaxComparisonThreads, even if there are
103 // spare cores.
104
105 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
106 RTC_DCHECK_GE(num_cores, 1);
107 static const uint32_t kMinCoresLeft = 4;
108 static const uint32_t kMaxComparisonThreads = 8;
109
110 if (num_cores <= kMinCoresLeft) {
111 num_cores = 1;
112 } else {
113 num_cores -= kMinCoresLeft;
114 num_cores = std::min(num_cores, kMaxComparisonThreads);
115 }
116
117 for (uint32_t i = 0; i < num_cores; ++i) {
118 rtc::PlatformThread* thread =
119 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
120 thread->Start();
121 comparison_thread_pool_.push_back(thread);
122 }
123
124 if (!rtp_dump_name.empty()) {
125 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
126 rtp_file_writer_.reset(test::RtpFileWriter::Create(
127 test::RtpFileWriter::kRtpDump, rtp_dump_name));
128 }
129}
130
131VideoAnalyzer::~VideoAnalyzer() {
132 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
133 thread->Stop();
134 delete thread;
135 }
136}
137
138void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
139 receiver_ = receiver;
140}
141
142void VideoAnalyzer::SetSource(test::VideoCapturer* video_capturer,
143 bool respect_sink_wants) {
144 if (respect_sink_wants)
145 captured_frame_forwarder_.SetSource(video_capturer);
146 rtc::VideoSinkWants wants;
147 video_capturer->AddOrUpdateSink(InputInterface(), wants);
148}
149
150void VideoAnalyzer::SetCall(Call* call) {
151 rtc::CritScope lock(&crit_);
152 RTC_DCHECK(!call_);
153 call_ = call;
154}
155
156void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
157 rtc::CritScope lock(&crit_);
158 RTC_DCHECK(!send_stream_);
159 send_stream_ = stream;
160}
161
162void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
163 rtc::CritScope lock(&crit_);
164 RTC_DCHECK(!receive_stream_);
165 receive_stream_ = stream;
166}
167
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200168void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
169 rtc::CritScope lock(&crit_);
170 RTC_CHECK(!audio_receive_stream_);
171 audio_receive_stream_ = recv_stream;
172}
173
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200174rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
175 return &captured_frame_forwarder_;
176}
177
178rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
179 return &captured_frame_forwarder_;
180}
181
182PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
183 MediaType media_type,
184 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 11:03:12 +0200185 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200186 // Ignore timestamps of RTCP packets. They're not synchronized with
187 // RTP packet timestamps and so they would confuse wrap_handler_.
188 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
Niels Möller70082872018-08-07 11:03:12 +0200189 return receiver_->DeliverPacket(media_type, std::move(packet),
190 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200191 }
192
193 if (rtp_file_writer_) {
194 test::RtpPacket p;
195 memcpy(p.data, packet.cdata(), packet.size());
196 p.length = packet.size();
197 p.original_length = packet.size();
198 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
199 rtp_file_writer_->WritePacket(&p);
200 }
201
202 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
203 RTPHeader header;
204 parser.Parse(&header);
205 if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
206 header.ssrc == rtx_ssrc_to_analyze_)) {
207 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
208 // (FlexFEC and media are sent on different SSRCs, which have different
209 // timestamps spaces.)
210 // Also ignore packets from wrong SSRC, but include retransmits.
211 rtc::CritScope lock(&crit_);
212 int64_t timestamp =
213 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
214 recv_times_[timestamp] =
215 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
216 }
217
Niels Möller70082872018-08-07 11:03:12 +0200218 return receiver_->DeliverPacket(media_type, std::move(packet),
219 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200220}
221
222void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
223 rtc::CritScope lock(&crit_);
224 if (!first_encoded_timestamp_) {
225 while (frames_.front().timestamp() != video_frame.timestamp()) {
226 ++dropped_frames_before_first_encode_;
227 frames_.pop_front();
228 RTC_CHECK(!frames_.empty());
229 }
230 first_encoded_timestamp_ = video_frame.timestamp();
231 }
232}
233
234void VideoAnalyzer::EncodedFrameCallback(const EncodedFrame& encoded_frame) {
235 rtc::CritScope lock(&crit_);
236 if (!first_sent_timestamp_ && encoded_frame.stream_id_ == selected_stream_) {
237 first_sent_timestamp_ = encoded_frame.timestamp_;
238 }
239}
240
241bool VideoAnalyzer::SendRtp(const uint8_t* packet,
242 size_t length,
243 const PacketOptions& options) {
244 RtpUtility::RtpHeaderParser parser(packet, length);
245 RTPHeader header;
246 parser.Parse(&header);
247
248 int64_t current_time = Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
249
250 bool result = transport_->SendRtp(packet, length, options);
251 {
252 rtc::CritScope lock(&crit_);
253 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
254 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
255 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
256 }
257
258 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
259 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
260 // (FlexFEC and media are sent on different SSRCs, which have different
261 // timestamps spaces.)
262 // Also ignore packets from wrong SSRC and retransmits.
263 int64_t timestamp =
264 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
265 send_times_[timestamp] = current_time;
266
267 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
268 encoded_frame_sizes_[timestamp] +=
269 length - (header.headerLength + header.paddingLength);
270 total_media_bytes_ +=
271 length - (header.headerLength + header.paddingLength);
272 }
273 if (first_sending_time_ == 0)
274 first_sending_time_ = current_time;
275 last_sending_time_ = current_time;
276 }
277 }
278 return result;
279}
280
281bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
282 return transport_->SendRtcp(packet, length);
283}
284
285void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
286 int64_t render_time_ms =
287 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
288
289 rtc::CritScope lock(&crit_);
290
291 StartExcludingCpuThreadTime();
292
293 int64_t send_timestamp =
294 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
295
296 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
297 if (!last_rendered_frame_) {
298 // No previous frame rendered, this one was dropped after sending but
299 // before rendering.
300 ++dropped_frames_before_rendering_;
301 } else {
302 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
303 render_time_ms);
304 }
305 frames_.pop_front();
306 RTC_DCHECK(!frames_.empty());
307 }
308
309 VideoFrame reference_frame = frames_.front();
310 frames_.pop_front();
311 int64_t reference_timestamp =
312 wrap_handler_.Unwrap(reference_frame.timestamp());
313 if (send_timestamp == reference_timestamp - 1) {
314 // TODO(ivica): Make this work for > 2 streams.
315 // Look at RTPSender::BuildRTPHeader.
316 ++send_timestamp;
317 }
318 ASSERT_EQ(reference_timestamp, send_timestamp);
319
320 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
321
322 last_rendered_frame_ = video_frame;
323
324 StopExcludingCpuThreadTime();
325}
326
327void VideoAnalyzer::Wait() {
328 // Frame comparisons can be very expensive. Wait for test to be done, but
329 // at time-out check if frames_processed is going up. If so, give it more
330 // time, otherwise fail. Hopefully this will reduce test flakiness.
331
332 stats_polling_thread_.Start();
333
334 int last_frames_processed = -1;
335 int iteration = 0;
336 while (!done_.Wait(test::CallTest::kDefaultTimeoutMs)) {
337 int frames_processed;
338 {
339 rtc::CritScope crit(&comparison_lock_);
340 frames_processed = frames_processed_;
341 }
342
343 // Print some output so test infrastructure won't think we've crashed.
344 const char* kKeepAliveMessages[3] = {
345 "Uh, I'm-I'm not quite dead, sir.",
346 "Uh, I-I think uh, I could pull through, sir.",
347 "Actually, I think I'm all right to come with you--"};
348 printf("- %s\n", kKeepAliveMessages[iteration++ % 3]);
349
350 if (last_frames_processed == -1) {
351 last_frames_processed = frames_processed;
352 continue;
353 }
354 if (frames_processed == last_frames_processed) {
355 EXPECT_GT(frames_processed, last_frames_processed)
356 << "Analyzer stalled while waiting for test to finish.";
357 done_.Set();
358 break;
359 }
360 last_frames_processed = frames_processed;
361 }
362
363 if (iteration > 0)
364 printf("- Farewell, sweet Concorde!\n");
365
366 stats_polling_thread_.Stop();
367}
368
369rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::pre_encode_proxy() {
370 return &pre_encode_proxy_;
371}
372
373void VideoAnalyzer::StartMeasuringCpuProcessTime() {
374 rtc::CritScope lock(&cpu_measurement_lock_);
375 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
376 wallclock_time_ -= rtc::SystemTimeNanos();
377}
378
379void VideoAnalyzer::StopMeasuringCpuProcessTime() {
380 rtc::CritScope lock(&cpu_measurement_lock_);
381 cpu_time_ += rtc::GetProcessCpuTimeNanos();
382 wallclock_time_ += rtc::SystemTimeNanos();
383}
384
385void VideoAnalyzer::StartExcludingCpuThreadTime() {
386 rtc::CritScope lock(&cpu_measurement_lock_);
387 cpu_time_ += rtc::GetThreadCpuTimeNanos();
388}
389
390void VideoAnalyzer::StopExcludingCpuThreadTime() {
391 rtc::CritScope lock(&cpu_measurement_lock_);
392 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
393}
394
395double VideoAnalyzer::GetCpuUsagePercent() {
396 rtc::CritScope lock(&cpu_measurement_lock_);
397 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
398}
399
400bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
401 const uint8_t* packet,
402 size_t length,
403 const RTPHeader& header) {
404 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
405 header.payloadType != test::CallTest::kPayloadTypeVP8) {
406 return true;
407 } else {
408 // Get VP8 and VP9 specific header to check layers indexes.
409 const uint8_t* payload = packet + header.headerLength;
410 const size_t payload_length = length - header.headerLength;
411 const size_t payload_data_length = payload_length - header.paddingLength;
412 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
413 std::unique_ptr<RtpDepacketizer> depacketizer(
414 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
415 RtpDepacketizer::ParsedPayload parsed_payload;
416 bool result =
417 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
418 RTC_DCHECK(result);
419 const int temporal_idx = static_cast<int>(
420 is_vp8 ? parsed_payload.video_header().vp8().temporalIdx
421 : parsed_payload.video_header().vp9().temporal_idx);
422 const int spatial_idx = static_cast<int>(
423 is_vp8 ? kNoSpatialIdx
424 : parsed_payload.video_header().vp9().spatial_idx);
425 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
426 temporal_idx <= selected_tl_) &&
427 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
428 spatial_idx <= selected_sl_);
429 }
430}
431
432void VideoAnalyzer::PollStatsThread(void* obj) {
433 static_cast<VideoAnalyzer*>(obj)->PollStats();
434}
435
436void VideoAnalyzer::PollStats() {
437 while (!done_.Wait(kSendStatsPollingIntervalMs)) {
438 rtc::CritScope crit(&comparison_lock_);
439
440 Call::Stats call_stats = call_->GetStats();
441 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
442
443 VideoSendStream::Stats send_stats = send_stream_->GetStats();
444 // It's not certain that we yet have estimates for any of these stats.
445 // Check that they are positive before mixing them in.
446 if (send_stats.encode_frame_rate > 0)
447 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
448 if (send_stats.avg_encode_time_ms > 0)
449 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
450 if (send_stats.encode_usage_percent > 0)
451 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
452 if (send_stats.media_bitrate_bps > 0)
453 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
454 size_t fec_bytes = 0;
455 for (auto kv : send_stats.substreams) {
456 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
457 kv.second.rtp_stats.fec.padding_bytes;
458 }
459 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
460 last_fec_bytes_ = fec_bytes;
461
462 if (receive_stream_ != nullptr) {
463 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
464 if (receive_stats.decode_ms > 0)
465 decode_time_ms_.AddSample(receive_stats.decode_ms);
466 if (receive_stats.max_decode_ms > 0)
467 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
468 }
469
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200470 if (audio_receive_stream_ != nullptr) {
471 AudioReceiveStream::Stats receive_stats =
472 audio_receive_stream_->GetStats();
473 audio_expand_rate_.AddSample(receive_stats.expand_rate);
474 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
475 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
476 }
477
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200478 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
479 }
480}
481
482bool VideoAnalyzer::FrameComparisonThread(void* obj) {
483 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
484}
485
486bool VideoAnalyzer::CompareFrames() {
487 if (AllFramesRecorded())
488 return false;
489
490 FrameComparison comparison;
491
492 if (!PopComparison(&comparison)) {
493 // Wait until new comparison task is available, or test is done.
494 // If done, wake up remaining threads waiting.
495 comparison_available_event_.Wait(1000);
496 if (AllFramesRecorded()) {
497 comparison_available_event_.Set();
498 return false;
499 }
500 return true; // Try again.
501 }
502
503 StartExcludingCpuThreadTime();
504
505 PerformFrameComparison(comparison);
506
507 StopExcludingCpuThreadTime();
508
509 if (FrameProcessed()) {
510 PrintResults();
511 if (graph_data_output_file_)
512 PrintSamplesToFile();
513 done_.Set();
514 comparison_available_event_.Set();
515 return false;
516 }
517
518 return true;
519}
520
521bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
522 rtc::CritScope crit(&comparison_lock_);
523 // If AllFramesRecorded() is true, it means we have already popped
524 // frames_to_process_ frames from comparisons_, so there is no more work
525 // for this thread to be done. frames_processed_ might still be lower if
526 // all comparisons are not done, but those frames are currently being
527 // worked on by other threads.
528 if (comparisons_.empty() || AllFramesRecorded())
529 return false;
530
531 *comparison = comparisons_.front();
532 comparisons_.pop_front();
533
534 FrameRecorded();
535 return true;
536}
537
538void VideoAnalyzer::FrameRecorded() {
539 rtc::CritScope crit(&comparison_lock_);
540 ++frames_recorded_;
541}
542
543bool VideoAnalyzer::AllFramesRecorded() {
544 rtc::CritScope crit(&comparison_lock_);
545 assert(frames_recorded_ <= frames_to_process_);
546 return frames_recorded_ == frames_to_process_;
547}
548
549bool VideoAnalyzer::FrameProcessed() {
550 rtc::CritScope crit(&comparison_lock_);
551 ++frames_processed_;
552 assert(frames_processed_ <= frames_to_process_);
553 return frames_processed_ == frames_to_process_;
554}
555
556void VideoAnalyzer::PrintResults() {
557 StopMeasuringCpuProcessTime();
558 rtc::CritScope crit(&comparison_lock_);
559 // Record the time from the last freeze until the last rendered frame to
560 // ensure we cover the full timespan of the session. Otherwise the metric
561 // would penalize an early freeze followed by no freezes until the end.
562 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
563 PrintResult("psnr", psnr_, " dB");
564 PrintResult("ssim", ssim_, " score");
565 PrintResult("sender_time", sender_time_, " ms");
566 PrintResult("receiver_time", receiver_time_, " ms");
567 PrintResult("network_time", network_time_, " ms");
568 PrintResult("total_delay_incl_network", end_to_end_, " ms");
569 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
570 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
571 PrintResult("encode_time", encode_time_ms_, " ms");
572 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
573 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
574 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
575 PrintResult("time_between_freezes", time_between_freezes_, " ms");
576
577 if (worst_frame_) {
578 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
579 "dB", false);
580 }
581
582 if (receive_stream_ != nullptr) {
583 PrintResult("decode_time", decode_time_ms_, " ms");
584 }
585
586 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
587 "frames", false);
588 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
589 "%", false);
590
591#if defined(WEBRTC_WIN)
592 // On Linux and Mac in Resident Set some unused pages may be counted.
593 // Therefore this metric will depend on order in which tests are run and
594 // will be flaky.
595 PrintResult("memory_usage", memory_usage_, " bytes");
596#endif
597
598 // Saving only the worst frame for manual analysis. Intention here is to
599 // only detect video corruptions and not to track picture quality. Thus,
600 // jpeg is used here.
601 if (FLAG_save_worst_frame && worst_frame_) {
602 std::string output_dir;
603 test::GetTestArtifactsDir(&output_dir);
604 std::string output_path =
605 rtc::Pathname(output_dir, test_label_ + ".jpg").pathname();
606 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
607 test::JpegFrameWriter frame_writer(output_path);
608 RTC_CHECK(
609 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
610 }
611
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200612 if (audio_receive_stream_ != nullptr) {
613 PrintResult("audio_expand_rate", audio_expand_rate_, "");
614 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
615 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
616 }
617
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200618 // Disable quality check for quick test, as quality checks may fail
619 // because too few samples were collected.
620 if (!is_quick_test_enabled_) {
621 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
622 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
623 }
624}
625
626void VideoAnalyzer::PerformFrameComparison(
627 const VideoAnalyzer::FrameComparison& comparison) {
628 // Perform expensive psnr and ssim calculations while not holding lock.
629 double psnr = -1.0;
630 double ssim = -1.0;
631 if (comparison.reference && !comparison.dropped) {
632 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
633 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
634 }
635
636 rtc::CritScope crit(&comparison_lock_);
637
638 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
639 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
640 }
641
642 if (graph_data_output_file_) {
643 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
644 comparison.send_time_ms, comparison.recv_time_ms,
645 comparison.render_time_ms,
646 comparison.encoded_frame_size, psnr, ssim));
647 }
648 if (psnr >= 0.0)
649 psnr_.AddSample(psnr);
650 if (ssim >= 0.0)
651 ssim_.AddSample(ssim);
652
653 if (comparison.dropped) {
654 ++dropped_frames_;
655 return;
656 }
657 if (last_unfreeze_time_ms_ == 0)
658 last_unfreeze_time_ms_ = comparison.render_time_ms;
659 if (last_render_time_ != 0) {
660 const int64_t render_delta_ms =
661 comparison.render_time_ms - last_render_time_;
662 rendered_delta_.AddSample(render_delta_ms);
663 if (last_render_delta_ms_ != 0 &&
664 render_delta_ms - last_render_delta_ms_ > 150) {
665 time_between_freezes_.AddSample(last_render_time_ -
666 last_unfreeze_time_ms_);
667 last_unfreeze_time_ms_ = comparison.render_time_ms;
668 }
669 last_render_delta_ms_ = render_delta_ms;
670 }
671 last_render_time_ = comparison.render_time_ms;
672
673 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
674 if (comparison.recv_time_ms > 0) {
675 // If recv_time_ms == 0, this frame consisted of a packets which were all
676 // lost in the transport. Since we were able to render the frame, however,
677 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
678 // happens internally in Call, and we can therefore here not know which
679 // FEC packets that protected the lost media packets. Consequently, we
680 // were not able to record a meaningful recv_time_ms. We therefore skip
681 // this sample.
682 //
683 // The reasoning above does not hold for ULPFEC and RTX, as for those
684 // strategies the timestamp of the received packets is set to the
685 // timestamp of the protected/retransmitted media packet. I.e., then
686 // recv_time_ms != 0, even though the media packets were lost.
687 receiver_time_.AddSample(comparison.render_time_ms -
688 comparison.recv_time_ms);
689 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
690 }
691 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
692 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
693}
694
695void VideoAnalyzer::PrintResult(const char* result_type,
696 test::Statistics stats,
697 const char* unit) {
698 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(),
699 stats.Mean(), stats.StandardDeviation(), unit,
700 false);
701}
702
703void VideoAnalyzer::PrintSamplesToFile() {
704 FILE* out = graph_data_output_file_;
705 rtc::CritScope crit(&comparison_lock_);
706 std::sort(samples_.begin(), samples_.end(),
707 [](const Sample& A, const Sample& B) -> bool {
708 return A.input_time_ms < B.input_time_ms;
709 });
710
711 fprintf(out, "%s\n", graph_title_.c_str());
712 fprintf(out, "%" PRIuS "\n", samples_.size());
713 fprintf(out,
714 "dropped "
715 "input_time_ms "
716 "send_time_ms "
717 "recv_time_ms "
718 "render_time_ms "
719 "encoded_frame_size "
720 "psnr "
721 "ssim "
722 "encode_time_ms\n");
723 for (const Sample& sample : samples_) {
724 fprintf(out,
725 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
726 " %lf %lf\n",
727 sample.dropped, sample.input_time_ms, sample.send_time_ms,
728 sample.recv_time_ms, sample.render_time_ms,
729 sample.encoded_frame_size, sample.psnr, sample.ssim);
730 }
731}
732
733double VideoAnalyzer::GetAverageMediaBitrateBps() {
734 if (last_sending_time_ == first_sending_time_) {
735 return 0;
736 } else {
737 return static_cast<double>(total_media_bytes_) * 8 /
738 (last_sending_time_ - first_sending_time_) *
739 rtc::kNumMillisecsPerSec;
740 }
741}
742
743void VideoAnalyzer::AddCapturedFrameForComparison(
744 const VideoFrame& video_frame) {
745 rtc::CritScope lock(&crit_);
746 frames_.push_back(video_frame);
747}
748
749void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
750 const VideoFrame& render,
751 bool dropped,
752 int64_t render_time_ms) {
753 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
754 int64_t send_time_ms = send_times_[reference_timestamp];
755 send_times_.erase(reference_timestamp);
756 int64_t recv_time_ms = recv_times_[reference_timestamp];
757 recv_times_.erase(reference_timestamp);
758
759 // TODO(ivica): Make this work for > 2 streams.
760 auto it = encoded_frame_sizes_.find(reference_timestamp);
761 if (it == encoded_frame_sizes_.end())
762 it = encoded_frame_sizes_.find(reference_timestamp - 1);
763 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
764 if (it != encoded_frame_sizes_.end())
765 encoded_frame_sizes_.erase(it);
766
767 rtc::CritScope crit(&comparison_lock_);
768 if (comparisons_.size() < kMaxComparisons) {
769 comparisons_.push_back(FrameComparison(
770 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
771 recv_time_ms, render_time_ms, encoded_size));
772 } else {
773 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
774 send_time_ms, recv_time_ms,
775 render_time_ms, encoded_size));
776 }
777 comparison_available_event_.Set();
778}
779
780VideoAnalyzer::FrameComparison::FrameComparison()
781 : dropped(false),
782 input_time_ms(0),
783 send_time_ms(0),
784 recv_time_ms(0),
785 render_time_ms(0),
786 encoded_frame_size(0) {}
787
788VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
789 const VideoFrame& render,
790 bool dropped,
791 int64_t input_time_ms,
792 int64_t send_time_ms,
793 int64_t recv_time_ms,
794 int64_t render_time_ms,
795 size_t encoded_frame_size)
796 : reference(reference),
797 render(render),
798 dropped(dropped),
799 input_time_ms(input_time_ms),
800 send_time_ms(send_time_ms),
801 recv_time_ms(recv_time_ms),
802 render_time_ms(render_time_ms),
803 encoded_frame_size(encoded_frame_size) {}
804
805VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
806 int64_t input_time_ms,
807 int64_t send_time_ms,
808 int64_t recv_time_ms,
809 int64_t render_time_ms,
810 size_t encoded_frame_size)
811 : dropped(dropped),
812 input_time_ms(input_time_ms),
813 send_time_ms(send_time_ms),
814 recv_time_ms(recv_time_ms),
815 render_time_ms(render_time_ms),
816 encoded_frame_size(encoded_frame_size) {}
817
818VideoAnalyzer::Sample::Sample(int dropped,
819 int64_t input_time_ms,
820 int64_t send_time_ms,
821 int64_t recv_time_ms,
822 int64_t render_time_ms,
823 size_t encoded_frame_size,
824 double psnr,
825 double ssim)
826 : dropped(dropped),
827 input_time_ms(input_time_ms),
828 send_time_ms(send_time_ms),
829 recv_time_ms(recv_time_ms),
830 render_time_ms(render_time_ms),
831 encoded_frame_size(encoded_frame_size),
832 psnr(psnr),
833 ssim(ssim) {}
834
835VideoAnalyzer::PreEncodeProxy::PreEncodeProxy(VideoAnalyzer* parent)
836 : parent_(parent) {}
837
838void VideoAnalyzer::PreEncodeProxy::OnFrame(const VideoFrame& video_frame) {
839 parent_->PreEncodeOnFrame(video_frame);
840}
841
842VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
843 VideoAnalyzer* analyzer,
844 Clock* clock)
845 : analyzer_(analyzer),
846 send_stream_input_(nullptr),
847 video_capturer_(nullptr),
848 clock_(clock) {}
849
850void VideoAnalyzer::CapturedFrameForwarder::SetSource(
851 test::VideoCapturer* video_capturer) {
852 video_capturer_ = video_capturer;
853}
854
855void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
856 const VideoFrame& video_frame) {
857 VideoFrame copy = video_frame;
858 // Frames from the capturer does not have a rtp timestamp.
859 // Create one so it can be used for comparison.
860 RTC_DCHECK_EQ(0, video_frame.timestamp());
861 if (video_frame.ntp_time_ms() == 0)
862 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
863 copy.set_timestamp(copy.ntp_time_ms() * 90);
864 analyzer_->AddCapturedFrameForComparison(copy);
865 rtc::CritScope lock(&crit_);
866 if (send_stream_input_)
867 send_stream_input_->OnFrame(copy);
868}
869
870void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
871 rtc::VideoSinkInterface<VideoFrame>* sink,
872 const rtc::VideoSinkWants& wants) {
873 {
874 rtc::CritScope lock(&crit_);
875 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
876 send_stream_input_ = sink;
877 }
878 if (video_capturer_) {
879 video_capturer_->AddOrUpdateSink(this, wants);
880 }
881}
882
883void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
884 rtc::VideoSinkInterface<VideoFrame>* sink) {
885 rtc::CritScope lock(&crit_);
886 RTC_DCHECK(sink == send_stream_input_);
887 send_stream_input_ = nullptr;
888}
889
890} // namespace webrtc