blob: 9f17e3e0159d07efa377e54f8d76ffa3820a5ec6 [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
Niels Möllerea1e6f42022-05-09 07:21:1412#include <inttypes.h>
13
Sebastian Janssond4c5d632018-07-10 10:57:3714#include <algorithm>
15#include <utility>
16
Steve Antonbd631a02019-03-28 17:51:2717#include "absl/algorithm/container.h"
Mirko Bonadei2ab97f62019-07-18 11:44:1218#include "absl/flags/flag.h"
19#include "absl/flags/parse.h"
Artem Titov182044182022-09-24 23:47:0420#include "absl/strings/string_view.h"
21#include "api/test/metrics/global_metrics_logger_and_exporter.h"
22#include "api/test/metrics/metric.h"
Niels Möller1c931c42018-12-18 15:08:1123#include "common_video/libyuv/include/webrtc_libyuv.h"
Danil Chapovalovb57fe172019-12-11 08:38:4424#include "modules/rtp_rtcp/source/create_video_rtp_depacketizer.h"
25#include "modules/rtp_rtcp/source/rtp_packet.h"
Danil Chapovalov00ca0042021-07-05 17:06:1726#include "modules/rtp_rtcp/source/rtp_util.h"
Sebastian Janssond4c5d632018-07-10 10:57:3727#include "rtc_base/cpu_time.h"
Sebastian Janssond4c5d632018-07-10 10:57:3728#include "rtc_base/memory_usage.h"
Danil Chapovalov9cd53b42019-10-21 11:36:5929#include "rtc_base/task_queue_for_test.h"
30#include "rtc_base/task_utils/repeating_task.h"
Johannes Kronb73c9f02021-02-15 12:29:4531#include "rtc_base/time_utils.h"
Sebastian Janssond4c5d632018-07-10 10:57:3732#include "system_wrappers/include/cpu_info.h"
33#include "test/call_test.h"
Steve Anton10542f22019-01-11 17:11:0034#include "test/testsupport/file_utils.h"
Sebastian Janssond4c5d632018-07-10 10:57:3735#include "test/testsupport/frame_writer.h"
Sebastian Janssond4c5d632018-07-10 10:57:3736#include "test/testsupport/test_artifacts.h"
Artem Titov8a9f3a82023-04-25 07:56:4937#include "test/video_test_constants.h"
Sebastian Janssond4c5d632018-07-10 10:57:3738
Mirko Bonadei2ab97f62019-07-18 11:44:1239ABSL_FLAG(bool,
40 save_worst_frame,
41 false,
42 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
43 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 10:57:3744
45namespace webrtc {
46namespace {
Artem Titov182044182022-09-24 23:47:0447
48using ::webrtc::test::GetGlobalMetricsLogger;
49using ::webrtc::test::ImprovementDirection;
50using ::webrtc::test::Metric;
51using ::webrtc::test::Unit;
52
Danil Chapovalov0c626af2020-02-10 10:16:0053constexpr TimeDelta kSendStatsPollingInterval = TimeDelta::Seconds(1);
Sebastian Janssond4c5d632018-07-10 10:57:3754constexpr size_t kMaxComparisons = 10;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:0455// How often is keep alive message printed.
Markus Handell2cfc1af2022-08-19 08:16:4856constexpr TimeDelta kKeepAliveInterval = TimeDelta::Seconds(30);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:0457// Interval between checking that the test is over.
Markus Handell2cfc1af2022-08-19 08:16:4858constexpr TimeDelta kProbingInterval = TimeDelta::Millis(500);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:0459constexpr int kKeepAliveIntervalIterations =
Markus Handell2cfc1af2022-08-19 08:16:4860 kKeepAliveInterval.ms() / kProbingInterval.ms();
Sebastian Janssond4c5d632018-07-10 10:57:3761
62bool IsFlexfec(int payload_type) {
Artem Titov8a9f3a82023-04-25 07:56:4963 return payload_type == test::VideoTestConstants::kFlexfecPayloadType;
Sebastian Janssond4c5d632018-07-10 10:57:3764}
Artem Titov182044182022-09-24 23:47:0465
Sebastian Janssond4c5d632018-07-10 10:57:3766} // namespace
67
Danil Chapovalov9cd53b42019-10-21 11:36:5968VideoAnalyzer::VideoAnalyzer(test::LayerFilteringTransport* transport,
69 const std::string& test_label,
70 double avg_psnr_threshold,
71 double avg_ssim_threshold,
72 int duration_frames,
Ilya Nikolaevskiy06c70952020-03-16 12:01:2573 TimeDelta test_duration,
Danil Chapovalov9cd53b42019-10-21 11:36:5974 FILE* graph_data_output_file,
75 const std::string& graph_title,
76 uint32_t ssrc_to_analyze,
77 uint32_t rtx_ssrc_to_analyze,
78 size_t selected_stream,
79 int selected_sl,
80 int selected_tl,
81 bool is_quick_test_enabled,
82 Clock* clock,
83 std::string rtp_dump_name,
84 TaskQueueBase* task_queue)
Sebastian Janssond4c5d632018-07-10 10:57:3785 : transport_(transport),
86 receiver_(nullptr),
87 call_(nullptr),
88 send_stream_(nullptr),
89 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 12:10:5690 audio_receive_stream_(nullptr),
Ilya Nikolaevskiy06c70952020-03-16 12:01:2591 captured_frame_forwarder_(this, clock, duration_frames, test_duration),
Sebastian Janssond4c5d632018-07-10 10:57:3792 test_label_(test_label),
93 graph_data_output_file_(graph_data_output_file),
94 graph_title_(graph_title),
95 ssrc_to_analyze_(ssrc_to_analyze),
96 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
97 selected_stream_(selected_stream),
98 selected_sl_(selected_sl),
99 selected_tl_(selected_tl),
Johannes Krona1b99b32019-07-30 13:08:16100 mean_decode_time_ms_(0.0),
Elad Alon8c513c72019-05-07 19:22:24101 freeze_count_(0),
102 total_freezes_duration_ms_(0),
Sergey Silkined0dd8e2022-12-20 12:58:15103 total_inter_frame_delay_(0),
104 total_squared_inter_frame_delay_(0),
Elad Alon58e06572019-05-08 13:34:24105 decode_frame_rate_(0),
106 render_frame_rate_(0),
Sebastian Janssond4c5d632018-07-10 10:57:37107 last_fec_bytes_(0),
108 frames_to_process_(duration_frames),
Ilya Nikolaevskiy06c70952020-03-16 12:01:25109 test_end_(clock->CurrentTime() + test_duration),
Sebastian Janssond4c5d632018-07-10 10:57:37110 frames_recorded_(0),
111 frames_processed_(0),
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04112 captured_frames_(0),
Yves Gerey0c67c802019-08-01 15:45:54113 dropped_frames_(0),
Sebastian Janssond4c5d632018-07-10 10:57:37114 dropped_frames_before_first_encode_(0),
115 dropped_frames_before_rendering_(0),
116 last_render_time_(0),
117 last_render_delta_ms_(0),
118 last_unfreeze_time_ms_(0),
119 rtp_timestamp_delta_(0),
Sebastian Janssond4c5d632018-07-10 10:57:37120 cpu_time_(0),
121 wallclock_time_(0),
122 avg_psnr_threshold_(avg_psnr_threshold),
123 avg_ssim_threshold_(avg_ssim_threshold),
124 is_quick_test_enabled_(is_quick_test_enabled),
Niels Möller4731f002019-05-03 07:34:24125 quit_(false),
Sebastian Janssond4c5d632018-07-10 10:57:37126 done_(true, false),
Danil Chapovalovb57fe172019-12-11 08:38:44127 vp8_depacketizer_(CreateVideoRtpDepacketizer(kVideoCodecVP8)),
128 vp9_depacketizer_(CreateVideoRtpDepacketizer(kVideoCodecVP9)),
Sebastian Janssond4c5d632018-07-10 10:57:37129 clock_(clock),
Artem Titovff7730d2019-04-02 11:46:53130 start_ms_(clock->TimeInMilliseconds()),
131 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 10:57:37132 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
133
134 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
135 // so that we don't accidentally starve "real" worker threads (codec etc).
136 // Also, don't allocate more than kMaxComparisonThreads, even if there are
137 // spare cores.
138
139 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
140 RTC_DCHECK_GE(num_cores, 1);
141 static const uint32_t kMinCoresLeft = 4;
142 static const uint32_t kMaxComparisonThreads = 8;
143
144 if (num_cores <= kMinCoresLeft) {
145 num_cores = 1;
146 } else {
147 num_cores -= kMinCoresLeft;
148 num_cores = std::min(num_cores, kMaxComparisonThreads);
149 }
150
151 for (uint32_t i = 0; i < num_cores; ++i) {
Markus Handellad5037b2021-05-07 13:02:36152 comparison_thread_pool_.push_back(rtc::PlatformThread::SpawnJoinable(
153 [this] {
154 while (CompareFrames()) {
155 }
156 },
157 "Analyzer"));
Sebastian Janssond4c5d632018-07-10 10:57:37158 }
159
160 if (!rtp_dump_name.empty()) {
161 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
162 rtp_file_writer_.reset(test::RtpFileWriter::Create(
163 test::RtpFileWriter::kRtpDump, rtp_dump_name));
164 }
165}
166
167VideoAnalyzer::~VideoAnalyzer() {
Niels Möller4731f002019-05-03 07:34:24168 {
Markus Handella3765182020-07-08 11:13:32169 MutexLock lock(&comparison_lock_);
Niels Möller4731f002019-05-03 07:34:24170 quit_ = true;
171 }
Markus Handellad5037b2021-05-07 13:02:36172 // Joins all threads.
173 comparison_thread_pool_.clear();
Sebastian Janssond4c5d632018-07-10 10:57:37174}
175
176void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
177 receiver_ = receiver;
178}
179
Niels Möller1c931c42018-12-18 15:08:11180void VideoAnalyzer::SetSource(
181 rtc::VideoSourceInterface<VideoFrame>* video_source,
182 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 10:57:37183 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 15:08:11184 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 10:57:37185 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 15:08:11186 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 10:57:37187}
188
189void VideoAnalyzer::SetCall(Call* call) {
Markus Handella3765182020-07-08 11:13:32190 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37191 RTC_DCHECK(!call_);
192 call_ = call;
193}
194
195void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
Markus Handella3765182020-07-08 11:13:32196 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37197 RTC_DCHECK(!send_stream_);
198 send_stream_ = stream;
199}
200
Tommif6f45432022-05-20 13:21:20201void VideoAnalyzer::SetReceiveStream(VideoReceiveStreamInterface* stream) {
Markus Handella3765182020-07-08 11:13:32202 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37203 RTC_DCHECK(!receive_stream_);
204 receive_stream_ = stream;
205}
206
Tommi3176ef72022-05-22 18:47:28207void VideoAnalyzer::SetAudioReceiveStream(
208 AudioReceiveStreamInterface* recv_stream) {
Markus Handella3765182020-07-08 11:13:32209 MutexLock lock(&lock_);
Christoffer Rodbroc2a02882018-08-07 12:10:56210 RTC_CHECK(!audio_receive_stream_);
211 audio_receive_stream_ = recv_stream;
212}
213
Sebastian Janssond4c5d632018-07-10 10:57:37214rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
215 return &captured_frame_forwarder_;
216}
217
218rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
219 return &captured_frame_forwarder_;
220}
221
Per Kjellander89870ff2023-01-19 15:45:58222void VideoAnalyzer::DeliverRtcpPacket(rtc::CopyOnWriteBuffer packet) {
223 return receiver_->DeliverRtcpPacket(std::move(packet));
224}
Per Kjellander3e61f882023-01-19 10:08:35225
Per Kjellander89870ff2023-01-19 15:45:58226void VideoAnalyzer::DeliverRtpPacket(
227 MediaType media_type,
228 RtpPacketReceived packet,
229 PacketReceiver::OnUndemuxablePacketHandler undemuxable_packet_handler) {
Sebastian Janssond4c5d632018-07-10 10:57:37230 if (rtp_file_writer_) {
231 test::RtpPacket p;
Per Kjellander89870ff2023-01-19 15:45:58232 memcpy(p.data, packet.Buffer().data(), packet.size());
Sebastian Janssond4c5d632018-07-10 10:57:37233 p.length = packet.size();
234 p.original_length = packet.size();
235 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
236 rtp_file_writer_->WritePacket(&p);
237 }
238
Per Kjellander89870ff2023-01-19 15:45:58239 if (!IsFlexfec(packet.PayloadType()) &&
240 (packet.Ssrc() == ssrc_to_analyze_ ||
241 packet.Ssrc() == rtx_ssrc_to_analyze_)) {
Sebastian Janssond4c5d632018-07-10 10:57:37242 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
243 // (FlexFEC and media are sent on different SSRCs, which have different
244 // timestamps spaces.)
245 // Also ignore packets from wrong SSRC, but include retransmits.
Markus Handella3765182020-07-08 11:13:32246 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37247 int64_t timestamp =
Per Kjellander89870ff2023-01-19 15:45:58248 wrap_handler_.Unwrap(packet.Timestamp() - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 13:17:26249 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37250 }
251
Per Kjellander89870ff2023-01-19 15:45:58252 return receiver_->DeliverRtpPacket(media_type, std::move(packet),
253 std::move(undemuxable_packet_handler));
Sebastian Janssond4c5d632018-07-10 10:57:37254}
255
256void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
Markus Handella3765182020-07-08 11:13:32257 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37258 if (!first_encoded_timestamp_) {
259 while (frames_.front().timestamp() != video_frame.timestamp()) {
260 ++dropped_frames_before_first_encode_;
261 frames_.pop_front();
262 RTC_CHECK(!frames_.empty());
263 }
264 first_encoded_timestamp_ = video_frame.timestamp();
265 }
266}
267
Niels Möller88be9722018-10-10 08:58:52268void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Markus Handella3765182020-07-08 11:13:32269 MutexLock lock(&lock_);
Niels Möller88be9722018-10-10 08:58:52270 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
271 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 10:57:37272 }
273}
274
Harald Alvestrandd43af912023-08-15 11:41:45275bool VideoAnalyzer::SendRtp(rtc::ArrayView<const uint8_t> packet,
Sebastian Janssond4c5d632018-07-10 10:57:37276 const PacketOptions& options) {
Danil Chapovalovb57fe172019-12-11 08:38:44277 RtpPacket rtp_packet;
Harald Alvestrandd43af912023-08-15 11:41:45278 rtp_packet.Parse(packet);
Sebastian Janssond4c5d632018-07-10 10:57:37279
Sebastian Jansson11c012a2019-03-29 13:17:26280 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37281
Harald Alvestrandd43af912023-08-15 11:41:45282 bool result = transport_->SendRtp(packet, options);
Sebastian Janssond4c5d632018-07-10 10:57:37283 {
Markus Handella3765182020-07-08 11:13:32284 MutexLock lock(&lock_);
Danil Chapovalovb57fe172019-12-11 08:38:44285 if (rtp_timestamp_delta_ == 0 && rtp_packet.Ssrc() == ssrc_to_analyze_) {
Sebastian Janssond4c5d632018-07-10 10:57:37286 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
Danil Chapovalovb57fe172019-12-11 08:38:44287 rtp_timestamp_delta_ = rtp_packet.Timestamp() - *first_sent_timestamp_;
Sebastian Janssond4c5d632018-07-10 10:57:37288 }
289
Danil Chapovalovb57fe172019-12-11 08:38:44290 if (!IsFlexfec(rtp_packet.PayloadType()) &&
291 rtp_packet.Ssrc() == ssrc_to_analyze_) {
Sebastian Janssond4c5d632018-07-10 10:57:37292 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
293 // (FlexFEC and media are sent on different SSRCs, which have different
294 // timestamps spaces.)
295 // Also ignore packets from wrong SSRC and retransmits.
296 int64_t timestamp =
Danil Chapovalovb57fe172019-12-11 08:38:44297 wrap_handler_.Unwrap(rtp_packet.Timestamp() - rtp_timestamp_delta_);
Sebastian Janssond4c5d632018-07-10 10:57:37298 send_times_[timestamp] = current_time;
299
Danil Chapovalovb57fe172019-12-11 08:38:44300 if (IsInSelectedSpatialAndTemporalLayer(rtp_packet)) {
301 encoded_frame_sizes_[timestamp] += rtp_packet.payload_size();
Sebastian Janssond4c5d632018-07-10 10:57:37302 }
Sebastian Janssond4c5d632018-07-10 10:57:37303 }
304 }
305 return result;
306}
307
Harald Alvestrandd43af912023-08-15 11:41:45308bool VideoAnalyzer::SendRtcp(rtc::ArrayView<const uint8_t> packet) {
309 return transport_->SendRtcp(packet);
Sebastian Janssond4c5d632018-07-10 10:57:37310}
311
312void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 13:17:26313 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37314
Markus Handella3765182020-07-08 11:13:32315 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37316
317 StartExcludingCpuThreadTime();
318
319 int64_t send_timestamp =
320 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
321
322 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
323 if (!last_rendered_frame_) {
324 // No previous frame rendered, this one was dropped after sending but
325 // before rendering.
326 ++dropped_frames_before_rendering_;
327 } else {
328 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
329 render_time_ms);
330 }
331 frames_.pop_front();
332 RTC_DCHECK(!frames_.empty());
333 }
334
335 VideoFrame reference_frame = frames_.front();
336 frames_.pop_front();
337 int64_t reference_timestamp =
338 wrap_handler_.Unwrap(reference_frame.timestamp());
339 if (send_timestamp == reference_timestamp - 1) {
340 // TODO(ivica): Make this work for > 2 streams.
341 // Look at RTPSender::BuildRTPHeader.
342 ++send_timestamp;
343 }
344 ASSERT_EQ(reference_timestamp, send_timestamp);
345
346 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
347
348 last_rendered_frame_ = video_frame;
349
350 StopExcludingCpuThreadTime();
351}
352
353void VideoAnalyzer::Wait() {
354 // Frame comparisons can be very expensive. Wait for test to be done, but
355 // at time-out check if frames_processed is going up. If so, give it more
356 // time, otherwise fail. Hopefully this will reduce test flakiness.
357
Danil Chapovalov9cd53b42019-10-21 11:36:59358 RepeatingTaskHandle stats_polling_task = RepeatingTaskHandle::DelayedStart(
359 task_queue_, kSendStatsPollingInterval, [this] {
360 PollStats();
361 return kSendStatsPollingInterval;
362 });
Sebastian Janssond4c5d632018-07-10 10:57:37363
364 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04365 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 10:57:37366 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04367
Markus Handell2cfc1af2022-08-19 08:16:48368 while (!done_.Wait(kProbingInterval)) {
Sebastian Janssond4c5d632018-07-10 10:57:37369 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04370 int frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37371 {
Markus Handella3765182020-07-08 11:13:32372 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37373 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04374 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 10:57:37375 }
376
377 // Print some output so test infrastructure won't think we've crashed.
378 const char* kKeepAliveMessages[3] = {
379 "Uh, I'm-I'm not quite dead, sir.",
380 "Uh, I-I think uh, I could pull through, sir.",
381 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04382 if (++iteration % kKeepAliveIntervalIterations == 0) {
383 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
384 }
Sebastian Janssond4c5d632018-07-10 10:57:37385
386 if (last_frames_processed == -1) {
387 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04388 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37389 continue;
390 }
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04391 if (frames_processed == last_frames_processed &&
Ilya Nikolaevskiy06c70952020-03-16 12:01:25392 last_frames_captured == frames_captured &&
393 clock_->CurrentTime() > test_end_) {
Sebastian Janssond4c5d632018-07-10 10:57:37394 done_.Set();
395 break;
396 }
397 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04398 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37399 }
400
401 if (iteration > 0)
402 printf("- Farewell, sweet Concorde!\n");
403
Danil Chapovalove519f382022-08-11 10:26:09404 SendTask(task_queue_, [&] { stats_polling_task.Stop(); });
Artem Titovff7730d2019-04-02 11:46:53405
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04406 PrintResults();
407 if (graph_data_output_file_)
408 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 10:57:37409}
410
Sebastian Janssond4c5d632018-07-10 10:57:37411void VideoAnalyzer::StartMeasuringCpuProcessTime() {
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::StopMeasuringCpuProcessTime() {
Markus Handella3765182020-07-08 11:13:32418 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37419 cpu_time_ += rtc::GetProcessCpuTimeNanos();
420 wallclock_time_ += rtc::SystemTimeNanos();
421}
422
423void VideoAnalyzer::StartExcludingCpuThreadTime() {
Markus Handella3765182020-07-08 11:13:32424 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37425 cpu_time_ += rtc::GetThreadCpuTimeNanos();
426}
427
428void VideoAnalyzer::StopExcludingCpuThreadTime() {
Markus Handella3765182020-07-08 11:13:32429 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37430 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
431}
432
433double VideoAnalyzer::GetCpuUsagePercent() {
Markus Handella3765182020-07-08 11:13:32434 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37435 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
436}
437
438bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
Danil Chapovalovb57fe172019-12-11 08:38:44439 const RtpPacket& rtp_packet) {
Artem Titov8a9f3a82023-04-25 07:56:49440 if (rtp_packet.PayloadType() == test::VideoTestConstants::kPayloadTypeVP8) {
Danil Chapovalovb57fe172019-12-11 08:38:44441 auto parsed_payload = vp8_depacketizer_->Parse(rtp_packet.PayloadBuffer());
442 RTC_DCHECK(parsed_payload);
443 const auto& vp8_header = absl::get<RTPVideoHeaderVP8>(
444 parsed_payload->video_header.video_type_header);
445 int temporal_idx = vp8_header.temporalIdx;
446 return selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
447 temporal_idx <= selected_tl_;
448 }
philipel29d88462018-08-08 12:26:00449
Artem Titov8a9f3a82023-04-25 07:56:49450 if (rtp_packet.PayloadType() == test::VideoTestConstants::kPayloadTypeVP9) {
Danil Chapovalovb57fe172019-12-11 08:38:44451 auto parsed_payload = vp9_depacketizer_->Parse(rtp_packet.PayloadBuffer());
452 RTC_DCHECK(parsed_payload);
453 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
454 parsed_payload->video_header.video_type_header);
455 int temporal_idx = vp9_header.temporal_idx;
456 int spatial_idx = vp9_header.spatial_idx;
Sebastian Janssond4c5d632018-07-10 10:57:37457 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
458 temporal_idx <= selected_tl_) &&
459 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
460 spatial_idx <= selected_sl_);
461 }
Danil Chapovalovb57fe172019-12-11 08:38:44462
463 return true;
Sebastian Janssond4c5d632018-07-10 10:57:37464}
465
Sebastian Janssond4c5d632018-07-10 10:57:37466void VideoAnalyzer::PollStats() {
Artem Titovab30d722021-07-27 14:22:11467 // Do not grab `comparison_lock_`, before `GetStats()` completes.
Ilya Nikolaevskiy3ea3e0c2020-07-29 16:20:13468 // Otherwise a deadlock may occur:
Artem Titovab30d722021-07-27 14:22:11469 // 1) `comparison_lock_` is acquired after `lock_`
470 // 2) `lock_` is acquired after internal pacer lock in SendRtp()
Ilya Nikolaevskiy3ea3e0c2020-07-29 16:20:13471 // 3) internal pacer lock is acquired by GetStats().
472 Call::Stats call_stats = call_->GetStats();
473
Markus Handella3765182020-07-08 11:13:32474 MutexLock lock(&comparison_lock_);
Artem Titovff7730d2019-04-02 11:46:53475
Artem Titovff7730d2019-04-02 11:46:53476 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
477
478 VideoSendStream::Stats send_stats = send_stream_->GetStats();
479 // It's not certain that we yet have estimates for any of these stats.
480 // Check that they are positive before mixing them in.
481 if (send_stats.encode_frame_rate > 0)
482 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
483 if (send_stats.avg_encode_time_ms > 0)
484 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
485 if (send_stats.encode_usage_percent > 0)
486 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
487 if (send_stats.media_bitrate_bps > 0)
488 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
489 size_t fec_bytes = 0;
490 for (const auto& kv : send_stats.substreams) {
491 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
492 kv.second.rtp_stats.fec.padding_bytes;
493 }
494 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
495 last_fec_bytes_ = fec_bytes;
496
497 if (receive_stream_ != nullptr) {
Tommif6f45432022-05-20 13:21:20498 VideoReceiveStreamInterface::Stats receive_stats =
499 receive_stream_->GetStats();
Sergey Silkined0dd8e2022-12-20 12:58:15500
501 // Freeze metrics.
502 freeze_count_ = receive_stats.freeze_count;
503 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
504 total_inter_frame_delay_ = receive_stats.total_inter_frame_delay;
505 total_squared_inter_frame_delay_ =
506 receive_stats.total_squared_inter_frame_delay;
507
Artem Titovab30d722021-07-27 14:22:11508 // `total_decode_time_ms` gives a good estimate of the mean decode time,
509 // `decode_ms` is used to keep track of the standard deviation.
Johannes Krona1b99b32019-07-30 13:08:16510 if (receive_stats.frames_decoded > 0)
Philipp Hancked970b092022-06-17 05:34:23511 mean_decode_time_ms_ = receive_stats.total_decode_time.ms<double>() /
512 receive_stats.frames_decoded;
Artem Titovff7730d2019-04-02 11:46:53513 if (receive_stats.decode_ms > 0)
514 decode_time_ms_.AddSample(receive_stats.decode_ms);
515 if (receive_stats.max_decode_ms > 0)
516 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
517 if (receive_stats.width > 0 && receive_stats.height > 0) {
518 pixels_.AddSample(receive_stats.width * receive_stats.height);
519 }
Elad Alon58e06572019-05-08 13:34:24520
Artem Titovab30d722021-07-27 14:22:11521 // `frames_decoded` and `frames_rendered` are used because they are more
522 // accurate than `decode_frame_rate` and `render_frame_rate`.
Elad Alon58e06572019-05-08 13:34:24523 // The latter two are calculated on a momentary basis.
Sergey Silkined0dd8e2022-12-20 12:58:15524 if (total_inter_frame_delay_ > 0) {
525 decode_frame_rate_ =
526 receive_stats.frames_decoded / total_inter_frame_delay_;
527 render_frame_rate_ =
528 receive_stats.frames_rendered / total_inter_frame_delay_;
Elad Alon58e06572019-05-08 13:34:24529 }
Artem Titovff7730d2019-04-02 11:46:53530 }
531
532 if (audio_receive_stream_ != nullptr) {
Tommi3176ef72022-05-22 18:47:28533 AudioReceiveStreamInterface::Stats receive_stats =
Niels Möller6b4d9622020-09-14 08:47:50534 audio_receive_stream_->GetStats(/*get_and_clear_legacy_stats=*/true);
Artem Titovff7730d2019-04-02 11:46:53535 audio_expand_rate_.AddSample(receive_stats.expand_rate);
536 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
537 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
538 }
539
540 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
Sebastian Janssond4c5d632018-07-10 10:57:37541}
542
Sebastian Janssond4c5d632018-07-10 10:57:37543bool VideoAnalyzer::CompareFrames() {
544 if (AllFramesRecorded())
545 return false;
546
547 FrameComparison comparison;
548
549 if (!PopComparison(&comparison)) {
550 // Wait until new comparison task is available, or test is done.
551 // If done, wake up remaining threads waiting.
Markus Handell2cfc1af2022-08-19 08:16:48552 comparison_available_event_.Wait(TimeDelta::Seconds(1));
Sebastian Janssond4c5d632018-07-10 10:57:37553 if (AllFramesRecorded()) {
554 comparison_available_event_.Set();
555 return false;
556 }
557 return true; // Try again.
558 }
559
560 StartExcludingCpuThreadTime();
561
562 PerformFrameComparison(comparison);
563
564 StopExcludingCpuThreadTime();
565
566 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 10:57:37567 done_.Set();
568 comparison_available_event_.Set();
569 return false;
570 }
571
572 return true;
573}
574
575bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
Markus Handella3765182020-07-08 11:13:32576 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37577 // If AllFramesRecorded() is true, it means we have already popped
578 // frames_to_process_ frames from comparisons_, so there is no more work
579 // for this thread to be done. frames_processed_ might still be lower if
580 // all comparisons are not done, but those frames are currently being
581 // worked on by other threads.
Markus Handelladbfd1d2020-07-08 07:32:42582 if (comparisons_.empty() || AllFramesRecordedLocked())
Sebastian Janssond4c5d632018-07-10 10:57:37583 return false;
584
585 *comparison = comparisons_.front();
586 comparisons_.pop_front();
587
588 FrameRecorded();
589 return true;
590}
591
592void VideoAnalyzer::FrameRecorded() {
Sebastian Janssond4c5d632018-07-10 10:57:37593 ++frames_recorded_;
594}
595
596bool VideoAnalyzer::AllFramesRecorded() {
Markus Handella3765182020-07-08 11:13:32597 MutexLock lock(&comparison_lock_);
Markus Handelladbfd1d2020-07-08 07:32:42598 return AllFramesRecordedLocked();
599}
600
601bool VideoAnalyzer::AllFramesRecordedLocked() {
Niels Möller4731f002019-05-03 07:34:24602 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
Ilya Nikolaevskiy06c70952020-03-16 12:01:25603 return frames_recorded_ == frames_to_process_ ||
604 (clock_->CurrentTime() > test_end_ && comparisons_.empty()) || quit_;
Sebastian Janssond4c5d632018-07-10 10:57:37605}
606
607bool VideoAnalyzer::FrameProcessed() {
Markus Handella3765182020-07-08 11:13:32608 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37609 ++frames_processed_;
Mirko Bonadei25ab3222021-07-08 18:08:20610 RTC_DCHECK_LE(frames_processed_, frames_to_process_);
Ilya Nikolaevskiy06c70952020-03-16 12:01:25611 return frames_processed_ == frames_to_process_ ||
612 (clock_->CurrentTime() > test_end_ && comparisons_.empty());
Sebastian Janssond4c5d632018-07-10 10:57:37613}
614
615void VideoAnalyzer::PrintResults() {
616 StopMeasuringCpuProcessTime();
Yves Gerey0c67c802019-08-01 15:45:54617 int dropped_frames_diff;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04618 {
Markus Handella3765182020-07-08 11:13:32619 MutexLock lock(&lock_);
Yves Gerey0c67c802019-08-01 15:45:54620 dropped_frames_diff = dropped_frames_before_first_encode_ +
621 dropped_frames_before_rendering_ + frames_.size();
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04622 }
Markus Handella3765182020-07-08 11:13:32623 MutexLock lock(&comparison_lock_);
Artem Titov182044182022-09-24 23:47:04624 PrintResult("psnr_dB", psnr_, Unit::kUnitless,
625 ImprovementDirection::kBiggerIsBetter);
626 PrintResult("ssim", ssim_, Unit::kUnitless,
627 ImprovementDirection::kBiggerIsBetter);
628 PrintResult("sender_time", sender_time_, Unit::kMilliseconds,
629 ImprovementDirection::kSmallerIsBetter);
630 PrintResult("receiver_time", receiver_time_, Unit::kMilliseconds,
631 ImprovementDirection::kSmallerIsBetter);
632 PrintResult("network_time", network_time_, Unit::kMilliseconds,
633 ImprovementDirection::kSmallerIsBetter);
634 PrintResult("total_delay_incl_network", end_to_end_, Unit::kMilliseconds,
635 ImprovementDirection::kSmallerIsBetter);
636 PrintResult("time_between_rendered_frames", rendered_delta_,
637 Unit::kMilliseconds, ImprovementDirection::kSmallerIsBetter);
638 PrintResult("encode_frame_rate_fps", encode_frame_rate_, Unit::kHertz,
639 ImprovementDirection::kBiggerIsBetter);
640 PrintResult("encode_time", encode_time_ms_, Unit::kMilliseconds,
641 ImprovementDirection::kSmallerIsBetter);
642 PrintResult("media_bitrate", media_bitrate_bps_ / 1000.0,
643 Unit::kKilobitsPerSecond, ImprovementDirection::kNeitherIsBetter);
644 PrintResult("fec_bitrate", fec_bitrate_bps_ / 1000.0,
645 Unit::kKilobitsPerSecond, ImprovementDirection::kNeitherIsBetter);
646 PrintResult("send_bandwidth", send_bandwidth_bps_ / 1000.0,
647 Unit::kKilobitsPerSecond, ImprovementDirection::kNeitherIsBetter);
648 PrintResult("pixels_per_frame", pixels_, Unit::kCount,
649 ImprovementDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37650
Artem Titov182044182022-09-24 23:47:04651 GetGlobalMetricsLogger()->LogSingleValueMetric(
652 "decode_frame_rate_fps", test_label_, decode_frame_rate_, Unit::kHertz,
653 ImprovementDirection::kBiggerIsBetter);
654 GetGlobalMetricsLogger()->LogSingleValueMetric(
655 "render_frame_rate_fps", test_label_, render_frame_rate_, Unit::kHertz,
656 ImprovementDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 13:34:24657
Elad Alon8c513c72019-05-07 19:22:24658 // Record the time from the last freeze until the last rendered frame to
659 // ensure we cover the full timespan of the session. Otherwise the metric
660 // would penalize an early freeze followed by no freezes until the end.
661 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
662
663 // Freeze metrics.
Artem Titov182044182022-09-24 23:47:04664 PrintResult("time_between_freezes", time_between_freezes_,
665 Unit::kMilliseconds, ImprovementDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24666
667 const double freeze_count_double = static_cast<double>(freeze_count_);
668 const double total_freezes_duration_ms_double =
669 static_cast<double>(total_freezes_duration_ms_);
670 const double total_frames_duration_ms_double =
Sergey Silkined0dd8e2022-12-20 12:58:15671 total_inter_frame_delay_ * rtc::kNumMillisecsPerSec;
Elad Alon8c513c72019-05-07 19:22:24672
673 if (total_frames_duration_ms_double > 0) {
Artem Titov182044182022-09-24 23:47:04674 GetGlobalMetricsLogger()->LogSingleValueMetric(
675 "freeze_duration_ratio", test_label_,
Artem Titovea9798c2019-07-31 12:27:42676 total_freezes_duration_ms_double / total_frames_duration_ms_double,
Artem Titov182044182022-09-24 23:47:04677 Unit::kUnitless, ImprovementDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24678 RTC_DCHECK_LE(total_freezes_duration_ms_double,
679 total_frames_duration_ms_double);
680
681 constexpr double ms_per_minute = 60 * 1000;
682 const double total_frames_duration_min =
683 total_frames_duration_ms_double / ms_per_minute;
684 if (total_frames_duration_min > 0) {
Artem Titov182044182022-09-24 23:47:04685 GetGlobalMetricsLogger()->LogSingleValueMetric(
686 "freeze_count_per_minute", test_label_,
687 freeze_count_double / total_frames_duration_min, Unit::kUnitless,
688 ImprovementDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24689 }
690 }
691
Artem Titov182044182022-09-24 23:47:04692 GetGlobalMetricsLogger()->LogSingleValueMetric(
693 "freeze_duration_average", test_label_,
694 freeze_count_double > 0
695 ? total_freezes_duration_ms_double / freeze_count_double
696 : 0,
697 Unit::kMilliseconds, ImprovementDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24698
Sergey Silkined0dd8e2022-12-20 12:58:15699 if (total_squared_inter_frame_delay_ > 0) {
Artem Titov182044182022-09-24 23:47:04700 GetGlobalMetricsLogger()->LogSingleValueMetric(
701 "harmonic_frame_rate_fps", test_label_,
Sergey Silkined0dd8e2022-12-20 12:58:15702 total_frames_duration_ms_double /
703 (1000 * total_squared_inter_frame_delay_),
Artem Titov182044182022-09-24 23:47:04704 Unit::kHertz, ImprovementDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24705 }
706
Sebastian Janssond4c5d632018-07-10 10:57:37707 if (worst_frame_) {
Artem Titov182044182022-09-24 23:47:04708 GetGlobalMetricsLogger()->LogSingleValueMetric(
709 "min_psnr_dB", test_label_, worst_frame_->psnr, Unit::kUnitless,
710 ImprovementDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37711 }
712
713 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 13:08:16714 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titov182044182022-09-24 23:47:04715 decode_time_ms_, Unit::kMilliseconds,
716 ImprovementDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37717 }
Yves Gerey0c67c802019-08-01 15:45:54718 dropped_frames_ += dropped_frames_diff;
Artem Titov182044182022-09-24 23:47:04719 GetGlobalMetricsLogger()->LogSingleValueMetric(
720 "dropped_frames", test_label_, dropped_frames_, Unit::kCount,
721 ImprovementDirection::kSmallerIsBetter);
722 GetGlobalMetricsLogger()->LogSingleValueMetric(
723 "cpu_usage_%", test_label_, GetCpuUsagePercent(), Unit::kUnitless,
724 ImprovementDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37725
726#if defined(WEBRTC_WIN)
727 // On Linux and Mac in Resident Set some unused pages may be counted.
728 // Therefore this metric will depend on order in which tests are run and
729 // will be flaky.
Artem Titov182044182022-09-24 23:47:04730 PrintResult("memory_usage", memory_usage_, Unit::kBytes,
731 ImprovementDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37732#endif
733
734 // Saving only the worst frame for manual analysis. Intention here is to
735 // only detect video corruptions and not to track picture quality. Thus,
736 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 11:44:12737 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 10:57:37738 std::string output_dir;
739 test::GetTestArtifactsDir(&output_dir);
740 std::string output_path =
Niels Möller7b3c76b2018-11-07 08:54:28741 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 10:57:37742 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
743 test::JpegFrameWriter frame_writer(output_path);
744 RTC_CHECK(
745 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
746 }
747
Christoffer Rodbroc2a02882018-08-07 12:10:56748 if (audio_receive_stream_ != nullptr) {
Artem Titov182044182022-09-24 23:47:04749 PrintResult("audio_expand_rate", audio_expand_rate_, Unit::kUnitless,
750 ImprovementDirection::kSmallerIsBetter);
751 PrintResult("audio_accelerate_rate", audio_accelerate_rate_,
752 Unit::kUnitless, ImprovementDirection::kSmallerIsBetter);
753 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_,
754 Unit::kMilliseconds, ImprovementDirection::kNeitherIsBetter);
Christoffer Rodbroc2a02882018-08-07 12:10:56755 }
756
Sebastian Janssond4c5d632018-07-10 10:57:37757 // Disable quality check for quick test, as quality checks may fail
758 // because too few samples were collected.
759 if (!is_quick_test_enabled_) {
Artem Titov182044182022-09-24 23:47:04760 EXPECT_GT(psnr_.GetAverage(), avg_psnr_threshold_);
761 EXPECT_GT(ssim_.GetAverage(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 10:57:37762 }
763}
764
765void VideoAnalyzer::PerformFrameComparison(
766 const VideoAnalyzer::FrameComparison& comparison) {
767 // Perform expensive psnr and ssim calculations while not holding lock.
768 double psnr = -1.0;
769 double ssim = -1.0;
770 if (comparison.reference && !comparison.dropped) {
771 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
772 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
773 }
774
Markus Handella3765182020-07-08 11:13:32775 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37776
777 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
778 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
779 }
780
781 if (graph_data_output_file_) {
782 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
783 comparison.send_time_ms, comparison.recv_time_ms,
784 comparison.render_time_ms,
785 comparison.encoded_frame_size, psnr, ssim));
786 }
787 if (psnr >= 0.0)
788 psnr_.AddSample(psnr);
789 if (ssim >= 0.0)
790 ssim_.AddSample(ssim);
791
792 if (comparison.dropped) {
793 ++dropped_frames_;
794 return;
795 }
796 if (last_unfreeze_time_ms_ == 0)
797 last_unfreeze_time_ms_ = comparison.render_time_ms;
798 if (last_render_time_ != 0) {
799 const int64_t render_delta_ms =
800 comparison.render_time_ms - last_render_time_;
801 rendered_delta_.AddSample(render_delta_ms);
802 if (last_render_delta_ms_ != 0 &&
803 render_delta_ms - last_render_delta_ms_ > 150) {
804 time_between_freezes_.AddSample(last_render_time_ -
805 last_unfreeze_time_ms_);
806 last_unfreeze_time_ms_ = comparison.render_time_ms;
807 }
808 last_render_delta_ms_ = render_delta_ms;
809 }
810 last_render_time_ = comparison.render_time_ms;
811
812 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
813 if (comparison.recv_time_ms > 0) {
814 // If recv_time_ms == 0, this frame consisted of a packets which were all
815 // lost in the transport. Since we were able to render the frame, however,
816 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
817 // happens internally in Call, and we can therefore here not know which
818 // FEC packets that protected the lost media packets. Consequently, we
819 // were not able to record a meaningful recv_time_ms. We therefore skip
820 // this sample.
821 //
822 // The reasoning above does not hold for ULPFEC and RTX, as for those
823 // strategies the timestamp of the received packets is set to the
824 // timestamp of the protected/retransmitted media packet. I.e., then
825 // recv_time_ms != 0, even though the media packets were lost.
826 receiver_time_.AddSample(comparison.render_time_ms -
827 comparison.recv_time_ms);
828 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
829 }
830 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
831 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
832}
833
Artem Titov182044182022-09-24 23:47:04834void VideoAnalyzer::PrintResult(absl::string_view result_type,
835 const SamplesStatsCounter& stats,
836 Unit unit,
837 ImprovementDirection improvement_direction) {
838 GetGlobalMetricsLogger()->LogMetric(result_type, test_label_, stats, unit,
839 improvement_direction);
Sebastian Janssond4c5d632018-07-10 10:57:37840}
841
Artem Titov82ce3842019-09-23 15:55:52842void VideoAnalyzer::PrintResultWithExternalMean(
Artem Titov182044182022-09-24 23:47:04843 absl::string_view result_type,
Artem Titov82ce3842019-09-23 15:55:52844 double mean,
Artem Titov182044182022-09-24 23:47:04845 const SamplesStatsCounter& stats,
846 Unit unit,
847 ImprovementDirection improvement_direction) {
Johannes Krona1b99b32019-07-30 13:08:16848 // If the true mean is different than the sample mean, the sample variance is
849 // too low. The sample variance given a known mean is obtained by adding the
850 // squared error between the true mean and the sample mean.
851 double compensated_variance =
Artem Titov182044182022-09-24 23:47:04852 stats.IsEmpty()
853 ? 0.0
854 : stats.GetVariance() + pow(mean - stats.GetAverage(), 2.0);
855 GetGlobalMetricsLogger()->LogMetric(
856 result_type, test_label_,
857 Metric::Stats{.mean = mean, .stddev = std::sqrt(compensated_variance)},
858 unit, improvement_direction);
Johannes Krona1b99b32019-07-30 13:08:16859}
860
Sebastian Janssond4c5d632018-07-10 10:57:37861void VideoAnalyzer::PrintSamplesToFile() {
862 FILE* out = graph_data_output_file_;
Markus Handella3765182020-07-08 11:13:32863 MutexLock lock(&comparison_lock_);
Steve Antonbd631a02019-03-28 17:51:27864 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
865 return A.input_time_ms < B.input_time_ms;
866 });
Sebastian Janssond4c5d632018-07-10 10:57:37867
868 fprintf(out, "%s\n", graph_title_.c_str());
Niels Möllerea1e6f42022-05-09 07:21:14869 fprintf(out, "%zu\n", samples_.size());
Sebastian Janssond4c5d632018-07-10 10:57:37870 fprintf(out,
871 "dropped "
872 "input_time_ms "
873 "send_time_ms "
874 "recv_time_ms "
875 "render_time_ms "
876 "encoded_frame_size "
877 "psnr "
878 "ssim "
879 "encode_time_ms\n");
880 for (const Sample& sample : samples_) {
881 fprintf(out,
Niels Möllerea1e6f42022-05-09 07:21:14882 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %zu %lf %lf\n",
Sebastian Janssond4c5d632018-07-10 10:57:37883 sample.dropped, sample.input_time_ms, sample.send_time_ms,
884 sample.recv_time_ms, sample.render_time_ms,
885 sample.encoded_frame_size, sample.psnr, sample.ssim);
886 }
887}
888
Sebastian Janssond4c5d632018-07-10 10:57:37889void VideoAnalyzer::AddCapturedFrameForComparison(
890 const VideoFrame& video_frame) {
Yves Gerey0c67c802019-08-01 15:45:54891 bool must_capture = false;
892 {
Markus Handella3765182020-07-08 11:13:32893 MutexLock lock(&comparison_lock_);
Yves Gerey0c67c802019-08-01 15:45:54894 must_capture = captured_frames_ < frames_to_process_;
895 if (must_capture) {
896 ++captured_frames_;
897 }
898 }
899 if (must_capture) {
Markus Handella3765182020-07-08 11:13:32900 MutexLock lock(&lock_);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04901 frames_.push_back(video_frame);
902 }
Sebastian Janssond4c5d632018-07-10 10:57:37903}
904
905void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
906 const VideoFrame& render,
907 bool dropped,
908 int64_t render_time_ms) {
909 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
910 int64_t send_time_ms = send_times_[reference_timestamp];
911 send_times_.erase(reference_timestamp);
912 int64_t recv_time_ms = recv_times_[reference_timestamp];
913 recv_times_.erase(reference_timestamp);
914
915 // TODO(ivica): Make this work for > 2 streams.
916 auto it = encoded_frame_sizes_.find(reference_timestamp);
917 if (it == encoded_frame_sizes_.end())
918 it = encoded_frame_sizes_.find(reference_timestamp - 1);
919 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
920 if (it != encoded_frame_sizes_.end())
921 encoded_frame_sizes_.erase(it);
922
Markus Handella3765182020-07-08 11:13:32923 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37924 if (comparisons_.size() < kMaxComparisons) {
925 comparisons_.push_back(FrameComparison(
926 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
927 recv_time_ms, render_time_ms, encoded_size));
928 } else {
929 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
930 send_time_ms, recv_time_ms,
931 render_time_ms, encoded_size));
932 }
933 comparison_available_event_.Set();
934}
935
936VideoAnalyzer::FrameComparison::FrameComparison()
937 : dropped(false),
938 input_time_ms(0),
939 send_time_ms(0),
940 recv_time_ms(0),
941 render_time_ms(0),
942 encoded_frame_size(0) {}
943
944VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
945 const VideoFrame& render,
946 bool dropped,
947 int64_t input_time_ms,
948 int64_t send_time_ms,
949 int64_t recv_time_ms,
950 int64_t render_time_ms,
951 size_t encoded_frame_size)
952 : reference(reference),
953 render(render),
954 dropped(dropped),
955 input_time_ms(input_time_ms),
956 send_time_ms(send_time_ms),
957 recv_time_ms(recv_time_ms),
958 render_time_ms(render_time_ms),
959 encoded_frame_size(encoded_frame_size) {}
960
961VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
962 int64_t input_time_ms,
963 int64_t send_time_ms,
964 int64_t recv_time_ms,
965 int64_t render_time_ms,
966 size_t encoded_frame_size)
967 : dropped(dropped),
968 input_time_ms(input_time_ms),
969 send_time_ms(send_time_ms),
970 recv_time_ms(recv_time_ms),
971 render_time_ms(render_time_ms),
972 encoded_frame_size(encoded_frame_size) {}
973
974VideoAnalyzer::Sample::Sample(int dropped,
975 int64_t input_time_ms,
976 int64_t send_time_ms,
977 int64_t recv_time_ms,
978 int64_t render_time_ms,
979 size_t encoded_frame_size,
980 double psnr,
981 double ssim)
982 : dropped(dropped),
983 input_time_ms(input_time_ms),
984 send_time_ms(send_time_ms),
985 recv_time_ms(recv_time_ms),
986 render_time_ms(render_time_ms),
987 encoded_frame_size(encoded_frame_size),
988 psnr(psnr),
989 ssim(ssim) {}
990
Sebastian Janssond4c5d632018-07-10 10:57:37991VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
992 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04993 Clock* clock,
Ilya Nikolaevskiy06c70952020-03-16 12:01:25994 int frames_to_capture,
995 TimeDelta test_duration)
Sebastian Janssond4c5d632018-07-10 10:57:37996 : analyzer_(analyzer),
997 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 15:08:11998 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04999 clock_(clock),
1000 captured_frames_(0),
Ilya Nikolaevskiy06c70952020-03-16 12:01:251001 frames_to_capture_(frames_to_capture),
1002 test_end_(clock->CurrentTime() + test_duration) {}
Sebastian Janssond4c5d632018-07-10 10:57:371003
1004void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 15:08:111005 VideoSourceInterface<VideoFrame>* video_source) {
1006 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 10:57:371007}
1008
1009void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
1010 const VideoFrame& video_frame) {
1011 VideoFrame copy = video_frame;
1012 // Frames from the capturer does not have a rtp timestamp.
1013 // Create one so it can be used for comparison.
1014 RTC_DCHECK_EQ(0, video_frame.timestamp());
1015 if (video_frame.ntp_time_ms() == 0)
1016 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
1017 copy.set_timestamp(copy.ntp_time_ms() * 90);
1018 analyzer_->AddCapturedFrameForComparison(copy);
Markus Handella3765182020-07-08 11:13:321019 MutexLock lock(&lock_);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:041020 ++captured_frames_;
Ilya Nikolaevskiy06c70952020-03-16 12:01:251021 if (send_stream_input_ && clock_->CurrentTime() <= test_end_ &&
1022 captured_frames_ <= frames_to_capture_) {
Sebastian Janssond4c5d632018-07-10 10:57:371023 send_stream_input_->OnFrame(copy);
Ilya Nikolaevskiy06c70952020-03-16 12:01:251024 }
Sebastian Janssond4c5d632018-07-10 10:57:371025}
1026
1027void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1028 rtc::VideoSinkInterface<VideoFrame>* sink,
1029 const rtc::VideoSinkWants& wants) {
1030 {
Markus Handella3765182020-07-08 11:13:321031 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:371032 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1033 send_stream_input_ = sink;
1034 }
Niels Möller1c931c42018-12-18 15:08:111035 if (video_source_) {
1036 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 10:57:371037 }
1038}
1039
1040void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1041 rtc::VideoSinkInterface<VideoFrame>* sink) {
Markus Handella3765182020-07-08 11:13:321042 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:371043 RTC_DCHECK(sink == send_stream_input_);
1044 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 10:57:371045}
1046
1047} // namespace webrtc