blob: d74b79ab606b6de81e9dde5b87d8d80694336be1 [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
Steve Antonbd631a02019-03-28 10:51:27 -070015#include "absl/algorithm/container.h"
Niels Möller1c931c42018-12-18 16:08:11 +010016#include "common_video/libyuv/include/webrtc_libyuv.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020017#include "modules/rtp_rtcp/source/rtp_format.h"
18#include "modules/rtp_rtcp/source/rtp_utility.h"
19#include "rtc_base/cpu_time.h"
20#include "rtc_base/flags.h"
21#include "rtc_base/format_macros.h"
22#include "rtc_base/memory_usage.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020023#include "system_wrappers/include/cpu_info.h"
24#include "test/call_test.h"
Steve Anton10542f22019-01-11 09:11:00 -080025#include "test/testsupport/file_utils.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020026#include "test/testsupport/frame_writer.h"
27#include "test/testsupport/perf_test.h"
28#include "test/testsupport/test_artifacts.h"
29
Mirko Bonadei2dfa9982018-10-18 11:35:32 +020030WEBRTC_DEFINE_bool(
31 save_worst_frame,
32 false,
33 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
34 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 12:57:37 +020035
36namespace webrtc {
37namespace {
38constexpr int kSendStatsPollingIntervalMs = 1000;
39constexpr size_t kMaxComparisons = 10;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010040// How often is keep alive message printed.
41constexpr int kKeepAliveIntervalSeconds = 30;
42// Interval between checking that the test is over.
43constexpr int kProbingIntervalMs = 500;
44constexpr int kKeepAliveIntervalIterations =
45 kKeepAliveIntervalSeconds * 1000 / kProbingIntervalMs;
Sebastian Janssond4c5d632018-07-10 12:57:37 +020046
47bool IsFlexfec(int payload_type) {
48 return payload_type == test::CallTest::kFlexfecPayloadType;
49}
50} // namespace
51
Artem Titovff7730d2019-04-02 13:46:53 +020052VideoAnalyzer::VideoAnalyzer(
53 test::LayerFilteringTransport* transport,
54 const std::string& test_label,
55 double avg_psnr_threshold,
56 double avg_ssim_threshold,
57 int duration_frames,
58 FILE* graph_data_output_file,
59 const std::string& graph_title,
60 uint32_t ssrc_to_analyze,
61 uint32_t rtx_ssrc_to_analyze,
62 size_t selected_stream,
63 int selected_sl,
64 int selected_tl,
65 bool is_quick_test_enabled,
66 Clock* clock,
67 std::string rtp_dump_name,
68 test::SingleThreadedTaskQueueForTesting* task_queue)
Sebastian Janssond4c5d632018-07-10 12:57:37 +020069 : transport_(transport),
70 receiver_(nullptr),
71 call_(nullptr),
72 send_stream_(nullptr),
73 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 14:10:56 +020074 audio_receive_stream_(nullptr),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +010075 captured_frame_forwarder_(this, clock, duration_frames),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020076 test_label_(test_label),
77 graph_data_output_file_(graph_data_output_file),
78 graph_title_(graph_title),
79 ssrc_to_analyze_(ssrc_to_analyze),
80 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
81 selected_stream_(selected_stream),
82 selected_sl_(selected_sl),
83 selected_tl_(selected_tl),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020084 last_fec_bytes_(0),
85 frames_to_process_(duration_frames),
86 frames_recorded_(0),
87 frames_processed_(0),
88 dropped_frames_(0),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010089 captured_frames_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020090 dropped_frames_before_first_encode_(0),
91 dropped_frames_before_rendering_(0),
92 last_render_time_(0),
93 last_render_delta_ms_(0),
94 last_unfreeze_time_ms_(0),
95 rtp_timestamp_delta_(0),
96 total_media_bytes_(0),
97 first_sending_time_(0),
98 last_sending_time_(0),
99 cpu_time_(0),
100 wallclock_time_(0),
101 avg_psnr_threshold_(avg_psnr_threshold),
102 avg_ssim_threshold_(avg_ssim_threshold),
103 is_quick_test_enabled_(is_quick_test_enabled),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200104 done_(true, false),
105 clock_(clock),
Artem Titovff7730d2019-04-02 13:46:53 +0200106 start_ms_(clock->TimeInMilliseconds()),
107 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200108 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
109
110 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
111 // so that we don't accidentally starve "real" worker threads (codec etc).
112 // Also, don't allocate more than kMaxComparisonThreads, even if there are
113 // spare cores.
114
115 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
116 RTC_DCHECK_GE(num_cores, 1);
117 static const uint32_t kMinCoresLeft = 4;
118 static const uint32_t kMaxComparisonThreads = 8;
119
120 if (num_cores <= kMinCoresLeft) {
121 num_cores = 1;
122 } else {
123 num_cores -= kMinCoresLeft;
124 num_cores = std::min(num_cores, kMaxComparisonThreads);
125 }
126
127 for (uint32_t i = 0; i < num_cores; ++i) {
128 rtc::PlatformThread* thread =
129 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
130 thread->Start();
131 comparison_thread_pool_.push_back(thread);
132 }
133
134 if (!rtp_dump_name.empty()) {
135 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
136 rtp_file_writer_.reset(test::RtpFileWriter::Create(
137 test::RtpFileWriter::kRtpDump, rtp_dump_name));
138 }
139}
140
141VideoAnalyzer::~VideoAnalyzer() {
142 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
143 thread->Stop();
144 delete thread;
145 }
146}
147
148void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
149 receiver_ = receiver;
150}
151
Niels Möller1c931c42018-12-18 16:08:11 +0100152void VideoAnalyzer::SetSource(
153 rtc::VideoSourceInterface<VideoFrame>* video_source,
154 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200155 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 16:08:11 +0100156 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200157 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 16:08:11 +0100158 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200159}
160
161void VideoAnalyzer::SetCall(Call* call) {
162 rtc::CritScope lock(&crit_);
163 RTC_DCHECK(!call_);
164 call_ = call;
165}
166
167void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
168 rtc::CritScope lock(&crit_);
169 RTC_DCHECK(!send_stream_);
170 send_stream_ = stream;
171}
172
173void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
174 rtc::CritScope lock(&crit_);
175 RTC_DCHECK(!receive_stream_);
176 receive_stream_ = stream;
177}
178
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200179void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
180 rtc::CritScope lock(&crit_);
181 RTC_CHECK(!audio_receive_stream_);
182 audio_receive_stream_ = recv_stream;
183}
184
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200185rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
186 return &captured_frame_forwarder_;
187}
188
189rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
190 return &captured_frame_forwarder_;
191}
192
193PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
194 MediaType media_type,
195 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 11:03:12 +0200196 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200197 // Ignore timestamps of RTCP packets. They're not synchronized with
198 // RTP packet timestamps and so they would confuse wrap_handler_.
199 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
Niels Möller70082872018-08-07 11:03:12 +0200200 return receiver_->DeliverPacket(media_type, std::move(packet),
201 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200202 }
203
204 if (rtp_file_writer_) {
205 test::RtpPacket p;
206 memcpy(p.data, packet.cdata(), packet.size());
207 p.length = packet.size();
208 p.original_length = packet.size();
209 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
210 rtp_file_writer_->WritePacket(&p);
211 }
212
213 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
214 RTPHeader header;
215 parser.Parse(&header);
216 if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
217 header.ssrc == rtx_ssrc_to_analyze_)) {
218 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
219 // (FlexFEC and media are sent on different SSRCs, which have different
220 // timestamps spaces.)
221 // Also ignore packets from wrong SSRC, but include retransmits.
222 rtc::CritScope lock(&crit_);
223 int64_t timestamp =
224 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100225 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200226 }
227
Niels Möller70082872018-08-07 11:03:12 +0200228 return receiver_->DeliverPacket(media_type, std::move(packet),
229 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200230}
231
232void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
233 rtc::CritScope lock(&crit_);
234 if (!first_encoded_timestamp_) {
235 while (frames_.front().timestamp() != video_frame.timestamp()) {
236 ++dropped_frames_before_first_encode_;
237 frames_.pop_front();
238 RTC_CHECK(!frames_.empty());
239 }
240 first_encoded_timestamp_ = video_frame.timestamp();
241 }
242}
243
Niels Möller88be9722018-10-10 10:58:52 +0200244void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200245 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200246 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
247 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200248 }
249}
250
251bool VideoAnalyzer::SendRtp(const uint8_t* packet,
252 size_t length,
253 const PacketOptions& options) {
254 RtpUtility::RtpHeaderParser parser(packet, length);
255 RTPHeader header;
256 parser.Parse(&header);
257
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100258 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200259
260 bool result = transport_->SendRtp(packet, length, options);
261 {
262 rtc::CritScope lock(&crit_);
263 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
264 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
265 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
266 }
267
268 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
269 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
270 // (FlexFEC and media are sent on different SSRCs, which have different
271 // timestamps spaces.)
272 // Also ignore packets from wrong SSRC and retransmits.
273 int64_t timestamp =
274 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
275 send_times_[timestamp] = current_time;
276
277 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
278 encoded_frame_sizes_[timestamp] +=
279 length - (header.headerLength + header.paddingLength);
280 total_media_bytes_ +=
281 length - (header.headerLength + header.paddingLength);
282 }
283 if (first_sending_time_ == 0)
284 first_sending_time_ = current_time;
285 last_sending_time_ = current_time;
286 }
287 }
288 return result;
289}
290
291bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
292 return transport_->SendRtcp(packet, length);
293}
294
295void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100296 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200297
298 rtc::CritScope lock(&crit_);
299
300 StartExcludingCpuThreadTime();
301
302 int64_t send_timestamp =
303 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
304
305 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
306 if (!last_rendered_frame_) {
307 // No previous frame rendered, this one was dropped after sending but
308 // before rendering.
309 ++dropped_frames_before_rendering_;
310 } else {
311 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
312 render_time_ms);
313 }
314 frames_.pop_front();
315 RTC_DCHECK(!frames_.empty());
316 }
317
318 VideoFrame reference_frame = frames_.front();
319 frames_.pop_front();
320 int64_t reference_timestamp =
321 wrap_handler_.Unwrap(reference_frame.timestamp());
322 if (send_timestamp == reference_timestamp - 1) {
323 // TODO(ivica): Make this work for > 2 streams.
324 // Look at RTPSender::BuildRTPHeader.
325 ++send_timestamp;
326 }
327 ASSERT_EQ(reference_timestamp, send_timestamp);
328
329 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
330
331 last_rendered_frame_ = video_frame;
332
333 StopExcludingCpuThreadTime();
334}
335
336void VideoAnalyzer::Wait() {
337 // Frame comparisons can be very expensive. Wait for test to be done, but
338 // at time-out check if frames_processed is going up. If so, give it more
339 // time, otherwise fail. Hopefully this will reduce test flakiness.
340
Artem Titovff7730d2019-04-02 13:46:53 +0200341 {
342 rtc::CritScope lock(&comparison_lock_);
343 stop_stats_poller_ = false;
344 stats_polling_task_id_ = task_queue_->PostDelayedTask(
345 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
346 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200347
348 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100349 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200350 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100351
352 while (!done_.Wait(kProbingIntervalMs)) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200353 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100354 int frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200355 {
356 rtc::CritScope crit(&comparison_lock_);
357 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100358 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200359 }
360
361 // Print some output so test infrastructure won't think we've crashed.
362 const char* kKeepAliveMessages[3] = {
363 "Uh, I'm-I'm not quite dead, sir.",
364 "Uh, I-I think uh, I could pull through, sir.",
365 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100366 if (++iteration % kKeepAliveIntervalIterations == 0) {
367 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
368 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200369
370 if (last_frames_processed == -1) {
371 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100372 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200373 continue;
374 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100375 if (frames_processed == last_frames_processed &&
376 last_frames_captured == frames_captured) {
377 if (frames_captured < frames_to_process_) {
378 EXPECT_GT(frames_processed, last_frames_processed)
379 << "Analyzer stalled while waiting for test to finish.";
380 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200381 done_.Set();
382 break;
383 }
384 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100385 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200386 }
387
388 if (iteration > 0)
389 printf("- Farewell, sweet Concorde!\n");
390
Artem Titovff7730d2019-04-02 13:46:53 +0200391 {
392 rtc::CritScope lock(&comparison_lock_);
393 stop_stats_poller_ = true;
394 task_queue_->CancelTask(stats_polling_task_id_);
395 }
396
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100397 PrintResults();
398 if (graph_data_output_file_)
399 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200400}
401
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200402void VideoAnalyzer::StartMeasuringCpuProcessTime() {
403 rtc::CritScope lock(&cpu_measurement_lock_);
404 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
405 wallclock_time_ -= rtc::SystemTimeNanos();
406}
407
408void VideoAnalyzer::StopMeasuringCpuProcessTime() {
409 rtc::CritScope lock(&cpu_measurement_lock_);
410 cpu_time_ += rtc::GetProcessCpuTimeNanos();
411 wallclock_time_ += rtc::SystemTimeNanos();
412}
413
414void VideoAnalyzer::StartExcludingCpuThreadTime() {
415 rtc::CritScope lock(&cpu_measurement_lock_);
416 cpu_time_ += rtc::GetThreadCpuTimeNanos();
417}
418
419void VideoAnalyzer::StopExcludingCpuThreadTime() {
420 rtc::CritScope lock(&cpu_measurement_lock_);
421 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
422}
423
424double VideoAnalyzer::GetCpuUsagePercent() {
425 rtc::CritScope lock(&cpu_measurement_lock_);
426 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
427}
428
429bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
430 const uint8_t* packet,
431 size_t length,
432 const RTPHeader& header) {
433 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
434 header.payloadType != test::CallTest::kPayloadTypeVP8) {
435 return true;
436 } else {
437 // Get VP8 and VP9 specific header to check layers indexes.
438 const uint8_t* payload = packet + header.headerLength;
439 const size_t payload_length = length - header.headerLength;
440 const size_t payload_data_length = payload_length - header.paddingLength;
441 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
442 std::unique_ptr<RtpDepacketizer> depacketizer(
443 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
444 RtpDepacketizer::ParsedPayload parsed_payload;
445 bool result =
446 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
447 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200448
449 int temporal_idx;
450 int spatial_idx;
451 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000452 temporal_idx = absl::get<RTPVideoHeaderVP8>(
453 parsed_payload.video_header().video_type_header)
454 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200455 spatial_idx = kNoTemporalIdx;
456 } else {
457 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
458 parsed_payload.video_header().video_type_header);
459 temporal_idx = vp9_header.temporal_idx;
460 spatial_idx = vp9_header.spatial_idx;
461 }
462
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200463 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
464 temporal_idx <= selected_tl_) &&
465 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
466 spatial_idx <= selected_sl_);
467 }
468}
469
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200470void VideoAnalyzer::PollStats() {
Artem Titovff7730d2019-04-02 13:46:53 +0200471 rtc::CritScope crit(&comparison_lock_);
472 if (stop_stats_poller_) {
473 return;
Artem Titovf537da62019-04-02 13:46:53 +0200474 }
Artem Titovff7730d2019-04-02 13:46:53 +0200475
476 Call::Stats call_stats = call_->GetStats();
477 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
478
479 VideoSendStream::Stats send_stats = send_stream_->GetStats();
480 // It's not certain that we yet have estimates for any of these stats.
481 // Check that they are positive before mixing them in.
482 if (send_stats.encode_frame_rate > 0)
483 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
484 if (send_stats.avg_encode_time_ms > 0)
485 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
486 if (send_stats.encode_usage_percent > 0)
487 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
488 if (send_stats.media_bitrate_bps > 0)
489 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
490 size_t fec_bytes = 0;
491 for (const auto& kv : send_stats.substreams) {
492 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
493 kv.second.rtp_stats.fec.padding_bytes;
494 }
495 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
496 last_fec_bytes_ = fec_bytes;
497
498 if (receive_stream_ != nullptr) {
499 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
500 if (receive_stats.decode_ms > 0)
501 decode_time_ms_.AddSample(receive_stats.decode_ms);
502 if (receive_stats.max_decode_ms > 0)
503 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
504 if (receive_stats.width > 0 && receive_stats.height > 0) {
505 pixels_.AddSample(receive_stats.width * receive_stats.height);
506 }
507 }
508
509 if (audio_receive_stream_ != nullptr) {
510 AudioReceiveStream::Stats receive_stats = audio_receive_stream_->GetStats();
511 audio_expand_rate_.AddSample(receive_stats.expand_rate);
512 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
513 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
514 }
515
516 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
517
518 stats_polling_task_id_ = task_queue_->PostDelayedTask(
519 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200520}
521
522bool VideoAnalyzer::FrameComparisonThread(void* obj) {
523 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
524}
525
526bool VideoAnalyzer::CompareFrames() {
527 if (AllFramesRecorded())
528 return false;
529
530 FrameComparison comparison;
531
532 if (!PopComparison(&comparison)) {
533 // Wait until new comparison task is available, or test is done.
534 // If done, wake up remaining threads waiting.
535 comparison_available_event_.Wait(1000);
536 if (AllFramesRecorded()) {
537 comparison_available_event_.Set();
538 return false;
539 }
540 return true; // Try again.
541 }
542
543 StartExcludingCpuThreadTime();
544
545 PerformFrameComparison(comparison);
546
547 StopExcludingCpuThreadTime();
548
549 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200550 done_.Set();
551 comparison_available_event_.Set();
552 return false;
553 }
554
555 return true;
556}
557
558bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
559 rtc::CritScope crit(&comparison_lock_);
560 // If AllFramesRecorded() is true, it means we have already popped
561 // frames_to_process_ frames from comparisons_, so there is no more work
562 // for this thread to be done. frames_processed_ might still be lower if
563 // all comparisons are not done, but those frames are currently being
564 // worked on by other threads.
565 if (comparisons_.empty() || AllFramesRecorded())
566 return false;
567
568 *comparison = comparisons_.front();
569 comparisons_.pop_front();
570
571 FrameRecorded();
572 return true;
573}
574
575void VideoAnalyzer::FrameRecorded() {
576 rtc::CritScope crit(&comparison_lock_);
577 ++frames_recorded_;
578}
579
580bool VideoAnalyzer::AllFramesRecorded() {
581 rtc::CritScope crit(&comparison_lock_);
582 assert(frames_recorded_ <= frames_to_process_);
583 return frames_recorded_ == frames_to_process_;
584}
585
586bool VideoAnalyzer::FrameProcessed() {
587 rtc::CritScope crit(&comparison_lock_);
588 ++frames_processed_;
589 assert(frames_processed_ <= frames_to_process_);
590 return frames_processed_ == frames_to_process_;
591}
592
593void VideoAnalyzer::PrintResults() {
594 StopMeasuringCpuProcessTime();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100595 int frames_left;
596 {
597 rtc::CritScope crit(&crit_);
598 frames_left = frames_.size();
599 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200600 rtc::CritScope crit(&comparison_lock_);
601 // Record the time from the last freeze until the last rendered frame to
602 // ensure we cover the full timespan of the session. Otherwise the metric
603 // would penalize an early freeze followed by no freezes until the end.
604 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
605 PrintResult("psnr", psnr_, " dB");
606 PrintResult("ssim", ssim_, " score");
607 PrintResult("sender_time", sender_time_, " ms");
608 PrintResult("receiver_time", receiver_time_, " ms");
609 PrintResult("network_time", network_time_, " ms");
610 PrintResult("total_delay_incl_network", end_to_end_, " ms");
611 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
612 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
613 PrintResult("encode_time", encode_time_ms_, " ms");
614 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
615 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
616 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
617 PrintResult("time_between_freezes", time_between_freezes_, " ms");
Ilya Nikolaevskiyd47d3eb2019-01-21 16:27:17 +0100618 PrintResult("pixels_per_frame", pixels_, " px");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200619
620 if (worst_frame_) {
621 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
622 "dB", false);
623 }
624
625 if (receive_stream_ != nullptr) {
626 PrintResult("decode_time", decode_time_ms_, " ms");
627 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100628 dropped_frames_ += dropped_frames_before_first_encode_ +
629 dropped_frames_before_rendering_ + frames_left;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200630 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
631 "frames", false);
632 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
633 "%", false);
634
635#if defined(WEBRTC_WIN)
636 // On Linux and Mac in Resident Set some unused pages may be counted.
637 // Therefore this metric will depend on order in which tests are run and
638 // will be flaky.
639 PrintResult("memory_usage", memory_usage_, " bytes");
640#endif
641
642 // Saving only the worst frame for manual analysis. Intention here is to
643 // only detect video corruptions and not to track picture quality. Thus,
644 // jpeg is used here.
645 if (FLAG_save_worst_frame && worst_frame_) {
646 std::string output_dir;
647 test::GetTestArtifactsDir(&output_dir);
648 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100649 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200650 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
651 test::JpegFrameWriter frame_writer(output_path);
652 RTC_CHECK(
653 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
654 }
655
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200656 if (audio_receive_stream_ != nullptr) {
657 PrintResult("audio_expand_rate", audio_expand_rate_, "");
658 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
659 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
660 }
661
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200662 // Disable quality check for quick test, as quality checks may fail
663 // because too few samples were collected.
664 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200665 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
666 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200667 }
668}
669
670void VideoAnalyzer::PerformFrameComparison(
671 const VideoAnalyzer::FrameComparison& comparison) {
672 // Perform expensive psnr and ssim calculations while not holding lock.
673 double psnr = -1.0;
674 double ssim = -1.0;
675 if (comparison.reference && !comparison.dropped) {
676 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
677 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
678 }
679
680 rtc::CritScope crit(&comparison_lock_);
681
682 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
683 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
684 }
685
686 if (graph_data_output_file_) {
687 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
688 comparison.send_time_ms, comparison.recv_time_ms,
689 comparison.render_time_ms,
690 comparison.encoded_frame_size, psnr, ssim));
691 }
692 if (psnr >= 0.0)
693 psnr_.AddSample(psnr);
694 if (ssim >= 0.0)
695 ssim_.AddSample(ssim);
696
697 if (comparison.dropped) {
698 ++dropped_frames_;
699 return;
700 }
701 if (last_unfreeze_time_ms_ == 0)
702 last_unfreeze_time_ms_ = comparison.render_time_ms;
703 if (last_render_time_ != 0) {
704 const int64_t render_delta_ms =
705 comparison.render_time_ms - last_render_time_;
706 rendered_delta_.AddSample(render_delta_ms);
707 if (last_render_delta_ms_ != 0 &&
708 render_delta_ms - last_render_delta_ms_ > 150) {
709 time_between_freezes_.AddSample(last_render_time_ -
710 last_unfreeze_time_ms_);
711 last_unfreeze_time_ms_ = comparison.render_time_ms;
712 }
713 last_render_delta_ms_ = render_delta_ms;
714 }
715 last_render_time_ = comparison.render_time_ms;
716
717 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
718 if (comparison.recv_time_ms > 0) {
719 // If recv_time_ms == 0, this frame consisted of a packets which were all
720 // lost in the transport. Since we were able to render the frame, however,
721 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
722 // happens internally in Call, and we can therefore here not know which
723 // FEC packets that protected the lost media packets. Consequently, we
724 // were not able to record a meaningful recv_time_ms. We therefore skip
725 // this sample.
726 //
727 // The reasoning above does not hold for ULPFEC and RTX, as for those
728 // strategies the timestamp of the received packets is set to the
729 // timestamp of the protected/retransmitted media packet. I.e., then
730 // recv_time_ms != 0, even though the media packets were lost.
731 receiver_time_.AddSample(comparison.render_time_ms -
732 comparison.recv_time_ms);
733 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
734 }
735 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
736 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
737}
738
739void VideoAnalyzer::PrintResult(const char* result_type,
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200740 Statistics stats,
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200741 const char* unit) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200742 test::PrintResultMeanAndError(
743 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
744 stats.GetStandardDeviation().value_or(0), unit, false);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200745}
746
747void VideoAnalyzer::PrintSamplesToFile() {
748 FILE* out = graph_data_output_file_;
749 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700750 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
751 return A.input_time_ms < B.input_time_ms;
752 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200753
754 fprintf(out, "%s\n", graph_title_.c_str());
755 fprintf(out, "%" PRIuS "\n", samples_.size());
756 fprintf(out,
757 "dropped "
758 "input_time_ms "
759 "send_time_ms "
760 "recv_time_ms "
761 "render_time_ms "
762 "encoded_frame_size "
763 "psnr "
764 "ssim "
765 "encode_time_ms\n");
766 for (const Sample& sample : samples_) {
767 fprintf(out,
768 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
769 " %lf %lf\n",
770 sample.dropped, sample.input_time_ms, sample.send_time_ms,
771 sample.recv_time_ms, sample.render_time_ms,
772 sample.encoded_frame_size, sample.psnr, sample.ssim);
773 }
774}
775
776double VideoAnalyzer::GetAverageMediaBitrateBps() {
777 if (last_sending_time_ == first_sending_time_) {
778 return 0;
779 } else {
780 return static_cast<double>(total_media_bytes_) * 8 /
781 (last_sending_time_ - first_sending_time_) *
782 rtc::kNumMillisecsPerSec;
783 }
784}
785
786void VideoAnalyzer::AddCapturedFrameForComparison(
787 const VideoFrame& video_frame) {
788 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100789 if (captured_frames_ < frames_to_process_) {
790 ++captured_frames_;
791 frames_.push_back(video_frame);
792 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200793}
794
795void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
796 const VideoFrame& render,
797 bool dropped,
798 int64_t render_time_ms) {
799 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
800 int64_t send_time_ms = send_times_[reference_timestamp];
801 send_times_.erase(reference_timestamp);
802 int64_t recv_time_ms = recv_times_[reference_timestamp];
803 recv_times_.erase(reference_timestamp);
804
805 // TODO(ivica): Make this work for > 2 streams.
806 auto it = encoded_frame_sizes_.find(reference_timestamp);
807 if (it == encoded_frame_sizes_.end())
808 it = encoded_frame_sizes_.find(reference_timestamp - 1);
809 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
810 if (it != encoded_frame_sizes_.end())
811 encoded_frame_sizes_.erase(it);
812
813 rtc::CritScope crit(&comparison_lock_);
814 if (comparisons_.size() < kMaxComparisons) {
815 comparisons_.push_back(FrameComparison(
816 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
817 recv_time_ms, render_time_ms, encoded_size));
818 } else {
819 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
820 send_time_ms, recv_time_ms,
821 render_time_ms, encoded_size));
822 }
823 comparison_available_event_.Set();
824}
825
826VideoAnalyzer::FrameComparison::FrameComparison()
827 : dropped(false),
828 input_time_ms(0),
829 send_time_ms(0),
830 recv_time_ms(0),
831 render_time_ms(0),
832 encoded_frame_size(0) {}
833
834VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
835 const VideoFrame& render,
836 bool dropped,
837 int64_t input_time_ms,
838 int64_t send_time_ms,
839 int64_t recv_time_ms,
840 int64_t render_time_ms,
841 size_t encoded_frame_size)
842 : reference(reference),
843 render(render),
844 dropped(dropped),
845 input_time_ms(input_time_ms),
846 send_time_ms(send_time_ms),
847 recv_time_ms(recv_time_ms),
848 render_time_ms(render_time_ms),
849 encoded_frame_size(encoded_frame_size) {}
850
851VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
852 int64_t input_time_ms,
853 int64_t send_time_ms,
854 int64_t recv_time_ms,
855 int64_t render_time_ms,
856 size_t encoded_frame_size)
857 : dropped(dropped),
858 input_time_ms(input_time_ms),
859 send_time_ms(send_time_ms),
860 recv_time_ms(recv_time_ms),
861 render_time_ms(render_time_ms),
862 encoded_frame_size(encoded_frame_size) {}
863
864VideoAnalyzer::Sample::Sample(int dropped,
865 int64_t input_time_ms,
866 int64_t send_time_ms,
867 int64_t recv_time_ms,
868 int64_t render_time_ms,
869 size_t encoded_frame_size,
870 double psnr,
871 double ssim)
872 : dropped(dropped),
873 input_time_ms(input_time_ms),
874 send_time_ms(send_time_ms),
875 recv_time_ms(recv_time_ms),
876 render_time_ms(render_time_ms),
877 encoded_frame_size(encoded_frame_size),
878 psnr(psnr),
879 ssim(ssim) {}
880
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200881VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
882 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100883 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100884 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200885 : analyzer_(analyzer),
886 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100887 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100888 clock_(clock),
889 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100890 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200891
892void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100893 VideoSourceInterface<VideoFrame>* video_source) {
894 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200895}
896
897void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
898 const VideoFrame& video_frame) {
899 VideoFrame copy = video_frame;
900 // Frames from the capturer does not have a rtp timestamp.
901 // Create one so it can be used for comparison.
902 RTC_DCHECK_EQ(0, video_frame.timestamp());
903 if (video_frame.ntp_time_ms() == 0)
904 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
905 copy.set_timestamp(copy.ntp_time_ms() * 90);
906 analyzer_->AddCapturedFrameForComparison(copy);
907 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100908 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100909 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200910 send_stream_input_->OnFrame(copy);
911}
912
913void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
914 rtc::VideoSinkInterface<VideoFrame>* sink,
915 const rtc::VideoSinkWants& wants) {
916 {
917 rtc::CritScope lock(&crit_);
918 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
919 send_stream_input_ = sink;
920 }
Niels Möller1c931c42018-12-18 16:08:11 +0100921 if (video_source_) {
922 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200923 }
924}
925
926void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
927 rtc::VideoSinkInterface<VideoFrame>* sink) {
928 rtc::CritScope lock(&crit_);
929 RTC_DCHECK(sink == send_stream_input_);
930 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200931}
932
933} // namespace webrtc