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