blob: c81c9b7c434efc3f27677de34db890c82d8caefc [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),
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +000066 captured_frame_forwarder_(this, clock),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020067 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;
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000337 while (!done_.Wait(test::CallTest::kDefaultTimeoutMs)) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200338 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--"};
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000349 printf("- %s\n", kKeepAliveMessages[iteration++ % 3]);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200350
351 if (last_frames_processed == -1) {
352 last_frames_processed = frames_processed;
353 continue;
354 }
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000355 if (frames_processed == last_frames_processed) {
356 EXPECT_GT(frames_processed, last_frames_processed)
357 << "Analyzer stalled while waiting for test to finish.";
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200358 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;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100461 for (const auto& kv : send_stats.substreams) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200462 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);
Ilya Nikolaevskiyd47d3eb2019-01-21 16:27:17 +0100474 if (receive_stats.width > 0 && receive_stats.height > 0) {
475 pixels_.AddSample(receive_stats.width * receive_stats.height);
476 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200477 }
478
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200479 if (audio_receive_stream_ != nullptr) {
480 AudioReceiveStream::Stats receive_stats =
481 audio_receive_stream_->GetStats();
482 audio_expand_rate_.AddSample(receive_stats.expand_rate);
483 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
484 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
485 }
486
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200487 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
488 }
489}
490
491bool VideoAnalyzer::FrameComparisonThread(void* obj) {
492 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
493}
494
495bool VideoAnalyzer::CompareFrames() {
496 if (AllFramesRecorded())
497 return false;
498
499 FrameComparison comparison;
500
501 if (!PopComparison(&comparison)) {
502 // Wait until new comparison task is available, or test is done.
503 // If done, wake up remaining threads waiting.
504 comparison_available_event_.Wait(1000);
505 if (AllFramesRecorded()) {
506 comparison_available_event_.Set();
507 return false;
508 }
509 return true; // Try again.
510 }
511
512 StartExcludingCpuThreadTime();
513
514 PerformFrameComparison(comparison);
515
516 StopExcludingCpuThreadTime();
517
518 if (FrameProcessed()) {
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000519 PrintResults();
520 if (graph_data_output_file_)
521 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200522 done_.Set();
523 comparison_available_event_.Set();
524 return false;
525 }
526
527 return true;
528}
529
530bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
531 rtc::CritScope crit(&comparison_lock_);
532 // If AllFramesRecorded() is true, it means we have already popped
533 // frames_to_process_ frames from comparisons_, so there is no more work
534 // for this thread to be done. frames_processed_ might still be lower if
535 // all comparisons are not done, but those frames are currently being
536 // worked on by other threads.
537 if (comparisons_.empty() || AllFramesRecorded())
538 return false;
539
540 *comparison = comparisons_.front();
541 comparisons_.pop_front();
542
543 FrameRecorded();
544 return true;
545}
546
547void VideoAnalyzer::FrameRecorded() {
548 rtc::CritScope crit(&comparison_lock_);
549 ++frames_recorded_;
550}
551
552bool VideoAnalyzer::AllFramesRecorded() {
553 rtc::CritScope crit(&comparison_lock_);
554 assert(frames_recorded_ <= frames_to_process_);
555 return frames_recorded_ == frames_to_process_;
556}
557
558bool VideoAnalyzer::FrameProcessed() {
559 rtc::CritScope crit(&comparison_lock_);
560 ++frames_processed_;
561 assert(frames_processed_ <= frames_to_process_);
562 return frames_processed_ == frames_to_process_;
563}
564
565void VideoAnalyzer::PrintResults() {
566 StopMeasuringCpuProcessTime();
567 rtc::CritScope crit(&comparison_lock_);
568 // Record the time from the last freeze until the last rendered frame to
569 // ensure we cover the full timespan of the session. Otherwise the metric
570 // would penalize an early freeze followed by no freezes until the end.
571 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
572 PrintResult("psnr", psnr_, " dB");
573 PrintResult("ssim", ssim_, " score");
574 PrintResult("sender_time", sender_time_, " ms");
575 PrintResult("receiver_time", receiver_time_, " ms");
576 PrintResult("network_time", network_time_, " ms");
577 PrintResult("total_delay_incl_network", end_to_end_, " ms");
578 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
579 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
580 PrintResult("encode_time", encode_time_ms_, " ms");
581 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
582 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
583 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
584 PrintResult("time_between_freezes", time_between_freezes_, " ms");
Ilya Nikolaevskiyd47d3eb2019-01-21 16:27:17 +0100585 PrintResult("pixels_per_frame", pixels_, " px");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200586
587 if (worst_frame_) {
588 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
589 "dB", false);
590 }
591
592 if (receive_stream_ != nullptr) {
593 PrintResult("decode_time", decode_time_ms_, " ms");
594 }
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000595
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200596 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
597 "frames", false);
598 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
599 "%", false);
600
601#if defined(WEBRTC_WIN)
602 // On Linux and Mac in Resident Set some unused pages may be counted.
603 // Therefore this metric will depend on order in which tests are run and
604 // will be flaky.
605 PrintResult("memory_usage", memory_usage_, " bytes");
606#endif
607
608 // Saving only the worst frame for manual analysis. Intention here is to
609 // only detect video corruptions and not to track picture quality. Thus,
610 // jpeg is used here.
611 if (FLAG_save_worst_frame && worst_frame_) {
612 std::string output_dir;
613 test::GetTestArtifactsDir(&output_dir);
614 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100615 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200616 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
617 test::JpegFrameWriter frame_writer(output_path);
618 RTC_CHECK(
619 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
620 }
621
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200622 if (audio_receive_stream_ != nullptr) {
623 PrintResult("audio_expand_rate", audio_expand_rate_, "");
624 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
625 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
626 }
627
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200628 // Disable quality check for quick test, as quality checks may fail
629 // because too few samples were collected.
630 if (!is_quick_test_enabled_) {
631 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
632 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
633 }
634}
635
636void VideoAnalyzer::PerformFrameComparison(
637 const VideoAnalyzer::FrameComparison& comparison) {
638 // Perform expensive psnr and ssim calculations while not holding lock.
639 double psnr = -1.0;
640 double ssim = -1.0;
641 if (comparison.reference && !comparison.dropped) {
642 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
643 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
644 }
645
646 rtc::CritScope crit(&comparison_lock_);
647
648 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
649 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
650 }
651
652 if (graph_data_output_file_) {
653 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
654 comparison.send_time_ms, comparison.recv_time_ms,
655 comparison.render_time_ms,
656 comparison.encoded_frame_size, psnr, ssim));
657 }
658 if (psnr >= 0.0)
659 psnr_.AddSample(psnr);
660 if (ssim >= 0.0)
661 ssim_.AddSample(ssim);
662
663 if (comparison.dropped) {
664 ++dropped_frames_;
665 return;
666 }
667 if (last_unfreeze_time_ms_ == 0)
668 last_unfreeze_time_ms_ = comparison.render_time_ms;
669 if (last_render_time_ != 0) {
670 const int64_t render_delta_ms =
671 comparison.render_time_ms - last_render_time_;
672 rendered_delta_.AddSample(render_delta_ms);
673 if (last_render_delta_ms_ != 0 &&
674 render_delta_ms - last_render_delta_ms_ > 150) {
675 time_between_freezes_.AddSample(last_render_time_ -
676 last_unfreeze_time_ms_);
677 last_unfreeze_time_ms_ = comparison.render_time_ms;
678 }
679 last_render_delta_ms_ = render_delta_ms;
680 }
681 last_render_time_ = comparison.render_time_ms;
682
683 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
684 if (comparison.recv_time_ms > 0) {
685 // If recv_time_ms == 0, this frame consisted of a packets which were all
686 // lost in the transport. Since we were able to render the frame, however,
687 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
688 // happens internally in Call, and we can therefore here not know which
689 // FEC packets that protected the lost media packets. Consequently, we
690 // were not able to record a meaningful recv_time_ms. We therefore skip
691 // this sample.
692 //
693 // The reasoning above does not hold for ULPFEC and RTX, as for those
694 // strategies the timestamp of the received packets is set to the
695 // timestamp of the protected/retransmitted media packet. I.e., then
696 // recv_time_ms != 0, even though the media packets were lost.
697 receiver_time_.AddSample(comparison.render_time_ms -
698 comparison.recv_time_ms);
699 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
700 }
701 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
702 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
703}
704
705void VideoAnalyzer::PrintResult(const char* result_type,
706 test::Statistics stats,
707 const char* unit) {
708 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(),
709 stats.Mean(), stats.StandardDeviation(), unit,
710 false);
711}
712
713void VideoAnalyzer::PrintSamplesToFile() {
714 FILE* out = graph_data_output_file_;
715 rtc::CritScope crit(&comparison_lock_);
716 std::sort(samples_.begin(), samples_.end(),
717 [](const Sample& A, const Sample& B) -> bool {
718 return A.input_time_ms < B.input_time_ms;
719 });
720
721 fprintf(out, "%s\n", graph_title_.c_str());
722 fprintf(out, "%" PRIuS "\n", samples_.size());
723 fprintf(out,
724 "dropped "
725 "input_time_ms "
726 "send_time_ms "
727 "recv_time_ms "
728 "render_time_ms "
729 "encoded_frame_size "
730 "psnr "
731 "ssim "
732 "encode_time_ms\n");
733 for (const Sample& sample : samples_) {
734 fprintf(out,
735 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
736 " %lf %lf\n",
737 sample.dropped, sample.input_time_ms, sample.send_time_ms,
738 sample.recv_time_ms, sample.render_time_ms,
739 sample.encoded_frame_size, sample.psnr, sample.ssim);
740 }
741}
742
743double VideoAnalyzer::GetAverageMediaBitrateBps() {
744 if (last_sending_time_ == first_sending_time_) {
745 return 0;
746 } else {
747 return static_cast<double>(total_media_bytes_) * 8 /
748 (last_sending_time_ - first_sending_time_) *
749 rtc::kNumMillisecsPerSec;
750 }
751}
752
753void VideoAnalyzer::AddCapturedFrameForComparison(
754 const VideoFrame& video_frame) {
755 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000756 frames_.push_back(video_frame);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200757}
758
759void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
760 const VideoFrame& render,
761 bool dropped,
762 int64_t render_time_ms) {
763 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
764 int64_t send_time_ms = send_times_[reference_timestamp];
765 send_times_.erase(reference_timestamp);
766 int64_t recv_time_ms = recv_times_[reference_timestamp];
767 recv_times_.erase(reference_timestamp);
768
769 // TODO(ivica): Make this work for > 2 streams.
770 auto it = encoded_frame_sizes_.find(reference_timestamp);
771 if (it == encoded_frame_sizes_.end())
772 it = encoded_frame_sizes_.find(reference_timestamp - 1);
773 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
774 if (it != encoded_frame_sizes_.end())
775 encoded_frame_sizes_.erase(it);
776
777 rtc::CritScope crit(&comparison_lock_);
778 if (comparisons_.size() < kMaxComparisons) {
779 comparisons_.push_back(FrameComparison(
780 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
781 recv_time_ms, render_time_ms, encoded_size));
782 } else {
783 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
784 send_time_ms, recv_time_ms,
785 render_time_ms, encoded_size));
786 }
787 comparison_available_event_.Set();
788}
789
790VideoAnalyzer::FrameComparison::FrameComparison()
791 : dropped(false),
792 input_time_ms(0),
793 send_time_ms(0),
794 recv_time_ms(0),
795 render_time_ms(0),
796 encoded_frame_size(0) {}
797
798VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
799 const VideoFrame& render,
800 bool dropped,
801 int64_t input_time_ms,
802 int64_t send_time_ms,
803 int64_t recv_time_ms,
804 int64_t render_time_ms,
805 size_t encoded_frame_size)
806 : reference(reference),
807 render(render),
808 dropped(dropped),
809 input_time_ms(input_time_ms),
810 send_time_ms(send_time_ms),
811 recv_time_ms(recv_time_ms),
812 render_time_ms(render_time_ms),
813 encoded_frame_size(encoded_frame_size) {}
814
815VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
816 int64_t input_time_ms,
817 int64_t send_time_ms,
818 int64_t recv_time_ms,
819 int64_t render_time_ms,
820 size_t encoded_frame_size)
821 : dropped(dropped),
822 input_time_ms(input_time_ms),
823 send_time_ms(send_time_ms),
824 recv_time_ms(recv_time_ms),
825 render_time_ms(render_time_ms),
826 encoded_frame_size(encoded_frame_size) {}
827
828VideoAnalyzer::Sample::Sample(int dropped,
829 int64_t input_time_ms,
830 int64_t send_time_ms,
831 int64_t recv_time_ms,
832 int64_t render_time_ms,
833 size_t encoded_frame_size,
834 double psnr,
835 double ssim)
836 : dropped(dropped),
837 input_time_ms(input_time_ms),
838 send_time_ms(send_time_ms),
839 recv_time_ms(recv_time_ms),
840 render_time_ms(render_time_ms),
841 encoded_frame_size(encoded_frame_size),
842 psnr(psnr),
843 ssim(ssim) {}
844
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200845VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
846 VideoAnalyzer* analyzer,
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000847 Clock* clock)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200848 : analyzer_(analyzer),
849 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100850 video_source_(nullptr),
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000851 clock_(clock) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200852
853void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100854 VideoSourceInterface<VideoFrame>* video_source) {
855 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200856}
857
858void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
859 const VideoFrame& video_frame) {
860 VideoFrame copy = video_frame;
861 // Frames from the capturer does not have a rtp timestamp.
862 // Create one so it can be used for comparison.
863 RTC_DCHECK_EQ(0, video_frame.timestamp());
864 if (video_frame.ntp_time_ms() == 0)
865 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
866 copy.set_timestamp(copy.ntp_time_ms() * 90);
867 analyzer_->AddCapturedFrameForComparison(copy);
868 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiyb2d71412019-01-25 13:50:22 +0000869 if (send_stream_input_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200870 send_stream_input_->OnFrame(copy);
871}
872
873void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
874 rtc::VideoSinkInterface<VideoFrame>* sink,
875 const rtc::VideoSinkWants& wants) {
876 {
877 rtc::CritScope lock(&crit_);
878 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
879 send_stream_input_ = sink;
880 }
Niels Möller1c931c42018-12-18 16:08:11 +0100881 if (video_source_) {
882 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200883 }
884}
885
886void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
887 rtc::VideoSinkInterface<VideoFrame>* sink) {
888 rtc::CritScope lock(&crit_);
889 RTC_DCHECK(sink == send_stream_input_);
890 send_stream_input_ = nullptr;
891}
892
893} // namespace webrtc