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