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