blob: 62ee7b4352996d70c79367a0836776b5c6c33c38 [file] [log] [blame]
Sebastian Janssond4c5d632018-07-10 10:57:371/*
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 17:51:2715#include "absl/algorithm/container.h"
Mirko Bonadei2ab97f62019-07-18 11:44:1216#include "absl/flags/flag.h"
17#include "absl/flags/parse.h"
Niels Möller1c931c42018-12-18 15:08:1118#include "common_video/libyuv/include/webrtc_libyuv.h"
Danil Chapovalovb57fe172019-12-11 08:38:4419#include "modules/rtp_rtcp/source/create_video_rtp_depacketizer.h"
20#include "modules/rtp_rtcp/source/rtp_packet.h"
Danil Chapovalov00ca0042021-07-05 17:06:1721#include "modules/rtp_rtcp/source/rtp_util.h"
Sebastian Janssond4c5d632018-07-10 10:57:3722#include "rtc_base/cpu_time.h"
Sebastian Janssond4c5d632018-07-10 10:57:3723#include "rtc_base/format_macros.h"
24#include "rtc_base/memory_usage.h"
Danil Chapovalov9cd53b42019-10-21 11:36:5925#include "rtc_base/task_queue_for_test.h"
26#include "rtc_base/task_utils/repeating_task.h"
Johannes Kronb73c9f02021-02-15 12:29:4527#include "rtc_base/time_utils.h"
Sebastian Janssond4c5d632018-07-10 10:57:3728#include "system_wrappers/include/cpu_info.h"
29#include "test/call_test.h"
Steve Anton10542f22019-01-11 17:11:0030#include "test/testsupport/file_utils.h"
Sebastian Janssond4c5d632018-07-10 10:57:3731#include "test/testsupport/frame_writer.h"
32#include "test/testsupport/perf_test.h"
33#include "test/testsupport/test_artifacts.h"
34
Mirko Bonadei2ab97f62019-07-18 11:44:1235ABSL_FLAG(bool,
36 save_worst_frame,
37 false,
38 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
39 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 10:57:3740
41namespace webrtc {
42namespace {
Danil Chapovalov0c626af2020-02-10 10:16:0043constexpr TimeDelta kSendStatsPollingInterval = TimeDelta::Seconds(1);
Sebastian Janssond4c5d632018-07-10 10:57:3744constexpr size_t kMaxComparisons = 10;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:0445// How often is keep alive message printed.
46constexpr int kKeepAliveIntervalSeconds = 30;
47// Interval between checking that the test is over.
48constexpr int kProbingIntervalMs = 500;
49constexpr int kKeepAliveIntervalIterations =
50 kKeepAliveIntervalSeconds * 1000 / kProbingIntervalMs;
Sebastian Janssond4c5d632018-07-10 10:57:3751
52bool IsFlexfec(int payload_type) {
53 return payload_type == test::CallTest::kFlexfecPayloadType;
54}
55} // namespace
56
Danil Chapovalov9cd53b42019-10-21 11:36:5957VideoAnalyzer::VideoAnalyzer(test::LayerFilteringTransport* transport,
58 const std::string& test_label,
59 double avg_psnr_threshold,
60 double avg_ssim_threshold,
61 int duration_frames,
Ilya Nikolaevskiy06c70952020-03-16 12:01:2562 TimeDelta test_duration,
Danil Chapovalov9cd53b42019-10-21 11:36:5963 FILE* graph_data_output_file,
64 const std::string& graph_title,
65 uint32_t ssrc_to_analyze,
66 uint32_t rtx_ssrc_to_analyze,
67 size_t selected_stream,
68 int selected_sl,
69 int selected_tl,
70 bool is_quick_test_enabled,
71 Clock* clock,
72 std::string rtp_dump_name,
73 TaskQueueBase* task_queue)
Sebastian Janssond4c5d632018-07-10 10:57:3774 : transport_(transport),
75 receiver_(nullptr),
76 call_(nullptr),
77 send_stream_(nullptr),
78 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 12:10:5679 audio_receive_stream_(nullptr),
Ilya Nikolaevskiy06c70952020-03-16 12:01:2580 captured_frame_forwarder_(this, clock, duration_frames, test_duration),
Sebastian Janssond4c5d632018-07-10 10:57:3781 test_label_(test_label),
82 graph_data_output_file_(graph_data_output_file),
83 graph_title_(graph_title),
84 ssrc_to_analyze_(ssrc_to_analyze),
85 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
86 selected_stream_(selected_stream),
87 selected_sl_(selected_sl),
88 selected_tl_(selected_tl),
Johannes Krona1b99b32019-07-30 13:08:1689 mean_decode_time_ms_(0.0),
Elad Alon8c513c72019-05-07 19:22:2490 freeze_count_(0),
91 total_freezes_duration_ms_(0),
92 total_frames_duration_ms_(0),
93 sum_squared_frame_durations_(0),
Elad Alon58e06572019-05-08 13:34:2494 decode_frame_rate_(0),
95 render_frame_rate_(0),
Sebastian Janssond4c5d632018-07-10 10:57:3796 last_fec_bytes_(0),
97 frames_to_process_(duration_frames),
Ilya Nikolaevskiy06c70952020-03-16 12:01:2598 test_end_(clock->CurrentTime() + test_duration),
Sebastian Janssond4c5d632018-07-10 10:57:3799 frames_recorded_(0),
100 frames_processed_(0),
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04101 captured_frames_(0),
Yves Gerey0c67c802019-08-01 15:45:54102 dropped_frames_(0),
Sebastian Janssond4c5d632018-07-10 10:57:37103 dropped_frames_before_first_encode_(0),
104 dropped_frames_before_rendering_(0),
105 last_render_time_(0),
106 last_render_delta_ms_(0),
107 last_unfreeze_time_ms_(0),
108 rtp_timestamp_delta_(0),
Sebastian Janssond4c5d632018-07-10 10:57:37109 cpu_time_(0),
110 wallclock_time_(0),
111 avg_psnr_threshold_(avg_psnr_threshold),
112 avg_ssim_threshold_(avg_ssim_threshold),
113 is_quick_test_enabled_(is_quick_test_enabled),
Niels Möller4731f002019-05-03 07:34:24114 quit_(false),
Sebastian Janssond4c5d632018-07-10 10:57:37115 done_(true, false),
Danil Chapovalovb57fe172019-12-11 08:38:44116 vp8_depacketizer_(CreateVideoRtpDepacketizer(kVideoCodecVP8)),
117 vp9_depacketizer_(CreateVideoRtpDepacketizer(kVideoCodecVP9)),
Sebastian Janssond4c5d632018-07-10 10:57:37118 clock_(clock),
Artem Titovff7730d2019-04-02 11:46:53119 start_ms_(clock->TimeInMilliseconds()),
120 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 10:57:37121 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
122
123 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
124 // so that we don't accidentally starve "real" worker threads (codec etc).
125 // Also, don't allocate more than kMaxComparisonThreads, even if there are
126 // spare cores.
127
128 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
129 RTC_DCHECK_GE(num_cores, 1);
130 static const uint32_t kMinCoresLeft = 4;
131 static const uint32_t kMaxComparisonThreads = 8;
132
133 if (num_cores <= kMinCoresLeft) {
134 num_cores = 1;
135 } else {
136 num_cores -= kMinCoresLeft;
137 num_cores = std::min(num_cores, kMaxComparisonThreads);
138 }
139
140 for (uint32_t i = 0; i < num_cores; ++i) {
Markus Handellad5037b2021-05-07 13:02:36141 comparison_thread_pool_.push_back(rtc::PlatformThread::SpawnJoinable(
142 [this] {
143 while (CompareFrames()) {
144 }
145 },
146 "Analyzer"));
Sebastian Janssond4c5d632018-07-10 10:57:37147 }
148
149 if (!rtp_dump_name.empty()) {
150 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
151 rtp_file_writer_.reset(test::RtpFileWriter::Create(
152 test::RtpFileWriter::kRtpDump, rtp_dump_name));
153 }
154}
155
156VideoAnalyzer::~VideoAnalyzer() {
Niels Möller4731f002019-05-03 07:34:24157 {
Markus Handella3765182020-07-08 11:13:32158 MutexLock lock(&comparison_lock_);
Niels Möller4731f002019-05-03 07:34:24159 quit_ = true;
160 }
Markus Handellad5037b2021-05-07 13:02:36161 // Joins all threads.
162 comparison_thread_pool_.clear();
Sebastian Janssond4c5d632018-07-10 10:57:37163}
164
165void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
166 receiver_ = receiver;
167}
168
Niels Möller1c931c42018-12-18 15:08:11169void VideoAnalyzer::SetSource(
170 rtc::VideoSourceInterface<VideoFrame>* video_source,
171 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 10:57:37172 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 15:08:11173 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 10:57:37174 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 15:08:11175 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 10:57:37176}
177
178void VideoAnalyzer::SetCall(Call* call) {
Markus Handella3765182020-07-08 11:13:32179 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37180 RTC_DCHECK(!call_);
181 call_ = call;
182}
183
184void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
Markus Handella3765182020-07-08 11:13:32185 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37186 RTC_DCHECK(!send_stream_);
187 send_stream_ = stream;
188}
189
190void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
Markus Handella3765182020-07-08 11:13:32191 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37192 RTC_DCHECK(!receive_stream_);
193 receive_stream_ = stream;
194}
195
Christoffer Rodbroc2a02882018-08-07 12:10:56196void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
Markus Handella3765182020-07-08 11:13:32197 MutexLock lock(&lock_);
Christoffer Rodbroc2a02882018-08-07 12:10:56198 RTC_CHECK(!audio_receive_stream_);
199 audio_receive_stream_ = recv_stream;
200}
201
Sebastian Janssond4c5d632018-07-10 10:57:37202rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
203 return &captured_frame_forwarder_;
204}
205
206rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
207 return &captured_frame_forwarder_;
208}
209
210PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
211 MediaType media_type,
212 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 09:03:12213 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 10:57:37214 // Ignore timestamps of RTCP packets. They're not synchronized with
215 // RTP packet timestamps and so they would confuse wrap_handler_.
Danil Chapovalov00ca0042021-07-05 17:06:17216 if (IsRtcpPacket(packet)) {
Niels Möller70082872018-08-07 09:03:12217 return receiver_->DeliverPacket(media_type, std::move(packet),
218 packet_time_us);
Sebastian Janssond4c5d632018-07-10 10:57:37219 }
220
221 if (rtp_file_writer_) {
222 test::RtpPacket p;
223 memcpy(p.data, packet.cdata(), packet.size());
224 p.length = packet.size();
225 p.original_length = packet.size();
226 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
227 rtp_file_writer_->WritePacket(&p);
228 }
229
Danil Chapovalovb57fe172019-12-11 08:38:44230 RtpPacket rtp_packet;
231 rtp_packet.Parse(packet);
232 if (!IsFlexfec(rtp_packet.PayloadType()) &&
233 (rtp_packet.Ssrc() == ssrc_to_analyze_ ||
234 rtp_packet.Ssrc() == rtx_ssrc_to_analyze_)) {
Sebastian Janssond4c5d632018-07-10 10:57:37235 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
236 // (FlexFEC and media are sent on different SSRCs, which have different
237 // timestamps spaces.)
238 // Also ignore packets from wrong SSRC, but include retransmits.
Markus Handella3765182020-07-08 11:13:32239 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37240 int64_t timestamp =
Danil Chapovalovb57fe172019-12-11 08:38:44241 wrap_handler_.Unwrap(rtp_packet.Timestamp() - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 13:17:26242 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37243 }
244
Niels Möller70082872018-08-07 09:03:12245 return receiver_->DeliverPacket(media_type, std::move(packet),
246 packet_time_us);
Sebastian Janssond4c5d632018-07-10 10:57:37247}
248
249void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
Markus Handella3765182020-07-08 11:13:32250 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37251 if (!first_encoded_timestamp_) {
252 while (frames_.front().timestamp() != video_frame.timestamp()) {
253 ++dropped_frames_before_first_encode_;
254 frames_.pop_front();
255 RTC_CHECK(!frames_.empty());
256 }
257 first_encoded_timestamp_ = video_frame.timestamp();
258 }
259}
260
Niels Möller88be9722018-10-10 08:58:52261void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Markus Handella3765182020-07-08 11:13:32262 MutexLock lock(&lock_);
Niels Möller88be9722018-10-10 08:58:52263 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
264 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 10:57:37265 }
266}
267
268bool VideoAnalyzer::SendRtp(const uint8_t* packet,
269 size_t length,
270 const PacketOptions& options) {
Danil Chapovalovb57fe172019-12-11 08:38:44271 RtpPacket rtp_packet;
272 rtp_packet.Parse(packet, length);
Sebastian Janssond4c5d632018-07-10 10:57:37273
Sebastian Jansson11c012a2019-03-29 13:17:26274 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37275
276 bool result = transport_->SendRtp(packet, length, options);
277 {
Markus Handella3765182020-07-08 11:13:32278 MutexLock lock(&lock_);
Danil Chapovalovb57fe172019-12-11 08:38:44279 if (rtp_timestamp_delta_ == 0 && rtp_packet.Ssrc() == ssrc_to_analyze_) {
Sebastian Janssond4c5d632018-07-10 10:57:37280 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
Danil Chapovalovb57fe172019-12-11 08:38:44281 rtp_timestamp_delta_ = rtp_packet.Timestamp() - *first_sent_timestamp_;
Sebastian Janssond4c5d632018-07-10 10:57:37282 }
283
Danil Chapovalovb57fe172019-12-11 08:38:44284 if (!IsFlexfec(rtp_packet.PayloadType()) &&
285 rtp_packet.Ssrc() == ssrc_to_analyze_) {
Sebastian Janssond4c5d632018-07-10 10:57:37286 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
287 // (FlexFEC and media are sent on different SSRCs, which have different
288 // timestamps spaces.)
289 // Also ignore packets from wrong SSRC and retransmits.
290 int64_t timestamp =
Danil Chapovalovb57fe172019-12-11 08:38:44291 wrap_handler_.Unwrap(rtp_packet.Timestamp() - rtp_timestamp_delta_);
Sebastian Janssond4c5d632018-07-10 10:57:37292 send_times_[timestamp] = current_time;
293
Danil Chapovalovb57fe172019-12-11 08:38:44294 if (IsInSelectedSpatialAndTemporalLayer(rtp_packet)) {
295 encoded_frame_sizes_[timestamp] += rtp_packet.payload_size();
Sebastian Janssond4c5d632018-07-10 10:57:37296 }
Sebastian Janssond4c5d632018-07-10 10:57:37297 }
298 }
299 return result;
300}
301
302bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
303 return transport_->SendRtcp(packet, length);
304}
305
306void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 13:17:26307 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37308
Markus Handella3765182020-07-08 11:13:32309 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37310
311 StartExcludingCpuThreadTime();
312
313 int64_t send_timestamp =
314 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
315
316 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
317 if (!last_rendered_frame_) {
318 // No previous frame rendered, this one was dropped after sending but
319 // before rendering.
320 ++dropped_frames_before_rendering_;
321 } else {
322 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
323 render_time_ms);
324 }
325 frames_.pop_front();
326 RTC_DCHECK(!frames_.empty());
327 }
328
329 VideoFrame reference_frame = frames_.front();
330 frames_.pop_front();
331 int64_t reference_timestamp =
332 wrap_handler_.Unwrap(reference_frame.timestamp());
333 if (send_timestamp == reference_timestamp - 1) {
334 // TODO(ivica): Make this work for > 2 streams.
335 // Look at RTPSender::BuildRTPHeader.
336 ++send_timestamp;
337 }
338 ASSERT_EQ(reference_timestamp, send_timestamp);
339
340 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
341
342 last_rendered_frame_ = video_frame;
343
344 StopExcludingCpuThreadTime();
345}
346
347void VideoAnalyzer::Wait() {
348 // Frame comparisons can be very expensive. Wait for test to be done, but
349 // at time-out check if frames_processed is going up. If so, give it more
350 // time, otherwise fail. Hopefully this will reduce test flakiness.
351
Danil Chapovalov9cd53b42019-10-21 11:36:59352 RepeatingTaskHandle stats_polling_task = RepeatingTaskHandle::DelayedStart(
353 task_queue_, kSendStatsPollingInterval, [this] {
354 PollStats();
355 return kSendStatsPollingInterval;
356 });
Sebastian Janssond4c5d632018-07-10 10:57:37357
358 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04359 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 10:57:37360 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04361
362 while (!done_.Wait(kProbingIntervalMs)) {
Sebastian Janssond4c5d632018-07-10 10:57:37363 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04364 int frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37365 {
Markus Handella3765182020-07-08 11:13:32366 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37367 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04368 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 10:57:37369 }
370
371 // Print some output so test infrastructure won't think we've crashed.
372 const char* kKeepAliveMessages[3] = {
373 "Uh, I'm-I'm not quite dead, sir.",
374 "Uh, I-I think uh, I could pull through, sir.",
375 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04376 if (++iteration % kKeepAliveIntervalIterations == 0) {
377 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
378 }
Sebastian Janssond4c5d632018-07-10 10:57:37379
380 if (last_frames_processed == -1) {
381 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04382 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37383 continue;
384 }
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04385 if (frames_processed == last_frames_processed &&
Ilya Nikolaevskiy06c70952020-03-16 12:01:25386 last_frames_captured == frames_captured &&
387 clock_->CurrentTime() > test_end_) {
Sebastian Janssond4c5d632018-07-10 10:57:37388 done_.Set();
389 break;
390 }
391 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04392 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37393 }
394
395 if (iteration > 0)
396 printf("- Farewell, sweet Concorde!\n");
397
Danil Chapovalov9cd53b42019-10-21 11:36:59398 SendTask(RTC_FROM_HERE, task_queue_, [&] { stats_polling_task.Stop(); });
Artem Titovff7730d2019-04-02 11:46:53399
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04400 PrintResults();
401 if (graph_data_output_file_)
402 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 10:57:37403}
404
Sebastian Janssond4c5d632018-07-10 10:57:37405void VideoAnalyzer::StartMeasuringCpuProcessTime() {
Markus Handella3765182020-07-08 11:13:32406 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37407 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
408 wallclock_time_ -= rtc::SystemTimeNanos();
409}
410
411void VideoAnalyzer::StopMeasuringCpuProcessTime() {
Markus Handella3765182020-07-08 11:13:32412 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37413 cpu_time_ += rtc::GetProcessCpuTimeNanos();
414 wallclock_time_ += rtc::SystemTimeNanos();
415}
416
417void VideoAnalyzer::StartExcludingCpuThreadTime() {
Markus Handella3765182020-07-08 11:13:32418 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37419 cpu_time_ += rtc::GetThreadCpuTimeNanos();
420}
421
422void VideoAnalyzer::StopExcludingCpuThreadTime() {
Markus Handella3765182020-07-08 11:13:32423 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37424 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
425}
426
427double VideoAnalyzer::GetCpuUsagePercent() {
Markus Handella3765182020-07-08 11:13:32428 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37429 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
430}
431
432bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
Danil Chapovalovb57fe172019-12-11 08:38:44433 const RtpPacket& rtp_packet) {
434 if (rtp_packet.PayloadType() == test::CallTest::kPayloadTypeVP8) {
435 auto parsed_payload = vp8_depacketizer_->Parse(rtp_packet.PayloadBuffer());
436 RTC_DCHECK(parsed_payload);
437 const auto& vp8_header = absl::get<RTPVideoHeaderVP8>(
438 parsed_payload->video_header.video_type_header);
439 int temporal_idx = vp8_header.temporalIdx;
440 return selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
441 temporal_idx <= selected_tl_;
442 }
philipel29d88462018-08-08 12:26:00443
Danil Chapovalovb57fe172019-12-11 08:38:44444 if (rtp_packet.PayloadType() == test::CallTest::kPayloadTypeVP9) {
445 auto parsed_payload = vp9_depacketizer_->Parse(rtp_packet.PayloadBuffer());
446 RTC_DCHECK(parsed_payload);
447 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
448 parsed_payload->video_header.video_type_header);
449 int temporal_idx = vp9_header.temporal_idx;
450 int spatial_idx = vp9_header.spatial_idx;
Sebastian Janssond4c5d632018-07-10 10:57:37451 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
452 temporal_idx <= selected_tl_) &&
453 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
454 spatial_idx <= selected_sl_);
455 }
Danil Chapovalovb57fe172019-12-11 08:38:44456
457 return true;
Sebastian Janssond4c5d632018-07-10 10:57:37458}
459
Sebastian Janssond4c5d632018-07-10 10:57:37460void VideoAnalyzer::PollStats() {
Artem Titovab30d722021-07-27 14:22:11461 // Do not grab `comparison_lock_`, before `GetStats()` completes.
Ilya Nikolaevskiy3ea3e0c2020-07-29 16:20:13462 // Otherwise a deadlock may occur:
Artem Titovab30d722021-07-27 14:22:11463 // 1) `comparison_lock_` is acquired after `lock_`
464 // 2) `lock_` is acquired after internal pacer lock in SendRtp()
Ilya Nikolaevskiy3ea3e0c2020-07-29 16:20:13465 // 3) internal pacer lock is acquired by GetStats().
466 Call::Stats call_stats = call_->GetStats();
467
Markus Handella3765182020-07-08 11:13:32468 MutexLock lock(&comparison_lock_);
Artem Titovff7730d2019-04-02 11:46:53469
Artem Titovff7730d2019-04-02 11:46:53470 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;
484 for (const auto& kv : send_stats.substreams) {
485 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();
Artem Titovab30d722021-07-27 14:22:11493 // `total_decode_time_ms` gives a good estimate of the mean decode time,
494 // `decode_ms` is used to keep track of the standard deviation.
Johannes Krona1b99b32019-07-30 13:08:16495 if (receive_stats.frames_decoded > 0)
496 mean_decode_time_ms_ =
497 static_cast<double>(receive_stats.total_decode_time_ms) /
498 receive_stats.frames_decoded;
Artem Titovff7730d2019-04-02 11:46:53499 if (receive_stats.decode_ms > 0)
500 decode_time_ms_.AddSample(receive_stats.decode_ms);
501 if (receive_stats.max_decode_ms > 0)
502 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
503 if (receive_stats.width > 0 && receive_stats.height > 0) {
504 pixels_.AddSample(receive_stats.width * receive_stats.height);
505 }
Elad Alon58e06572019-05-08 13:34:24506
Artem Titovab30d722021-07-27 14:22:11507 // `frames_decoded` and `frames_rendered` are used because they are more
508 // accurate than `decode_frame_rate` and `render_frame_rate`.
Elad Alon58e06572019-05-08 13:34:24509 // The latter two are calculated on a momentary basis.
510 const double total_frames_duration_sec_double =
511 static_cast<double>(receive_stats.total_frames_duration_ms) / 1000.0;
512 if (total_frames_duration_sec_double > 0) {
513 decode_frame_rate_ = static_cast<double>(receive_stats.frames_decoded) /
514 total_frames_duration_sec_double;
515 render_frame_rate_ = static_cast<double>(receive_stats.frames_rendered) /
516 total_frames_duration_sec_double;
517 }
518
519 // Freeze metrics.
Elad Alon8c513c72019-05-07 19:22:24520 freeze_count_ = receive_stats.freeze_count;
521 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
522 total_frames_duration_ms_ = receive_stats.total_frames_duration_ms;
523 sum_squared_frame_durations_ = receive_stats.sum_squared_frame_durations;
Artem Titovff7730d2019-04-02 11:46:53524 }
525
526 if (audio_receive_stream_ != nullptr) {
Niels Möller6b4d9622020-09-14 08:47:50527 AudioReceiveStream::Stats receive_stats =
528 audio_receive_stream_->GetStats(/*get_and_clear_legacy_stats=*/true);
Artem Titovff7730d2019-04-02 11:46:53529 audio_expand_rate_.AddSample(receive_stats.expand_rate);
530 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
531 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
532 }
533
534 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
Sebastian Janssond4c5d632018-07-10 10:57:37535}
536
Sebastian Janssond4c5d632018-07-10 10:57:37537bool VideoAnalyzer::CompareFrames() {
538 if (AllFramesRecorded())
539 return false;
540
541 FrameComparison comparison;
542
543 if (!PopComparison(&comparison)) {
544 // Wait until new comparison task is available, or test is done.
545 // If done, wake up remaining threads waiting.
546 comparison_available_event_.Wait(1000);
547 if (AllFramesRecorded()) {
548 comparison_available_event_.Set();
549 return false;
550 }
551 return true; // Try again.
552 }
553
554 StartExcludingCpuThreadTime();
555
556 PerformFrameComparison(comparison);
557
558 StopExcludingCpuThreadTime();
559
560 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 10:57:37561 done_.Set();
562 comparison_available_event_.Set();
563 return false;
564 }
565
566 return true;
567}
568
569bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
Markus Handella3765182020-07-08 11:13:32570 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37571 // If AllFramesRecorded() is true, it means we have already popped
572 // frames_to_process_ frames from comparisons_, so there is no more work
573 // for this thread to be done. frames_processed_ might still be lower if
574 // all comparisons are not done, but those frames are currently being
575 // worked on by other threads.
Markus Handelladbfd1d2020-07-08 07:32:42576 if (comparisons_.empty() || AllFramesRecordedLocked())
Sebastian Janssond4c5d632018-07-10 10:57:37577 return false;
578
579 *comparison = comparisons_.front();
580 comparisons_.pop_front();
581
582 FrameRecorded();
583 return true;
584}
585
586void VideoAnalyzer::FrameRecorded() {
Sebastian Janssond4c5d632018-07-10 10:57:37587 ++frames_recorded_;
588}
589
590bool VideoAnalyzer::AllFramesRecorded() {
Markus Handella3765182020-07-08 11:13:32591 MutexLock lock(&comparison_lock_);
Markus Handelladbfd1d2020-07-08 07:32:42592 return AllFramesRecordedLocked();
593}
594
595bool VideoAnalyzer::AllFramesRecordedLocked() {
Niels Möller4731f002019-05-03 07:34:24596 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
Ilya Nikolaevskiy06c70952020-03-16 12:01:25597 return frames_recorded_ == frames_to_process_ ||
598 (clock_->CurrentTime() > test_end_ && comparisons_.empty()) || quit_;
Sebastian Janssond4c5d632018-07-10 10:57:37599}
600
601bool VideoAnalyzer::FrameProcessed() {
Markus Handella3765182020-07-08 11:13:32602 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37603 ++frames_processed_;
Mirko Bonadei25ab3222021-07-08 18:08:20604 RTC_DCHECK_LE(frames_processed_, frames_to_process_);
Ilya Nikolaevskiy06c70952020-03-16 12:01:25605 return frames_processed_ == frames_to_process_ ||
606 (clock_->CurrentTime() > test_end_ && comparisons_.empty());
Sebastian Janssond4c5d632018-07-10 10:57:37607}
608
609void VideoAnalyzer::PrintResults() {
Artem Titov82ce3842019-09-23 15:55:52610 using ::webrtc::test::ImproveDirection;
611
Sebastian Janssond4c5d632018-07-10 10:57:37612 StopMeasuringCpuProcessTime();
Yves Gerey0c67c802019-08-01 15:45:54613 int dropped_frames_diff;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04614 {
Markus Handella3765182020-07-08 11:13:32615 MutexLock lock(&lock_);
Yves Gerey0c67c802019-08-01 15:45:54616 dropped_frames_diff = dropped_frames_before_first_encode_ +
617 dropped_frames_before_rendering_ + frames_.size();
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04618 }
Markus Handella3765182020-07-08 11:13:32619 MutexLock lock(&comparison_lock_);
Artem Titov82ce3842019-09-23 15:55:52620 PrintResult("psnr", psnr_, "dB", ImproveDirection::kBiggerIsBetter);
621 PrintResult("ssim", ssim_, "unitless", ImproveDirection::kBiggerIsBetter);
622 PrintResult("sender_time", sender_time_, "ms",
623 ImproveDirection::kSmallerIsBetter);
624 PrintResult("receiver_time", receiver_time_, "ms",
625 ImproveDirection::kSmallerIsBetter);
626 PrintResult("network_time", network_time_, "ms",
627 ImproveDirection::kSmallerIsBetter);
628 PrintResult("total_delay_incl_network", end_to_end_, "ms",
629 ImproveDirection::kSmallerIsBetter);
630 PrintResult("time_between_rendered_frames", rendered_delta_, "ms",
631 ImproveDirection::kSmallerIsBetter);
632 PrintResult("encode_frame_rate", encode_frame_rate_, "fps",
633 ImproveDirection::kBiggerIsBetter);
634 PrintResult("encode_time", encode_time_ms_, "ms",
635 ImproveDirection::kSmallerIsBetter);
636 PrintResult("media_bitrate", media_bitrate_bps_, "bps",
637 ImproveDirection::kNone);
638 PrintResult("fec_bitrate", fec_bitrate_bps_, "bps", ImproveDirection::kNone);
639 PrintResult("send_bandwidth", send_bandwidth_bps_, "bps",
640 ImproveDirection::kNone);
641 PrintResult("pixels_per_frame", pixels_, "count",
642 ImproveDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37643
Elad Alon58e06572019-05-08 13:34:24644 test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
Artem Titov82ce3842019-09-23 15:55:52645 decode_frame_rate_, "fps", false,
646 ImproveDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 13:34:24647 test::PrintResult("render_frame_rate", "", test_label_.c_str(),
Artem Titov82ce3842019-09-23 15:55:52648 render_frame_rate_, "fps", false,
649 ImproveDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 13:34:24650
Elad Alon8c513c72019-05-07 19:22:24651 // Record the time from the last freeze until the last rendered frame to
652 // ensure we cover the full timespan of the session. Otherwise the metric
653 // would penalize an early freeze followed by no freezes until the end.
654 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
655
656 // Freeze metrics.
Artem Titov82ce3842019-09-23 15:55:52657 PrintResult("time_between_freezes", time_between_freezes_, "ms",
658 ImproveDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24659
660 const double freeze_count_double = static_cast<double>(freeze_count_);
661 const double total_freezes_duration_ms_double =
662 static_cast<double>(total_freezes_duration_ms_);
663 const double total_frames_duration_ms_double =
664 static_cast<double>(total_frames_duration_ms_);
665
666 if (total_frames_duration_ms_double > 0) {
667 test::PrintResult(
668 "freeze_duration_ratio", "", test_label_.c_str(),
Artem Titovea9798c2019-07-31 12:27:42669 total_freezes_duration_ms_double / total_frames_duration_ms_double,
Artem Titov82ce3842019-09-23 15:55:52670 "unitless", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24671 RTC_DCHECK_LE(total_freezes_duration_ms_double,
672 total_frames_duration_ms_double);
673
674 constexpr double ms_per_minute = 60 * 1000;
675 const double total_frames_duration_min =
676 total_frames_duration_ms_double / ms_per_minute;
677 if (total_frames_duration_min > 0) {
678 test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
679 freeze_count_double / total_frames_duration_min,
Artem Titov82ce3842019-09-23 15:55:52680 "unitless", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24681 }
682 }
683
Elad Alon133f7e72019-05-08 07:51:56684 test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
Elad Alon8c513c72019-05-07 19:22:24685 freeze_count_double > 0
686 ? total_freezes_duration_ms_double / freeze_count_double
687 : 0,
Artem Titov82ce3842019-09-23 15:55:52688 "ms", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24689
690 if (1000 * sum_squared_frame_durations_ > 0) {
691 test::PrintResult(
692 "harmonic_frame_rate", "", test_label_.c_str(),
693 total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
Artem Titov82ce3842019-09-23 15:55:52694 "fps", false, ImproveDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24695 }
696
Sebastian Janssond4c5d632018-07-10 10:57:37697 if (worst_frame_) {
698 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
Artem Titov82ce3842019-09-23 15:55:52699 "dB", false, ImproveDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37700 }
701
702 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 13:08:16703 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titov82ce3842019-09-23 15:55:52704 decode_time_ms_, "ms",
705 ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37706 }
Yves Gerey0c67c802019-08-01 15:45:54707 dropped_frames_ += dropped_frames_diff;
Sebastian Janssond4c5d632018-07-10 10:57:37708 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
Artem Titov82ce3842019-09-23 15:55:52709 "count", false, ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37710 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
Artem Titov82ce3842019-09-23 15:55:52711 "%", false, ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37712
713#if defined(WEBRTC_WIN)
714 // On Linux and Mac in Resident Set some unused pages may be counted.
715 // Therefore this metric will depend on order in which tests are run and
716 // will be flaky.
Artem Titov82ce3842019-09-23 15:55:52717 PrintResult("memory_usage", memory_usage_, "sizeInBytes",
718 ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37719#endif
720
721 // Saving only the worst frame for manual analysis. Intention here is to
722 // only detect video corruptions and not to track picture quality. Thus,
723 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 11:44:12724 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 10:57:37725 std::string output_dir;
726 test::GetTestArtifactsDir(&output_dir);
727 std::string output_path =
Niels Möller7b3c76b2018-11-07 08:54:28728 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 10:57:37729 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
730 test::JpegFrameWriter frame_writer(output_path);
731 RTC_CHECK(
732 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
733 }
734
Christoffer Rodbroc2a02882018-08-07 12:10:56735 if (audio_receive_stream_ != nullptr) {
Artem Titov82ce3842019-09-23 15:55:52736 PrintResult("audio_expand_rate", audio_expand_rate_, "unitless",
737 ImproveDirection::kSmallerIsBetter);
738 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "unitless",
739 ImproveDirection::kSmallerIsBetter);
740 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, "ms",
741 ImproveDirection::kNone);
Christoffer Rodbroc2a02882018-08-07 12:10:56742 }
743
Sebastian Janssond4c5d632018-07-10 10:57:37744 // Disable quality check for quick test, as quality checks may fail
745 // because too few samples were collected.
746 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 16:59:53747 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
748 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 10:57:37749 }
750}
751
752void VideoAnalyzer::PerformFrameComparison(
753 const VideoAnalyzer::FrameComparison& comparison) {
754 // Perform expensive psnr and ssim calculations while not holding lock.
755 double psnr = -1.0;
756 double ssim = -1.0;
757 if (comparison.reference && !comparison.dropped) {
758 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
759 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
760 }
761
Markus Handella3765182020-07-08 11:13:32762 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37763
764 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
765 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
766 }
767
768 if (graph_data_output_file_) {
769 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
770 comparison.send_time_ms, comparison.recv_time_ms,
771 comparison.render_time_ms,
772 comparison.encoded_frame_size, psnr, ssim));
773 }
774 if (psnr >= 0.0)
775 psnr_.AddSample(psnr);
776 if (ssim >= 0.0)
777 ssim_.AddSample(ssim);
778
779 if (comparison.dropped) {
780 ++dropped_frames_;
781 return;
782 }
783 if (last_unfreeze_time_ms_ == 0)
784 last_unfreeze_time_ms_ = comparison.render_time_ms;
785 if (last_render_time_ != 0) {
786 const int64_t render_delta_ms =
787 comparison.render_time_ms - last_render_time_;
788 rendered_delta_.AddSample(render_delta_ms);
789 if (last_render_delta_ms_ != 0 &&
790 render_delta_ms - last_render_delta_ms_ > 150) {
791 time_between_freezes_.AddSample(last_render_time_ -
792 last_unfreeze_time_ms_);
793 last_unfreeze_time_ms_ = comparison.render_time_ms;
794 }
795 last_render_delta_ms_ = render_delta_ms;
796 }
797 last_render_time_ = comparison.render_time_ms;
798
799 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
800 if (comparison.recv_time_ms > 0) {
801 // If recv_time_ms == 0, this frame consisted of a packets which were all
802 // lost in the transport. Since we were able to render the frame, however,
803 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
804 // happens internally in Call, and we can therefore here not know which
805 // FEC packets that protected the lost media packets. Consequently, we
806 // were not able to record a meaningful recv_time_ms. We therefore skip
807 // this sample.
808 //
809 // The reasoning above does not hold for ULPFEC and RTX, as for those
810 // strategies the timestamp of the received packets is set to the
811 // timestamp of the protected/retransmitted media packet. I.e., then
812 // recv_time_ms != 0, even though the media packets were lost.
813 receiver_time_.AddSample(comparison.render_time_ms -
814 comparison.recv_time_ms);
815 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
816 }
817 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
818 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
819}
820
Artem Titov82ce3842019-09-23 15:55:52821void VideoAnalyzer::PrintResult(
822 const char* result_type,
823 Statistics stats,
824 const char* unit,
825 webrtc::test::ImproveDirection improve_direction) {
Yves Gerey79e9f4b2019-04-13 16:59:53826 test::PrintResultMeanAndError(
827 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
Artem Titov82ce3842019-09-23 15:55:52828 stats.GetStandardDeviation().value_or(0), unit, false, improve_direction);
Sebastian Janssond4c5d632018-07-10 10:57:37829}
830
Artem Titov82ce3842019-09-23 15:55:52831void VideoAnalyzer::PrintResultWithExternalMean(
832 const char* result_type,
833 double mean,
834 Statistics stats,
835 const char* unit,
836 webrtc::test::ImproveDirection improve_direction) {
Johannes Krona1b99b32019-07-30 13:08:16837 // If the true mean is different than the sample mean, the sample variance is
838 // too low. The sample variance given a known mean is obtained by adding the
839 // squared error between the true mean and the sample mean.
840 double compensated_variance =
841 stats.Size() > 0
842 ? *stats.GetVariance() + pow(mean - *stats.GetMean(), 2.0)
843 : 0.0;
844 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(), mean,
Artem Titov82ce3842019-09-23 15:55:52845 std::sqrt(compensated_variance), unit, false,
846 improve_direction);
Johannes Krona1b99b32019-07-30 13:08:16847}
848
Sebastian Janssond4c5d632018-07-10 10:57:37849void VideoAnalyzer::PrintSamplesToFile() {
850 FILE* out = graph_data_output_file_;
Markus Handella3765182020-07-08 11:13:32851 MutexLock lock(&comparison_lock_);
Steve Antonbd631a02019-03-28 17:51:27852 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
853 return A.input_time_ms < B.input_time_ms;
854 });
Sebastian Janssond4c5d632018-07-10 10:57:37855
856 fprintf(out, "%s\n", graph_title_.c_str());
Oleh Prypinb1686782019-08-02 07:36:47857 fprintf(out, "%" RTC_PRIuS "\n", samples_.size());
Sebastian Janssond4c5d632018-07-10 10:57:37858 fprintf(out,
859 "dropped "
860 "input_time_ms "
861 "send_time_ms "
862 "recv_time_ms "
863 "render_time_ms "
864 "encoded_frame_size "
865 "psnr "
866 "ssim "
867 "encode_time_ms\n");
868 for (const Sample& sample : samples_) {
869 fprintf(out,
Oleh Prypinb1686782019-08-02 07:36:47870 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" RTC_PRIuS
Sebastian Janssond4c5d632018-07-10 10:57:37871 " %lf %lf\n",
872 sample.dropped, sample.input_time_ms, sample.send_time_ms,
873 sample.recv_time_ms, sample.render_time_ms,
874 sample.encoded_frame_size, sample.psnr, sample.ssim);
875 }
876}
877
Sebastian Janssond4c5d632018-07-10 10:57:37878void VideoAnalyzer::AddCapturedFrameForComparison(
879 const VideoFrame& video_frame) {
Yves Gerey0c67c802019-08-01 15:45:54880 bool must_capture = false;
881 {
Markus Handella3765182020-07-08 11:13:32882 MutexLock lock(&comparison_lock_);
Yves Gerey0c67c802019-08-01 15:45:54883 must_capture = captured_frames_ < frames_to_process_;
884 if (must_capture) {
885 ++captured_frames_;
886 }
887 }
888 if (must_capture) {
Markus Handella3765182020-07-08 11:13:32889 MutexLock lock(&lock_);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04890 frames_.push_back(video_frame);
891 }
Sebastian Janssond4c5d632018-07-10 10:57:37892}
893
894void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
895 const VideoFrame& render,
896 bool dropped,
897 int64_t render_time_ms) {
898 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
899 int64_t send_time_ms = send_times_[reference_timestamp];
900 send_times_.erase(reference_timestamp);
901 int64_t recv_time_ms = recv_times_[reference_timestamp];
902 recv_times_.erase(reference_timestamp);
903
904 // TODO(ivica): Make this work for > 2 streams.
905 auto it = encoded_frame_sizes_.find(reference_timestamp);
906 if (it == encoded_frame_sizes_.end())
907 it = encoded_frame_sizes_.find(reference_timestamp - 1);
908 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
909 if (it != encoded_frame_sizes_.end())
910 encoded_frame_sizes_.erase(it);
911
Markus Handella3765182020-07-08 11:13:32912 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37913 if (comparisons_.size() < kMaxComparisons) {
914 comparisons_.push_back(FrameComparison(
915 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
916 recv_time_ms, render_time_ms, encoded_size));
917 } else {
918 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
919 send_time_ms, recv_time_ms,
920 render_time_ms, encoded_size));
921 }
922 comparison_available_event_.Set();
923}
924
925VideoAnalyzer::FrameComparison::FrameComparison()
926 : dropped(false),
927 input_time_ms(0),
928 send_time_ms(0),
929 recv_time_ms(0),
930 render_time_ms(0),
931 encoded_frame_size(0) {}
932
933VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
934 const VideoFrame& render,
935 bool dropped,
936 int64_t input_time_ms,
937 int64_t send_time_ms,
938 int64_t recv_time_ms,
939 int64_t render_time_ms,
940 size_t encoded_frame_size)
941 : reference(reference),
942 render(render),
943 dropped(dropped),
944 input_time_ms(input_time_ms),
945 send_time_ms(send_time_ms),
946 recv_time_ms(recv_time_ms),
947 render_time_ms(render_time_ms),
948 encoded_frame_size(encoded_frame_size) {}
949
950VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
951 int64_t input_time_ms,
952 int64_t send_time_ms,
953 int64_t recv_time_ms,
954 int64_t render_time_ms,
955 size_t encoded_frame_size)
956 : dropped(dropped),
957 input_time_ms(input_time_ms),
958 send_time_ms(send_time_ms),
959 recv_time_ms(recv_time_ms),
960 render_time_ms(render_time_ms),
961 encoded_frame_size(encoded_frame_size) {}
962
963VideoAnalyzer::Sample::Sample(int dropped,
964 int64_t input_time_ms,
965 int64_t send_time_ms,
966 int64_t recv_time_ms,
967 int64_t render_time_ms,
968 size_t encoded_frame_size,
969 double psnr,
970 double ssim)
971 : dropped(dropped),
972 input_time_ms(input_time_ms),
973 send_time_ms(send_time_ms),
974 recv_time_ms(recv_time_ms),
975 render_time_ms(render_time_ms),
976 encoded_frame_size(encoded_frame_size),
977 psnr(psnr),
978 ssim(ssim) {}
979
Sebastian Janssond4c5d632018-07-10 10:57:37980VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
981 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04982 Clock* clock,
Ilya Nikolaevskiy06c70952020-03-16 12:01:25983 int frames_to_capture,
984 TimeDelta test_duration)
Sebastian Janssond4c5d632018-07-10 10:57:37985 : analyzer_(analyzer),
986 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 15:08:11987 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04988 clock_(clock),
989 captured_frames_(0),
Ilya Nikolaevskiy06c70952020-03-16 12:01:25990 frames_to_capture_(frames_to_capture),
991 test_end_(clock->CurrentTime() + test_duration) {}
Sebastian Janssond4c5d632018-07-10 10:57:37992
993void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 15:08:11994 VideoSourceInterface<VideoFrame>* video_source) {
995 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 10:57:37996}
997
998void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
999 const VideoFrame& video_frame) {
1000 VideoFrame copy = video_frame;
1001 // Frames from the capturer does not have a rtp timestamp.
1002 // Create one so it can be used for comparison.
1003 RTC_DCHECK_EQ(0, video_frame.timestamp());
1004 if (video_frame.ntp_time_ms() == 0)
1005 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
1006 copy.set_timestamp(copy.ntp_time_ms() * 90);
1007 analyzer_->AddCapturedFrameForComparison(copy);
Markus Handella3765182020-07-08 11:13:321008 MutexLock lock(&lock_);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:041009 ++captured_frames_;
Ilya Nikolaevskiy06c70952020-03-16 12:01:251010 if (send_stream_input_ && clock_->CurrentTime() <= test_end_ &&
1011 captured_frames_ <= frames_to_capture_) {
Sebastian Janssond4c5d632018-07-10 10:57:371012 send_stream_input_->OnFrame(copy);
Ilya Nikolaevskiy06c70952020-03-16 12:01:251013 }
Sebastian Janssond4c5d632018-07-10 10:57:371014}
1015
1016void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1017 rtc::VideoSinkInterface<VideoFrame>* sink,
1018 const rtc::VideoSinkWants& wants) {
1019 {
Markus Handella3765182020-07-08 11:13:321020 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:371021 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1022 send_stream_input_ = sink;
1023 }
Niels Möller1c931c42018-12-18 15:08:111024 if (video_source_) {
1025 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 10:57:371026 }
1027}
1028
1029void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1030 rtc::VideoSinkInterface<VideoFrame>* sink) {
Markus Handella3765182020-07-08 11:13:321031 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:371032 RTC_DCHECK(sink == send_stream_input_);
1033 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 10:57:371034}
1035
1036} // namespace webrtc