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