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