blob: b72048e6d904a616f5a7e3f6fb3c2e37889385cf [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_);
223 recv_times_[timestamp] =
224 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
225 }
226
Niels Möller70082872018-08-07 11:03:12 +0200227 return receiver_->DeliverPacket(media_type, std::move(packet),
228 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200229}
230
231void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
232 rtc::CritScope lock(&crit_);
233 if (!first_encoded_timestamp_) {
234 while (frames_.front().timestamp() != video_frame.timestamp()) {
235 ++dropped_frames_before_first_encode_;
236 frames_.pop_front();
237 RTC_CHECK(!frames_.empty());
238 }
239 first_encoded_timestamp_ = video_frame.timestamp();
240 }
241}
242
Niels Möller88be9722018-10-10 10:58:52 +0200243void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200244 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200245 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
246 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200247 }
248}
249
250bool VideoAnalyzer::SendRtp(const uint8_t* packet,
251 size_t length,
252 const PacketOptions& options) {
253 RtpUtility::RtpHeaderParser parser(packet, length);
254 RTPHeader header;
255 parser.Parse(&header);
256
257 int64_t current_time = Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
258
259 bool result = transport_->SendRtp(packet, length, options);
260 {
261 rtc::CritScope lock(&crit_);
262 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
263 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
264 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
265 }
266
267 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
268 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
269 // (FlexFEC and media are sent on different SSRCs, which have different
270 // timestamps spaces.)
271 // Also ignore packets from wrong SSRC and retransmits.
272 int64_t timestamp =
273 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
274 send_times_[timestamp] = current_time;
275
276 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
277 encoded_frame_sizes_[timestamp] +=
278 length - (header.headerLength + header.paddingLength);
279 total_media_bytes_ +=
280 length - (header.headerLength + header.paddingLength);
281 }
282 if (first_sending_time_ == 0)
283 first_sending_time_ = current_time;
284 last_sending_time_ = current_time;
285 }
286 }
287 return result;
288}
289
290bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
291 return transport_->SendRtcp(packet, length);
292}
293
294void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
295 int64_t render_time_ms =
296 Clock::GetRealTimeClock()->CurrentNtpInMilliseconds();
297
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
341 stats_polling_thread_.Start();
342
343 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100344 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200345 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100346
347 while (!done_.Wait(kProbingIntervalMs)) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200348 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100349 int frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200350 {
351 rtc::CritScope crit(&comparison_lock_);
352 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100353 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200354 }
355
356 // Print some output so test infrastructure won't think we've crashed.
357 const char* kKeepAliveMessages[3] = {
358 "Uh, I'm-I'm not quite dead, sir.",
359 "Uh, I-I think uh, I could pull through, sir.",
360 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100361 if (++iteration % kKeepAliveIntervalIterations == 0) {
362 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
363 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200364
365 if (last_frames_processed == -1) {
366 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100367 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200368 continue;
369 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100370 if (frames_processed == last_frames_processed &&
371 last_frames_captured == frames_captured) {
372 if (frames_captured < frames_to_process_) {
373 EXPECT_GT(frames_processed, last_frames_processed)
374 << "Analyzer stalled while waiting for test to finish.";
375 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200376 done_.Set();
377 break;
378 }
379 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100380 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200381 }
382
383 if (iteration > 0)
384 printf("- Farewell, sweet Concorde!\n");
385
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100386 PrintResults();
387 if (graph_data_output_file_)
388 PrintSamplesToFile();
389
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200390 stats_polling_thread_.Stop();
391}
392
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200393void VideoAnalyzer::StartMeasuringCpuProcessTime() {
394 rtc::CritScope lock(&cpu_measurement_lock_);
395 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
396 wallclock_time_ -= rtc::SystemTimeNanos();
397}
398
399void VideoAnalyzer::StopMeasuringCpuProcessTime() {
400 rtc::CritScope lock(&cpu_measurement_lock_);
401 cpu_time_ += rtc::GetProcessCpuTimeNanos();
402 wallclock_time_ += rtc::SystemTimeNanos();
403}
404
405void VideoAnalyzer::StartExcludingCpuThreadTime() {
406 rtc::CritScope lock(&cpu_measurement_lock_);
407 cpu_time_ += rtc::GetThreadCpuTimeNanos();
408}
409
410void VideoAnalyzer::StopExcludingCpuThreadTime() {
411 rtc::CritScope lock(&cpu_measurement_lock_);
412 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
413}
414
415double VideoAnalyzer::GetCpuUsagePercent() {
416 rtc::CritScope lock(&cpu_measurement_lock_);
417 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
418}
419
420bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
421 const uint8_t* packet,
422 size_t length,
423 const RTPHeader& header) {
424 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
425 header.payloadType != test::CallTest::kPayloadTypeVP8) {
426 return true;
427 } else {
428 // Get VP8 and VP9 specific header to check layers indexes.
429 const uint8_t* payload = packet + header.headerLength;
430 const size_t payload_length = length - header.headerLength;
431 const size_t payload_data_length = payload_length - header.paddingLength;
432 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
433 std::unique_ptr<RtpDepacketizer> depacketizer(
434 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
435 RtpDepacketizer::ParsedPayload parsed_payload;
436 bool result =
437 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
438 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200439
440 int temporal_idx;
441 int spatial_idx;
442 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000443 temporal_idx = absl::get<RTPVideoHeaderVP8>(
444 parsed_payload.video_header().video_type_header)
445 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200446 spatial_idx = kNoTemporalIdx;
447 } else {
448 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
449 parsed_payload.video_header().video_type_header);
450 temporal_idx = vp9_header.temporal_idx;
451 spatial_idx = vp9_header.spatial_idx;
452 }
453
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200454 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
455 temporal_idx <= selected_tl_) &&
456 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
457 spatial_idx <= selected_sl_);
458 }
459}
460
461void VideoAnalyzer::PollStatsThread(void* obj) {
462 static_cast<VideoAnalyzer*>(obj)->PollStats();
463}
464
465void VideoAnalyzer::PollStats() {
466 while (!done_.Wait(kSendStatsPollingIntervalMs)) {
467 rtc::CritScope crit(&comparison_lock_);
468
469 Call::Stats call_stats = call_->GetStats();
470 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
471
472 VideoSendStream::Stats send_stats = send_stream_->GetStats();
473 // It's not certain that we yet have estimates for any of these stats.
474 // Check that they are positive before mixing them in.
475 if (send_stats.encode_frame_rate > 0)
476 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
477 if (send_stats.avg_encode_time_ms > 0)
478 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
479 if (send_stats.encode_usage_percent > 0)
480 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
481 if (send_stats.media_bitrate_bps > 0)
482 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
483 size_t fec_bytes = 0;
Mirko Bonadei739baf02019-01-27 17:29:42 +0100484 for (const auto& kv : send_stats.substreams) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200485 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
486 kv.second.rtp_stats.fec.padding_bytes;
487 }
488 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
489 last_fec_bytes_ = fec_bytes;
490
491 if (receive_stream_ != nullptr) {
492 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
493 if (receive_stats.decode_ms > 0)
494 decode_time_ms_.AddSample(receive_stats.decode_ms);
495 if (receive_stats.max_decode_ms > 0)
496 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
Ilya Nikolaevskiyd47d3eb2019-01-21 16:27:17 +0100497 if (receive_stats.width > 0 && receive_stats.height > 0) {
498 pixels_.AddSample(receive_stats.width * receive_stats.height);
499 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200500 }
501
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200502 if (audio_receive_stream_ != nullptr) {
503 AudioReceiveStream::Stats receive_stats =
504 audio_receive_stream_->GetStats();
505 audio_expand_rate_.AddSample(receive_stats.expand_rate);
506 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
507 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
508 }
509
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200510 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
511 }
512}
513
514bool VideoAnalyzer::FrameComparisonThread(void* obj) {
515 return static_cast<VideoAnalyzer*>(obj)->CompareFrames();
516}
517
518bool VideoAnalyzer::CompareFrames() {
519 if (AllFramesRecorded())
520 return false;
521
522 FrameComparison comparison;
523
524 if (!PopComparison(&comparison)) {
525 // Wait until new comparison task is available, or test is done.
526 // If done, wake up remaining threads waiting.
527 comparison_available_event_.Wait(1000);
528 if (AllFramesRecorded()) {
529 comparison_available_event_.Set();
530 return false;
531 }
532 return true; // Try again.
533 }
534
535 StartExcludingCpuThreadTime();
536
537 PerformFrameComparison(comparison);
538
539 StopExcludingCpuThreadTime();
540
541 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200542 done_.Set();
543 comparison_available_event_.Set();
544 return false;
545 }
546
547 return true;
548}
549
550bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
551 rtc::CritScope crit(&comparison_lock_);
552 // If AllFramesRecorded() is true, it means we have already popped
553 // frames_to_process_ frames from comparisons_, so there is no more work
554 // for this thread to be done. frames_processed_ might still be lower if
555 // all comparisons are not done, but those frames are currently being
556 // worked on by other threads.
557 if (comparisons_.empty() || AllFramesRecorded())
558 return false;
559
560 *comparison = comparisons_.front();
561 comparisons_.pop_front();
562
563 FrameRecorded();
564 return true;
565}
566
567void VideoAnalyzer::FrameRecorded() {
568 rtc::CritScope crit(&comparison_lock_);
569 ++frames_recorded_;
570}
571
572bool VideoAnalyzer::AllFramesRecorded() {
573 rtc::CritScope crit(&comparison_lock_);
574 assert(frames_recorded_ <= frames_to_process_);
575 return frames_recorded_ == frames_to_process_;
576}
577
578bool VideoAnalyzer::FrameProcessed() {
579 rtc::CritScope crit(&comparison_lock_);
580 ++frames_processed_;
581 assert(frames_processed_ <= frames_to_process_);
582 return frames_processed_ == frames_to_process_;
583}
584
585void VideoAnalyzer::PrintResults() {
586 StopMeasuringCpuProcessTime();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100587 int frames_left;
588 {
589 rtc::CritScope crit(&crit_);
590 frames_left = frames_.size();
591 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200592 rtc::CritScope crit(&comparison_lock_);
593 // Record the time from the last freeze until the last rendered frame to
594 // ensure we cover the full timespan of the session. Otherwise the metric
595 // would penalize an early freeze followed by no freezes until the end.
596 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
597 PrintResult("psnr", psnr_, " dB");
598 PrintResult("ssim", ssim_, " score");
599 PrintResult("sender_time", sender_time_, " ms");
600 PrintResult("receiver_time", receiver_time_, " ms");
601 PrintResult("network_time", network_time_, " ms");
602 PrintResult("total_delay_incl_network", end_to_end_, " ms");
603 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
604 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
605 PrintResult("encode_time", encode_time_ms_, " ms");
606 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
607 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
608 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
609 PrintResult("time_between_freezes", time_between_freezes_, " ms");
Ilya Nikolaevskiyd47d3eb2019-01-21 16:27:17 +0100610 PrintResult("pixels_per_frame", pixels_, " px");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200611
612 if (worst_frame_) {
613 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
614 "dB", false);
615 }
616
617 if (receive_stream_ != nullptr) {
618 PrintResult("decode_time", decode_time_ms_, " ms");
619 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100620 dropped_frames_ += dropped_frames_before_first_encode_ +
621 dropped_frames_before_rendering_ + frames_left;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200622 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
623 "frames", false);
624 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
625 "%", false);
626
627#if defined(WEBRTC_WIN)
628 // On Linux and Mac in Resident Set some unused pages may be counted.
629 // Therefore this metric will depend on order in which tests are run and
630 // will be flaky.
631 PrintResult("memory_usage", memory_usage_, " bytes");
632#endif
633
634 // Saving only the worst frame for manual analysis. Intention here is to
635 // only detect video corruptions and not to track picture quality. Thus,
636 // jpeg is used here.
637 if (FLAG_save_worst_frame && worst_frame_) {
638 std::string output_dir;
639 test::GetTestArtifactsDir(&output_dir);
640 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100641 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200642 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
643 test::JpegFrameWriter frame_writer(output_path);
644 RTC_CHECK(
645 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
646 }
647
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200648 if (audio_receive_stream_ != nullptr) {
649 PrintResult("audio_expand_rate", audio_expand_rate_, "");
650 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
651 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
652 }
653
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200654 // Disable quality check for quick test, as quality checks may fail
655 // because too few samples were collected.
656 if (!is_quick_test_enabled_) {
657 EXPECT_GT(psnr_.Mean(), avg_psnr_threshold_);
658 EXPECT_GT(ssim_.Mean(), avg_ssim_threshold_);
659 }
660}
661
662void VideoAnalyzer::PerformFrameComparison(
663 const VideoAnalyzer::FrameComparison& comparison) {
664 // Perform expensive psnr and ssim calculations while not holding lock.
665 double psnr = -1.0;
666 double ssim = -1.0;
667 if (comparison.reference && !comparison.dropped) {
668 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
669 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
670 }
671
672 rtc::CritScope crit(&comparison_lock_);
673
674 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
675 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
676 }
677
678 if (graph_data_output_file_) {
679 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
680 comparison.send_time_ms, comparison.recv_time_ms,
681 comparison.render_time_ms,
682 comparison.encoded_frame_size, psnr, ssim));
683 }
684 if (psnr >= 0.0)
685 psnr_.AddSample(psnr);
686 if (ssim >= 0.0)
687 ssim_.AddSample(ssim);
688
689 if (comparison.dropped) {
690 ++dropped_frames_;
691 return;
692 }
693 if (last_unfreeze_time_ms_ == 0)
694 last_unfreeze_time_ms_ = comparison.render_time_ms;
695 if (last_render_time_ != 0) {
696 const int64_t render_delta_ms =
697 comparison.render_time_ms - last_render_time_;
698 rendered_delta_.AddSample(render_delta_ms);
699 if (last_render_delta_ms_ != 0 &&
700 render_delta_ms - last_render_delta_ms_ > 150) {
701 time_between_freezes_.AddSample(last_render_time_ -
702 last_unfreeze_time_ms_);
703 last_unfreeze_time_ms_ = comparison.render_time_ms;
704 }
705 last_render_delta_ms_ = render_delta_ms;
706 }
707 last_render_time_ = comparison.render_time_ms;
708
709 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
710 if (comparison.recv_time_ms > 0) {
711 // If recv_time_ms == 0, this frame consisted of a packets which were all
712 // lost in the transport. Since we were able to render the frame, however,
713 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
714 // happens internally in Call, and we can therefore here not know which
715 // FEC packets that protected the lost media packets. Consequently, we
716 // were not able to record a meaningful recv_time_ms. We therefore skip
717 // this sample.
718 //
719 // The reasoning above does not hold for ULPFEC and RTX, as for those
720 // strategies the timestamp of the received packets is set to the
721 // timestamp of the protected/retransmitted media packet. I.e., then
722 // recv_time_ms != 0, even though the media packets were lost.
723 receiver_time_.AddSample(comparison.render_time_ms -
724 comparison.recv_time_ms);
725 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
726 }
727 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
728 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
729}
730
731void VideoAnalyzer::PrintResult(const char* result_type,
732 test::Statistics stats,
733 const char* unit) {
734 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(),
735 stats.Mean(), stats.StandardDeviation(), unit,
736 false);
737}
738
739void VideoAnalyzer::PrintSamplesToFile() {
740 FILE* out = graph_data_output_file_;
741 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700742 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
743 return A.input_time_ms < B.input_time_ms;
744 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200745
746 fprintf(out, "%s\n", graph_title_.c_str());
747 fprintf(out, "%" PRIuS "\n", samples_.size());
748 fprintf(out,
749 "dropped "
750 "input_time_ms "
751 "send_time_ms "
752 "recv_time_ms "
753 "render_time_ms "
754 "encoded_frame_size "
755 "psnr "
756 "ssim "
757 "encode_time_ms\n");
758 for (const Sample& sample : samples_) {
759 fprintf(out,
760 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
761 " %lf %lf\n",
762 sample.dropped, sample.input_time_ms, sample.send_time_ms,
763 sample.recv_time_ms, sample.render_time_ms,
764 sample.encoded_frame_size, sample.psnr, sample.ssim);
765 }
766}
767
768double VideoAnalyzer::GetAverageMediaBitrateBps() {
769 if (last_sending_time_ == first_sending_time_) {
770 return 0;
771 } else {
772 return static_cast<double>(total_media_bytes_) * 8 /
773 (last_sending_time_ - first_sending_time_) *
774 rtc::kNumMillisecsPerSec;
775 }
776}
777
778void VideoAnalyzer::AddCapturedFrameForComparison(
779 const VideoFrame& video_frame) {
780 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100781 if (captured_frames_ < frames_to_process_) {
782 ++captured_frames_;
783 frames_.push_back(video_frame);
784 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200785}
786
787void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
788 const VideoFrame& render,
789 bool dropped,
790 int64_t render_time_ms) {
791 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
792 int64_t send_time_ms = send_times_[reference_timestamp];
793 send_times_.erase(reference_timestamp);
794 int64_t recv_time_ms = recv_times_[reference_timestamp];
795 recv_times_.erase(reference_timestamp);
796
797 // TODO(ivica): Make this work for > 2 streams.
798 auto it = encoded_frame_sizes_.find(reference_timestamp);
799 if (it == encoded_frame_sizes_.end())
800 it = encoded_frame_sizes_.find(reference_timestamp - 1);
801 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
802 if (it != encoded_frame_sizes_.end())
803 encoded_frame_sizes_.erase(it);
804
805 rtc::CritScope crit(&comparison_lock_);
806 if (comparisons_.size() < kMaxComparisons) {
807 comparisons_.push_back(FrameComparison(
808 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
809 recv_time_ms, render_time_ms, encoded_size));
810 } else {
811 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
812 send_time_ms, recv_time_ms,
813 render_time_ms, encoded_size));
814 }
815 comparison_available_event_.Set();
816}
817
818VideoAnalyzer::FrameComparison::FrameComparison()
819 : dropped(false),
820 input_time_ms(0),
821 send_time_ms(0),
822 recv_time_ms(0),
823 render_time_ms(0),
824 encoded_frame_size(0) {}
825
826VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
827 const VideoFrame& render,
828 bool 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 : reference(reference),
835 render(render),
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
843VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
844 int64_t input_time_ms,
845 int64_t send_time_ms,
846 int64_t recv_time_ms,
847 int64_t render_time_ms,
848 size_t encoded_frame_size)
849 : dropped(dropped),
850 input_time_ms(input_time_ms),
851 send_time_ms(send_time_ms),
852 recv_time_ms(recv_time_ms),
853 render_time_ms(render_time_ms),
854 encoded_frame_size(encoded_frame_size) {}
855
856VideoAnalyzer::Sample::Sample(int dropped,
857 int64_t input_time_ms,
858 int64_t send_time_ms,
859 int64_t recv_time_ms,
860 int64_t render_time_ms,
861 size_t encoded_frame_size,
862 double psnr,
863 double ssim)
864 : dropped(dropped),
865 input_time_ms(input_time_ms),
866 send_time_ms(send_time_ms),
867 recv_time_ms(recv_time_ms),
868 render_time_ms(render_time_ms),
869 encoded_frame_size(encoded_frame_size),
870 psnr(psnr),
871 ssim(ssim) {}
872
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200873VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
874 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100875 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100876 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200877 : analyzer_(analyzer),
878 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100879 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100880 clock_(clock),
881 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100882 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200883
884void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100885 VideoSourceInterface<VideoFrame>* video_source) {
886 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200887}
888
889void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
890 const VideoFrame& video_frame) {
891 VideoFrame copy = video_frame;
892 // Frames from the capturer does not have a rtp timestamp.
893 // Create one so it can be used for comparison.
894 RTC_DCHECK_EQ(0, video_frame.timestamp());
895 if (video_frame.ntp_time_ms() == 0)
896 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
897 copy.set_timestamp(copy.ntp_time_ms() * 90);
898 analyzer_->AddCapturedFrameForComparison(copy);
899 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100900 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100901 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200902 send_stream_input_->OnFrame(copy);
903}
904
905void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
906 rtc::VideoSinkInterface<VideoFrame>* sink,
907 const rtc::VideoSinkWants& wants) {
908 {
909 rtc::CritScope lock(&crit_);
910 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
911 send_stream_input_ = sink;
912 }
Niels Möller1c931c42018-12-18 16:08:11 +0100913 if (video_source_) {
914 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200915 }
916}
917
918void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
919 rtc::VideoSinkInterface<VideoFrame>* sink) {
920 rtc::CritScope lock(&crit_);
921 RTC_DCHECK(sink == send_stream_input_);
922 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200923}
924
925} // namespace webrtc