blob: 6d16b1a055ff55408cd24b8aae1577268f36911f [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"
Qingsi Wang2039ee72018-11-02 16:30:10 +000021#include "rtc_base/pathutils.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020022#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
Mirko Bonadei2dfa9982018-10-18 11:35:32 +020028WEBRTC_DEFINE_bool(
29 save_worst_frame,
30 false,
31 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
32 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 12:57:37 +020033
34namespace webrtc {
35namespace {
36constexpr int kSendStatsPollingIntervalMs = 1000;
37constexpr size_t kMaxComparisons = 10;
38
39bool IsFlexfec(int payload_type) {
40 return payload_type == test::CallTest::kFlexfecPayloadType;
41}
42} // namespace
43
44VideoAnalyzer::VideoAnalyzer(test::LayerFilteringTransport* transport,
45 const std::string& test_label,
46 double avg_psnr_threshold,
47 double avg_ssim_threshold,
48 int duration_frames,
49 FILE* graph_data_output_file,
50 const std::string& graph_title,
51 uint32_t ssrc_to_analyze,
52 uint32_t rtx_ssrc_to_analyze,
53 size_t selected_stream,
54 int selected_sl,
55 int selected_tl,
56 bool is_quick_test_enabled,
57 Clock* clock,
58 std::string rtp_dump_name)
59 : transport_(transport),
60 receiver_(nullptr),
61 call_(nullptr),
62 send_stream_(nullptr),
63 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 14:10:56 +020064 audio_receive_stream_(nullptr),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020065 captured_frame_forwarder_(this, clock),
66 test_label_(test_label),
67 graph_data_output_file_(graph_data_output_file),
68 graph_title_(graph_title),
69 ssrc_to_analyze_(ssrc_to_analyze),
70 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
71 selected_stream_(selected_stream),
72 selected_sl_(selected_sl),
73 selected_tl_(selected_tl),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020074 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
Niels Möller88be9722018-10-10 10:58:52 +0200234void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200235 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200236 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
237 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200238 }
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
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200369void VideoAnalyzer::StartMeasuringCpuProcessTime() {
370 rtc::CritScope lock(&cpu_measurement_lock_);
371 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
372 wallclock_time_ -= rtc::SystemTimeNanos();
373}
374
375void VideoAnalyzer::StopMeasuringCpuProcessTime() {
376 rtc::CritScope lock(&cpu_measurement_lock_);
377 cpu_time_ += rtc::GetProcessCpuTimeNanos();
378 wallclock_time_ += rtc::SystemTimeNanos();
379}
380
381void VideoAnalyzer::StartExcludingCpuThreadTime() {
382 rtc::CritScope lock(&cpu_measurement_lock_);
383 cpu_time_ += rtc::GetThreadCpuTimeNanos();
384}
385
386void VideoAnalyzer::StopExcludingCpuThreadTime() {
387 rtc::CritScope lock(&cpu_measurement_lock_);
388 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
389}
390
391double VideoAnalyzer::GetCpuUsagePercent() {
392 rtc::CritScope lock(&cpu_measurement_lock_);
393 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
394}
395
396bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
397 const uint8_t* packet,
398 size_t length,
399 const RTPHeader& header) {
400 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
401 header.payloadType != test::CallTest::kPayloadTypeVP8) {
402 return true;
403 } else {
404 // Get VP8 and VP9 specific header to check layers indexes.
405 const uint8_t* payload = packet + header.headerLength;
406 const size_t payload_length = length - header.headerLength;
407 const size_t payload_data_length = payload_length - header.paddingLength;
408 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
409 std::unique_ptr<RtpDepacketizer> depacketizer(
410 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
411 RtpDepacketizer::ParsedPayload parsed_payload;
412 bool result =
413 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
414 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200415
416 int temporal_idx;
417 int spatial_idx;
418 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000419 temporal_idx = absl::get<RTPVideoHeaderVP8>(
420 parsed_payload.video_header().video_type_header)
421 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200422 spatial_idx = kNoTemporalIdx;
423 } else {
424 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
425 parsed_payload.video_header().video_type_header);
426 temporal_idx = vp9_header.temporal_idx;
427 spatial_idx = vp9_header.spatial_idx;
428 }
429
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200430 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
431 temporal_idx <= selected_tl_) &&
432 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
433 spatial_idx <= selected_sl_);
434 }
435}
436
437void VideoAnalyzer::PollStatsThread(void* obj) {
438 static_cast<VideoAnalyzer*>(obj)->PollStats();
439}
440
441void VideoAnalyzer::PollStats() {
442 while (!done_.Wait(kSendStatsPollingIntervalMs)) {
443 rtc::CritScope crit(&comparison_lock_);
444
445 Call::Stats call_stats = call_->GetStats();
446 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
447
448 VideoSendStream::Stats send_stats = send_stream_->GetStats();
449 // It's not certain that we yet have estimates for any of these stats.
450 // Check that they are positive before mixing them in.
451 if (send_stats.encode_frame_rate > 0)
452 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
453 if (send_stats.avg_encode_time_ms > 0)
454 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
455 if (send_stats.encode_usage_percent > 0)
456 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
457 if (send_stats.media_bitrate_bps > 0)
458 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
459 size_t fec_bytes = 0;
460 for (auto kv : send_stats.substreams) {
461 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
462 kv.second.rtp_stats.fec.padding_bytes;
463 }
464 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
465 last_fec_bytes_ = fec_bytes;
466
467 if (receive_stream_ != nullptr) {
468 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
469 if (receive_stats.decode_ms > 0)
470 decode_time_ms_.AddSample(receive_stats.decode_ms);
471 if (receive_stats.max_decode_ms > 0)
472 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
473 }
474
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200475 if (audio_receive_stream_ != nullptr) {
476 AudioReceiveStream::Stats receive_stats =
477 audio_receive_stream_->GetStats();
478 audio_expand_rate_.AddSample(receive_stats.expand_rate);
479 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
480 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
481 }
482
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200483 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
484 }
485}
486
487bool VideoAnalyzer::FrameComparisonThread(void* obj) {
488 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
489}
490
491bool VideoAnalyzer::CompareFrames() {
492 if (AllFramesRecorded())
493 return false;
494
495 FrameComparison comparison;
496
497 if (!PopComparison(&comparison)) {
498 // Wait until new comparison task is available, or test is done.
499 // If done, wake up remaining threads waiting.
500 comparison_available_event_.Wait(1000);
501 if (AllFramesRecorded()) {
502 comparison_available_event_.Set();
503 return false;
504 }
505 return true; // Try again.
506 }
507
508 StartExcludingCpuThreadTime();
509
510 PerformFrameComparison(comparison);
511
512 StopExcludingCpuThreadTime();
513
514 if (FrameProcessed()) {
515 PrintResults();
516 if (graph_data_output_file_)
517 PrintSamplesToFile();
518 done_.Set();
519 comparison_available_event_.Set();
520 return false;
521 }
522
523 return true;
524}
525
526bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
527 rtc::CritScope crit(&comparison_lock_);
528 // If AllFramesRecorded() is true, it means we have already popped
529 // frames_to_process_ frames from comparisons_, so there is no more work
530 // for this thread to be done. frames_processed_ might still be lower if
531 // all comparisons are not done, but those frames are currently being
532 // worked on by other threads.
533 if (comparisons_.empty() || AllFramesRecorded())
534 return false;
535
536 *comparison = comparisons_.front();
537 comparisons_.pop_front();
538
539 FrameRecorded();
540 return true;
541}
542
543void VideoAnalyzer::FrameRecorded() {
544 rtc::CritScope crit(&comparison_lock_);
545 ++frames_recorded_;
546}
547
548bool VideoAnalyzer::AllFramesRecorded() {
549 rtc::CritScope crit(&comparison_lock_);
550 assert(frames_recorded_ <= frames_to_process_);
551 return frames_recorded_ == frames_to_process_;
552}
553
554bool VideoAnalyzer::FrameProcessed() {
555 rtc::CritScope crit(&comparison_lock_);
556 ++frames_processed_;
557 assert(frames_processed_ <= frames_to_process_);
558 return frames_processed_ == frames_to_process_;
559}
560
561void VideoAnalyzer::PrintResults() {
562 StopMeasuringCpuProcessTime();
563 rtc::CritScope crit(&comparison_lock_);
564 // Record the time from the last freeze until the last rendered frame to
565 // ensure we cover the full timespan of the session. Otherwise the metric
566 // would penalize an early freeze followed by no freezes until the end.
567 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
568 PrintResult("psnr", psnr_, " dB");
569 PrintResult("ssim", ssim_, " score");
570 PrintResult("sender_time", sender_time_, " ms");
571 PrintResult("receiver_time", receiver_time_, " ms");
572 PrintResult("network_time", network_time_, " ms");
573 PrintResult("total_delay_incl_network", end_to_end_, " ms");
574 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
575 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
576 PrintResult("encode_time", encode_time_ms_, " ms");
577 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
578 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
579 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
580 PrintResult("time_between_freezes", time_between_freezes_, " ms");
581
582 if (worst_frame_) {
583 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
584 "dB", false);
585 }
586
587 if (receive_stream_ != nullptr) {
588 PrintResult("decode_time", decode_time_ms_, " ms");
589 }
590
591 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
592 "frames", false);
593 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
594 "%", false);
595
596#if defined(WEBRTC_WIN)
597 // On Linux and Mac in Resident Set some unused pages may be counted.
598 // Therefore this metric will depend on order in which tests are run and
599 // will be flaky.
600 PrintResult("memory_usage", memory_usage_, " bytes");
601#endif
602
603 // Saving only the worst frame for manual analysis. Intention here is to
604 // only detect video corruptions and not to track picture quality. Thus,
605 // jpeg is used here.
606 if (FLAG_save_worst_frame && worst_frame_) {
607 std::string output_dir;
608 test::GetTestArtifactsDir(&output_dir);
609 std::string output_path =
Qingsi Wang2039ee72018-11-02 16:30:10 +0000610 rtc::Pathname(output_dir, test_label_ + ".jpg").pathname();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200611 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
612 test::JpegFrameWriter frame_writer(output_path);
613 RTC_CHECK(
614 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
615 }
616
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200617 if (audio_receive_stream_ != nullptr) {
618 PrintResult("audio_expand_rate", audio_expand_rate_, "");
619 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
620 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
621 }
622
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200623 // Disable quality check for quick test, as quality checks may fail
624 // because too few samples were collected.
625 if (!is_quick_test_enabled_) {
626 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
627 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
628 }
629}
630
631void VideoAnalyzer::PerformFrameComparison(
632 const VideoAnalyzer::FrameComparison& comparison) {
633 // Perform expensive psnr and ssim calculations while not holding lock.
634 double psnr = -1.0;
635 double ssim = -1.0;
636 if (comparison.reference && !comparison.dropped) {
637 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
638 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
639 }
640
641 rtc::CritScope crit(&comparison_lock_);
642
643 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
644 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
645 }
646
647 if (graph_data_output_file_) {
648 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
649 comparison.send_time_ms, comparison.recv_time_ms,
650 comparison.render_time_ms,
651 comparison.encoded_frame_size, psnr, ssim));
652 }
653 if (psnr >= 0.0)
654 psnr_.AddSample(psnr);
655 if (ssim >= 0.0)
656 ssim_.AddSample(ssim);
657
658 if (comparison.dropped) {
659 ++dropped_frames_;
660 return;
661 }
662 if (last_unfreeze_time_ms_ == 0)
663 last_unfreeze_time_ms_ = comparison.render_time_ms;
664 if (last_render_time_ != 0) {
665 const int64_t render_delta_ms =
666 comparison.render_time_ms - last_render_time_;
667 rendered_delta_.AddSample(render_delta_ms);
668 if (last_render_delta_ms_ != 0 &&
669 render_delta_ms - last_render_delta_ms_ > 150) {
670 time_between_freezes_.AddSample(last_render_time_ -
671 last_unfreeze_time_ms_);
672 last_unfreeze_time_ms_ = comparison.render_time_ms;
673 }
674 last_render_delta_ms_ = render_delta_ms;
675 }
676 last_render_time_ = comparison.render_time_ms;
677
678 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
679 if (comparison.recv_time_ms > 0) {
680 // If recv_time_ms == 0, this frame consisted of a packets which were all
681 // lost in the transport. Since we were able to render the frame, however,
682 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
683 // happens internally in Call, and we can therefore here not know which
684 // FEC packets that protected the lost media packets. Consequently, we
685 // were not able to record a meaningful recv_time_ms. We therefore skip
686 // this sample.
687 //
688 // The reasoning above does not hold for ULPFEC and RTX, as for those
689 // strategies the timestamp of the received packets is set to the
690 // timestamp of the protected/retransmitted media packet. I.e., then
691 // recv_time_ms != 0, even though the media packets were lost.
692 receiver_time_.AddSample(comparison.render_time_ms -
693 comparison.recv_time_ms);
694 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
695 }
696 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
697 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
698}
699
700void VideoAnalyzer::PrintResult(const char* result_type,
701 test::Statistics stats,
702 const char* unit) {
703 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(),
704 stats.Mean(), stats.StandardDeviation(), unit,
705 false);
706}
707
708void VideoAnalyzer::PrintSamplesToFile() {
709 FILE* out = graph_data_output_file_;
710 rtc::CritScope crit(&comparison_lock_);
711 std::sort(samples_.begin(), samples_.end(),
712 [](const Sample& A, const Sample& B) -> bool {
713 return A.input_time_ms < B.input_time_ms;
714 });
715
716 fprintf(out, "%s\n", graph_title_.c_str());
717 fprintf(out, "%" PRIuS "\n", samples_.size());
718 fprintf(out,
719 "dropped "
720 "input_time_ms "
721 "send_time_ms "
722 "recv_time_ms "
723 "render_time_ms "
724 "encoded_frame_size "
725 "psnr "
726 "ssim "
727 "encode_time_ms\n");
728 for (const Sample& sample : samples_) {
729 fprintf(out,
730 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
731 " %lf %lf\n",
732 sample.dropped, sample.input_time_ms, sample.send_time_ms,
733 sample.recv_time_ms, sample.render_time_ms,
734 sample.encoded_frame_size, sample.psnr, sample.ssim);
735 }
736}
737
738double VideoAnalyzer::GetAverageMediaBitrateBps() {
739 if (last_sending_time_ == first_sending_time_) {
740 return 0;
741 } else {
742 return static_cast<double>(total_media_bytes_) * 8 /
743 (last_sending_time_ - first_sending_time_) *
744 rtc::kNumMillisecsPerSec;
745 }
746}
747
748void VideoAnalyzer::AddCapturedFrameForComparison(
749 const VideoFrame& video_frame) {
750 rtc::CritScope lock(&crit_);
751 frames_.push_back(video_frame);
752}
753
754void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
755 const VideoFrame& render,
756 bool dropped,
757 int64_t render_time_ms) {
758 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
759 int64_t send_time_ms = send_times_[reference_timestamp];
760 send_times_.erase(reference_timestamp);
761 int64_t recv_time_ms = recv_times_[reference_timestamp];
762 recv_times_.erase(reference_timestamp);
763
764 // TODO(ivica): Make this work for > 2 streams.
765 auto it = encoded_frame_sizes_.find(reference_timestamp);
766 if (it == encoded_frame_sizes_.end())
767 it = encoded_frame_sizes_.find(reference_timestamp - 1);
768 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
769 if (it != encoded_frame_sizes_.end())
770 encoded_frame_sizes_.erase(it);
771
772 rtc::CritScope crit(&comparison_lock_);
773 if (comparisons_.size() < kMaxComparisons) {
774 comparisons_.push_back(FrameComparison(
775 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
776 recv_time_ms, render_time_ms, encoded_size));
777 } else {
778 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
779 send_time_ms, recv_time_ms,
780 render_time_ms, encoded_size));
781 }
782 comparison_available_event_.Set();
783}
784
785VideoAnalyzer::FrameComparison::FrameComparison()
786 : dropped(false),
787 input_time_ms(0),
788 send_time_ms(0),
789 recv_time_ms(0),
790 render_time_ms(0),
791 encoded_frame_size(0) {}
792
793VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
794 const VideoFrame& render,
795 bool 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 : reference(reference),
802 render(render),
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
810VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
811 int64_t input_time_ms,
812 int64_t send_time_ms,
813 int64_t recv_time_ms,
814 int64_t render_time_ms,
815 size_t encoded_frame_size)
816 : dropped(dropped),
817 input_time_ms(input_time_ms),
818 send_time_ms(send_time_ms),
819 recv_time_ms(recv_time_ms),
820 render_time_ms(render_time_ms),
821 encoded_frame_size(encoded_frame_size) {}
822
823VideoAnalyzer::Sample::Sample(int dropped,
824 int64_t input_time_ms,
825 int64_t send_time_ms,
826 int64_t recv_time_ms,
827 int64_t render_time_ms,
828 size_t encoded_frame_size,
829 double psnr,
830 double ssim)
831 : dropped(dropped),
832 input_time_ms(input_time_ms),
833 send_time_ms(send_time_ms),
834 recv_time_ms(recv_time_ms),
835 render_time_ms(render_time_ms),
836 encoded_frame_size(encoded_frame_size),
837 psnr(psnr),
838 ssim(ssim) {}
839
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200840VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
841 VideoAnalyzer* analyzer,
842 Clock* clock)
843 : analyzer_(analyzer),
844 send_stream_input_(nullptr),
845 video_capturer_(nullptr),
846 clock_(clock) {}
847
848void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Sebastian Janssonf1f363f2018-08-13 14:24:58 +0200849 test::TestVideoCapturer* video_capturer) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200850 video_capturer_ = video_capturer;
851}
852
853void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
854 const VideoFrame& video_frame) {
855 VideoFrame copy = video_frame;
856 // Frames from the capturer does not have a rtp timestamp.
857 // Create one so it can be used for comparison.
858 RTC_DCHECK_EQ(0, video_frame.timestamp());
859 if (video_frame.ntp_time_ms() == 0)
860 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
861 copy.set_timestamp(copy.ntp_time_ms() * 90);
862 analyzer_->AddCapturedFrameForComparison(copy);
863 rtc::CritScope lock(&crit_);
864 if (send_stream_input_)
865 send_stream_input_->OnFrame(copy);
866}
867
868void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
869 rtc::VideoSinkInterface<VideoFrame>* sink,
870 const rtc::VideoSinkWants& wants) {
871 {
872 rtc::CritScope lock(&crit_);
873 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
874 send_stream_input_ = sink;
875 }
876 if (video_capturer_) {
877 video_capturer_->AddOrUpdateSink(this, wants);
878 }
879}
880
881void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
882 rtc::VideoSinkInterface<VideoFrame>* sink) {
883 rtc::CritScope lock(&crit_);
884 RTC_DCHECK(sink == send_stream_input_);
885 send_stream_input_ = nullptr;
886}
887
888} // namespace webrtc