blob: 04b5c766c8728eb75dab5fd7f7c1d56175dd90d6 [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);
philipel29d88462018-08-08 14:26:00 +0200419
420 int temporal_idx;
421 int spatial_idx;
422 if (is_vp8) {
423 temporal_idx = parsed_payload.video_header().vp8().temporalIdx;
424 spatial_idx = kNoTemporalIdx;
425 } else {
426 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
427 parsed_payload.video_header().video_type_header);
428 temporal_idx = vp9_header.temporal_idx;
429 spatial_idx = vp9_header.spatial_idx;
430 }
431
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200432 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
433 temporal_idx <= selected_tl_) &&
434 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
435 spatial_idx <= selected_sl_);
436 }
437}
438
439void VideoAnalyzer::PollStatsThread(void* obj) {
440 static_cast<VideoAnalyzer*>(obj)->PollStats();
441}
442
443void VideoAnalyzer::PollStats() {
444 while (!done_.Wait(kSendStatsPollingIntervalMs)) {
445 rtc::CritScope crit(&comparison_lock_);
446
447 Call::Stats call_stats = call_->GetStats();
448 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
449
450 VideoSendStream::Stats send_stats = send_stream_->GetStats();
451 // It's not certain that we yet have estimates for any of these stats.
452 // Check that they are positive before mixing them in.
453 if (send_stats.encode_frame_rate > 0)
454 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
455 if (send_stats.avg_encode_time_ms > 0)
456 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
457 if (send_stats.encode_usage_percent > 0)
458 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
459 if (send_stats.media_bitrate_bps > 0)
460 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
461 size_t fec_bytes = 0;
462 for (auto kv : send_stats.substreams) {
463 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
464 kv.second.rtp_stats.fec.padding_bytes;
465 }
466 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
467 last_fec_bytes_ = fec_bytes;
468
469 if (receive_stream_ != nullptr) {
470 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
471 if (receive_stats.decode_ms > 0)
472 decode_time_ms_.AddSample(receive_stats.decode_ms);
473 if (receive_stats.max_decode_ms > 0)
474 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
475 }
476
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200477 if (audio_receive_stream_ != nullptr) {
478 AudioReceiveStream::Stats receive_stats =
479 audio_receive_stream_->GetStats();
480 audio_expand_rate_.AddSample(receive_stats.expand_rate);
481 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
482 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
483 }
484
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200485 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
486 }
487}
488
489bool VideoAnalyzer::FrameComparisonThread(void* obj) {
490 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
491}
492
493bool VideoAnalyzer::CompareFrames() {
494 if (AllFramesRecorded())
495 return false;
496
497 FrameComparison comparison;
498
499 if (!PopComparison(&comparison)) {
500 // Wait until new comparison task is available, or test is done.
501 // If done, wake up remaining threads waiting.
502 comparison_available_event_.Wait(1000);
503 if (AllFramesRecorded()) {
504 comparison_available_event_.Set();
505 return false;
506 }
507 return true; // Try again.
508 }
509
510 StartExcludingCpuThreadTime();
511
512 PerformFrameComparison(comparison);
513
514 StopExcludingCpuThreadTime();
515
516 if (FrameProcessed()) {
517 PrintResults();
518 if (graph_data_output_file_)
519 PrintSamplesToFile();
520 done_.Set();
521 comparison_available_event_.Set();
522 return false;
523 }
524
525 return true;
526}
527
528bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
529 rtc::CritScope crit(&comparison_lock_);
530 // If AllFramesRecorded() is true, it means we have already popped
531 // frames_to_process_ frames from comparisons_, so there is no more work
532 // for this thread to be done. frames_processed_ might still be lower if
533 // all comparisons are not done, but those frames are currently being
534 // worked on by other threads.
535 if (comparisons_.empty() || AllFramesRecorded())
536 return false;
537
538 *comparison = comparisons_.front();
539 comparisons_.pop_front();
540
541 FrameRecorded();
542 return true;
543}
544
545void VideoAnalyzer::FrameRecorded() {
546 rtc::CritScope crit(&comparison_lock_);
547 ++frames_recorded_;
548}
549
550bool VideoAnalyzer::AllFramesRecorded() {
551 rtc::CritScope crit(&comparison_lock_);
552 assert(frames_recorded_ <= frames_to_process_);
553 return frames_recorded_ == frames_to_process_;
554}
555
556bool VideoAnalyzer::FrameProcessed() {
557 rtc::CritScope crit(&comparison_lock_);
558 ++frames_processed_;
559 assert(frames_processed_ <= frames_to_process_);
560 return frames_processed_ == frames_to_process_;
561}
562
563void VideoAnalyzer::PrintResults() {
564 StopMeasuringCpuProcessTime();
565 rtc::CritScope crit(&comparison_lock_);
566 // Record the time from the last freeze until the last rendered frame to
567 // ensure we cover the full timespan of the session. Otherwise the metric
568 // would penalize an early freeze followed by no freezes until the end.
569 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
570 PrintResult("psnr", psnr_, " dB");
571 PrintResult("ssim", ssim_, " score");
572 PrintResult("sender_time", sender_time_, " ms");
573 PrintResult("receiver_time", receiver_time_, " ms");
574 PrintResult("network_time", network_time_, " ms");
575 PrintResult("total_delay_incl_network", end_to_end_, " ms");
576 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
577 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
578 PrintResult("encode_time", encode_time_ms_, " ms");
579 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
580 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
581 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
582 PrintResult("time_between_freezes", time_between_freezes_, " ms");
583
584 if (worst_frame_) {
585 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
586 "dB", false);
587 }
588
589 if (receive_stream_ != nullptr) {
590 PrintResult("decode_time", decode_time_ms_, " ms");
591 }
592
593 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
594 "frames", false);
595 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
596 "%", false);
597
598#if defined(WEBRTC_WIN)
599 // On Linux and Mac in Resident Set some unused pages may be counted.
600 // Therefore this metric will depend on order in which tests are run and
601 // will be flaky.
602 PrintResult("memory_usage", memory_usage_, " bytes");
603#endif
604
605 // Saving only the worst frame for manual analysis. Intention here is to
606 // only detect video corruptions and not to track picture quality. Thus,
607 // jpeg is used here.
608 if (FLAG_save_worst_frame && worst_frame_) {
609 std::string output_dir;
610 test::GetTestArtifactsDir(&output_dir);
611 std::string output_path =
612 rtc::Pathname(output_dir, test_label_ + ".jpg").pathname();
613 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
614 test::JpegFrameWriter frame_writer(output_path);
615 RTC_CHECK(
616 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
617 }
618
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200619 if (audio_receive_stream_ != nullptr) {
620 PrintResult("audio_expand_rate", audio_expand_rate_, "");
621 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
622 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
623 }
624
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200625 // Disable quality check for quick test, as quality checks may fail
626 // because too few samples were collected.
627 if (!is_quick_test_enabled_) {
628 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
629 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
630 }
631}
632
633void VideoAnalyzer::PerformFrameComparison(
634 const VideoAnalyzer::FrameComparison& comparison) {
635 // Perform expensive psnr and ssim calculations while not holding lock.
636 double psnr = -1.0;
637 double ssim = -1.0;
638 if (comparison.reference && !comparison.dropped) {
639 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
640 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
641 }
642
643 rtc::CritScope crit(&comparison_lock_);
644
645 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
646 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
647 }
648
649 if (graph_data_output_file_) {
650 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
651 comparison.send_time_ms, comparison.recv_time_ms,
652 comparison.render_time_ms,
653 comparison.encoded_frame_size, psnr, ssim));
654 }
655 if (psnr >= 0.0)
656 psnr_.AddSample(psnr);
657 if (ssim >= 0.0)
658 ssim_.AddSample(ssim);
659
660 if (comparison.dropped) {
661 ++dropped_frames_;
662 return;
663 }
664 if (last_unfreeze_time_ms_ == 0)
665 last_unfreeze_time_ms_ = comparison.render_time_ms;
666 if (last_render_time_ != 0) {
667 const int64_t render_delta_ms =
668 comparison.render_time_ms - last_render_time_;
669 rendered_delta_.AddSample(render_delta_ms);
670 if (last_render_delta_ms_ != 0 &&
671 render_delta_ms - last_render_delta_ms_ > 150) {
672 time_between_freezes_.AddSample(last_render_time_ -
673 last_unfreeze_time_ms_);
674 last_unfreeze_time_ms_ = comparison.render_time_ms;
675 }
676 last_render_delta_ms_ = render_delta_ms;
677 }
678 last_render_time_ = comparison.render_time_ms;
679
680 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
681 if (comparison.recv_time_ms > 0) {
682 // If recv_time_ms == 0, this frame consisted of a packets which were all
683 // lost in the transport. Since we were able to render the frame, however,
684 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
685 // happens internally in Call, and we can therefore here not know which
686 // FEC packets that protected the lost media packets. Consequently, we
687 // were not able to record a meaningful recv_time_ms. We therefore skip
688 // this sample.
689 //
690 // The reasoning above does not hold for ULPFEC and RTX, as for those
691 // strategies the timestamp of the received packets is set to the
692 // timestamp of the protected/retransmitted media packet. I.e., then
693 // recv_time_ms != 0, even though the media packets were lost.
694 receiver_time_.AddSample(comparison.render_time_ms -
695 comparison.recv_time_ms);
696 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
697 }
698 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
699 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
700}
701
702void VideoAnalyzer::PrintResult(const char* result_type,
703 test::Statistics stats,
704 const char* unit) {
705 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(),
706 stats.Mean(), stats.StandardDeviation(), unit,
707 false);
708}
709
710void VideoAnalyzer::PrintSamplesToFile() {
711 FILE* out = graph_data_output_file_;
712 rtc::CritScope crit(&comparison_lock_);
713 std::sort(samples_.begin(), samples_.end(),
714 [](const Sample& A, const Sample& B) -> bool {
715 return A.input_time_ms < B.input_time_ms;
716 });
717
718 fprintf(out, "%s\n", graph_title_.c_str());
719 fprintf(out, "%" PRIuS "\n", samples_.size());
720 fprintf(out,
721 "dropped "
722 "input_time_ms "
723 "send_time_ms "
724 "recv_time_ms "
725 "render_time_ms "
726 "encoded_frame_size "
727 "psnr "
728 "ssim "
729 "encode_time_ms\n");
730 for (const Sample& sample : samples_) {
731 fprintf(out,
732 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
733 " %lf %lf\n",
734 sample.dropped, sample.input_time_ms, sample.send_time_ms,
735 sample.recv_time_ms, sample.render_time_ms,
736 sample.encoded_frame_size, sample.psnr, sample.ssim);
737 }
738}
739
740double VideoAnalyzer::GetAverageMediaBitrateBps() {
741 if (last_sending_time_ == first_sending_time_) {
742 return 0;
743 } else {
744 return static_cast<double>(total_media_bytes_) * 8 /
745 (last_sending_time_ - first_sending_time_) *
746 rtc::kNumMillisecsPerSec;
747 }
748}
749
750void VideoAnalyzer::AddCapturedFrameForComparison(
751 const VideoFrame& video_frame) {
752 rtc::CritScope lock(&crit_);
753 frames_.push_back(video_frame);
754}
755
756void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
757 const VideoFrame& render,
758 bool dropped,
759 int64_t render_time_ms) {
760 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
761 int64_t send_time_ms = send_times_[reference_timestamp];
762 send_times_.erase(reference_timestamp);
763 int64_t recv_time_ms = recv_times_[reference_timestamp];
764 recv_times_.erase(reference_timestamp);
765
766 // TODO(ivica): Make this work for > 2 streams.
767 auto it = encoded_frame_sizes_.find(reference_timestamp);
768 if (it == encoded_frame_sizes_.end())
769 it = encoded_frame_sizes_.find(reference_timestamp - 1);
770 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
771 if (it != encoded_frame_sizes_.end())
772 encoded_frame_sizes_.erase(it);
773
774 rtc::CritScope crit(&comparison_lock_);
775 if (comparisons_.size() < kMaxComparisons) {
776 comparisons_.push_back(FrameComparison(
777 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
778 recv_time_ms, render_time_ms, encoded_size));
779 } else {
780 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
781 send_time_ms, recv_time_ms,
782 render_time_ms, encoded_size));
783 }
784 comparison_available_event_.Set();
785}
786
787VideoAnalyzer::FrameComparison::FrameComparison()
788 : dropped(false),
789 input_time_ms(0),
790 send_time_ms(0),
791 recv_time_ms(0),
792 render_time_ms(0),
793 encoded_frame_size(0) {}
794
795VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
796 const VideoFrame& render,
797 bool dropped,
798 int64_t input_time_ms,
799 int64_t send_time_ms,
800 int64_t recv_time_ms,
801 int64_t render_time_ms,
802 size_t encoded_frame_size)
803 : reference(reference),
804 render(render),
805 dropped(dropped),
806 input_time_ms(input_time_ms),
807 send_time_ms(send_time_ms),
808 recv_time_ms(recv_time_ms),
809 render_time_ms(render_time_ms),
810 encoded_frame_size(encoded_frame_size) {}
811
812VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
813 int64_t input_time_ms,
814 int64_t send_time_ms,
815 int64_t recv_time_ms,
816 int64_t render_time_ms,
817 size_t encoded_frame_size)
818 : dropped(dropped),
819 input_time_ms(input_time_ms),
820 send_time_ms(send_time_ms),
821 recv_time_ms(recv_time_ms),
822 render_time_ms(render_time_ms),
823 encoded_frame_size(encoded_frame_size) {}
824
825VideoAnalyzer::Sample::Sample(int dropped,
826 int64_t input_time_ms,
827 int64_t send_time_ms,
828 int64_t recv_time_ms,
829 int64_t render_time_ms,
830 size_t encoded_frame_size,
831 double psnr,
832 double ssim)
833 : dropped(dropped),
834 input_time_ms(input_time_ms),
835 send_time_ms(send_time_ms),
836 recv_time_ms(recv_time_ms),
837 render_time_ms(render_time_ms),
838 encoded_frame_size(encoded_frame_size),
839 psnr(psnr),
840 ssim(ssim) {}
841
842VideoAnalyzer::PreEncodeProxy::PreEncodeProxy(VideoAnalyzer* parent)
843 : parent_(parent) {}
844
845void VideoAnalyzer::PreEncodeProxy::OnFrame(const VideoFrame& video_frame) {
846 parent_->PreEncodeOnFrame(video_frame);
847}
848
849VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
850 VideoAnalyzer* analyzer,
851 Clock* clock)
852 : analyzer_(analyzer),
853 send_stream_input_(nullptr),
854 video_capturer_(nullptr),
855 clock_(clock) {}
856
857void VideoAnalyzer::CapturedFrameForwarder::SetSource(
858 test::VideoCapturer* video_capturer) {
859 video_capturer_ = video_capturer;
860}
861
862void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
863 const VideoFrame& video_frame) {
864 VideoFrame copy = video_frame;
865 // Frames from the capturer does not have a rtp timestamp.
866 // Create one so it can be used for comparison.
867 RTC_DCHECK_EQ(0, video_frame.timestamp());
868 if (video_frame.ntp_time_ms() == 0)
869 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
870 copy.set_timestamp(copy.ntp_time_ms() * 90);
871 analyzer_->AddCapturedFrameForComparison(copy);
872 rtc::CritScope lock(&crit_);
873 if (send_stream_input_)
874 send_stream_input_->OnFrame(copy);
875}
876
877void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
878 rtc::VideoSinkInterface<VideoFrame>* sink,
879 const rtc::VideoSinkWants& wants) {
880 {
881 rtc::CritScope lock(&crit_);
882 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
883 send_stream_input_ = sink;
884 }
885 if (video_capturer_) {
886 video_capturer_->AddOrUpdateSink(this, wants);
887 }
888}
889
890void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
891 rtc::VideoSinkInterface<VideoFrame>* sink) {
892 rtc::CritScope lock(&crit_);
893 RTC_DCHECK(sink == send_stream_input_);
894 send_stream_input_ = nullptr;
895}
896
897} // namespace webrtc