blob: 24bcfc9c8fc47933bf3c67bb606918e1c5735b8a [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 Titov01716662023-04-21 15:35: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 Titov01716662023-04-21 15:35: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
275bool VideoAnalyzer::SendRtp(const uint8_t* packet,
276 size_t length,
277 const PacketOptions& options) {
Danil Chapovalovb57fe172019-12-11 08:38:44278 RtpPacket rtp_packet;
279 rtp_packet.Parse(packet, length);
Sebastian Janssond4c5d632018-07-10 10:57:37280
Sebastian Jansson11c012a2019-03-29 13:17:26281 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37282
283 bool result = transport_->SendRtp(packet, length, options);
284 {
Markus Handella3765182020-07-08 11:13:32285 MutexLock lock(&lock_);
Danil Chapovalovb57fe172019-12-11 08:38:44286 if (rtp_timestamp_delta_ == 0 && rtp_packet.Ssrc() == ssrc_to_analyze_) {
Sebastian Janssond4c5d632018-07-10 10:57:37287 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
Danil Chapovalovb57fe172019-12-11 08:38:44288 rtp_timestamp_delta_ = rtp_packet.Timestamp() - *first_sent_timestamp_;
Sebastian Janssond4c5d632018-07-10 10:57:37289 }
290
Danil Chapovalovb57fe172019-12-11 08:38:44291 if (!IsFlexfec(rtp_packet.PayloadType()) &&
292 rtp_packet.Ssrc() == ssrc_to_analyze_) {
Sebastian Janssond4c5d632018-07-10 10:57:37293 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
294 // (FlexFEC and media are sent on different SSRCs, which have different
295 // timestamps spaces.)
296 // Also ignore packets from wrong SSRC and retransmits.
297 int64_t timestamp =
Danil Chapovalovb57fe172019-12-11 08:38:44298 wrap_handler_.Unwrap(rtp_packet.Timestamp() - rtp_timestamp_delta_);
Sebastian Janssond4c5d632018-07-10 10:57:37299 send_times_[timestamp] = current_time;
300
Danil Chapovalovb57fe172019-12-11 08:38:44301 if (IsInSelectedSpatialAndTemporalLayer(rtp_packet)) {
302 encoded_frame_sizes_[timestamp] += rtp_packet.payload_size();
Sebastian Janssond4c5d632018-07-10 10:57:37303 }
Sebastian Janssond4c5d632018-07-10 10:57:37304 }
305 }
306 return result;
307}
308
309bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
310 return transport_->SendRtcp(packet, length);
311}
312
313void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 13:17:26314 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 10:57:37315
Markus Handella3765182020-07-08 11:13:32316 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37317
318 StartExcludingCpuThreadTime();
319
320 int64_t send_timestamp =
321 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
322
323 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
324 if (!last_rendered_frame_) {
325 // No previous frame rendered, this one was dropped after sending but
326 // before rendering.
327 ++dropped_frames_before_rendering_;
328 } else {
329 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
330 render_time_ms);
331 }
332 frames_.pop_front();
333 RTC_DCHECK(!frames_.empty());
334 }
335
336 VideoFrame reference_frame = frames_.front();
337 frames_.pop_front();
338 int64_t reference_timestamp =
339 wrap_handler_.Unwrap(reference_frame.timestamp());
340 if (send_timestamp == reference_timestamp - 1) {
341 // TODO(ivica): Make this work for > 2 streams.
342 // Look at RTPSender::BuildRTPHeader.
343 ++send_timestamp;
344 }
345 ASSERT_EQ(reference_timestamp, send_timestamp);
346
347 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
348
349 last_rendered_frame_ = video_frame;
350
351 StopExcludingCpuThreadTime();
352}
353
354void VideoAnalyzer::Wait() {
355 // Frame comparisons can be very expensive. Wait for test to be done, but
356 // at time-out check if frames_processed is going up. If so, give it more
357 // time, otherwise fail. Hopefully this will reduce test flakiness.
358
Danil Chapovalov9cd53b42019-10-21 11:36:59359 RepeatingTaskHandle stats_polling_task = RepeatingTaskHandle::DelayedStart(
360 task_queue_, kSendStatsPollingInterval, [this] {
361 PollStats();
362 return kSendStatsPollingInterval;
363 });
Sebastian Janssond4c5d632018-07-10 10:57:37364
365 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04366 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 10:57:37367 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04368
Markus Handell2cfc1af2022-08-19 08:16:48369 while (!done_.Wait(kProbingInterval)) {
Sebastian Janssond4c5d632018-07-10 10:57:37370 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04371 int frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37372 {
Markus Handella3765182020-07-08 11:13:32373 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37374 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04375 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 10:57:37376 }
377
378 // Print some output so test infrastructure won't think we've crashed.
379 const char* kKeepAliveMessages[3] = {
380 "Uh, I'm-I'm not quite dead, sir.",
381 "Uh, I-I think uh, I could pull through, sir.",
382 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04383 if (++iteration % kKeepAliveIntervalIterations == 0) {
384 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
385 }
Sebastian Janssond4c5d632018-07-10 10:57:37386
387 if (last_frames_processed == -1) {
388 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04389 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37390 continue;
391 }
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04392 if (frames_processed == last_frames_processed &&
Ilya Nikolaevskiy06c70952020-03-16 12:01:25393 last_frames_captured == frames_captured &&
394 clock_->CurrentTime() > test_end_) {
Sebastian Janssond4c5d632018-07-10 10:57:37395 done_.Set();
396 break;
397 }
398 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04399 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 10:57:37400 }
401
402 if (iteration > 0)
403 printf("- Farewell, sweet Concorde!\n");
404
Danil Chapovalove519f382022-08-11 10:26:09405 SendTask(task_queue_, [&] { stats_polling_task.Stop(); });
Artem Titovff7730d2019-04-02 11:46:53406
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04407 PrintResults();
408 if (graph_data_output_file_)
409 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 10:57:37410}
411
Sebastian Janssond4c5d632018-07-10 10:57:37412void VideoAnalyzer::StartMeasuringCpuProcessTime() {
Markus Handella3765182020-07-08 11:13:32413 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37414 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
415 wallclock_time_ -= rtc::SystemTimeNanos();
416}
417
418void VideoAnalyzer::StopMeasuringCpuProcessTime() {
Markus Handella3765182020-07-08 11:13:32419 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37420 cpu_time_ += rtc::GetProcessCpuTimeNanos();
421 wallclock_time_ += rtc::SystemTimeNanos();
422}
423
424void VideoAnalyzer::StartExcludingCpuThreadTime() {
Markus Handella3765182020-07-08 11:13:32425 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37426 cpu_time_ += rtc::GetThreadCpuTimeNanos();
427}
428
429void VideoAnalyzer::StopExcludingCpuThreadTime() {
Markus Handella3765182020-07-08 11:13:32430 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37431 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
432}
433
434double VideoAnalyzer::GetCpuUsagePercent() {
Markus Handella3765182020-07-08 11:13:32435 MutexLock lock(&cpu_measurement_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37436 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
437}
438
439bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
Danil Chapovalovb57fe172019-12-11 08:38:44440 const RtpPacket& rtp_packet) {
Artem Titov01716662023-04-21 15:35:49441 if (rtp_packet.PayloadType() == test::VideoTestConstants::kPayloadTypeVP8) {
Danil Chapovalovb57fe172019-12-11 08:38:44442 auto parsed_payload = vp8_depacketizer_->Parse(rtp_packet.PayloadBuffer());
443 RTC_DCHECK(parsed_payload);
444 const auto& vp8_header = absl::get<RTPVideoHeaderVP8>(
445 parsed_payload->video_header.video_type_header);
446 int temporal_idx = vp8_header.temporalIdx;
447 return selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
448 temporal_idx <= selected_tl_;
449 }
philipel29d88462018-08-08 12:26:00450
Artem Titov01716662023-04-21 15:35:49451 if (rtp_packet.PayloadType() == test::VideoTestConstants::kPayloadTypeVP9) {
Danil Chapovalovb57fe172019-12-11 08:38:44452 auto parsed_payload = vp9_depacketizer_->Parse(rtp_packet.PayloadBuffer());
453 RTC_DCHECK(parsed_payload);
454 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
455 parsed_payload->video_header.video_type_header);
456 int temporal_idx = vp9_header.temporal_idx;
457 int spatial_idx = vp9_header.spatial_idx;
Sebastian Janssond4c5d632018-07-10 10:57:37458 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
459 temporal_idx <= selected_tl_) &&
460 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
461 spatial_idx <= selected_sl_);
462 }
Danil Chapovalovb57fe172019-12-11 08:38:44463
464 return true;
Sebastian Janssond4c5d632018-07-10 10:57:37465}
466
Sebastian Janssond4c5d632018-07-10 10:57:37467void VideoAnalyzer::PollStats() {
Artem Titovab30d722021-07-27 14:22:11468 // Do not grab `comparison_lock_`, before `GetStats()` completes.
Ilya Nikolaevskiy3ea3e0c2020-07-29 16:20:13469 // Otherwise a deadlock may occur:
Artem Titovab30d722021-07-27 14:22:11470 // 1) `comparison_lock_` is acquired after `lock_`
471 // 2) `lock_` is acquired after internal pacer lock in SendRtp()
Ilya Nikolaevskiy3ea3e0c2020-07-29 16:20:13472 // 3) internal pacer lock is acquired by GetStats().
473 Call::Stats call_stats = call_->GetStats();
474
Markus Handella3765182020-07-08 11:13:32475 MutexLock lock(&comparison_lock_);
Artem Titovff7730d2019-04-02 11:46:53476
Artem Titovff7730d2019-04-02 11:46:53477 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
478
479 VideoSendStream::Stats send_stats = send_stream_->GetStats();
480 // It's not certain that we yet have estimates for any of these stats.
481 // Check that they are positive before mixing them in.
482 if (send_stats.encode_frame_rate > 0)
483 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
484 if (send_stats.avg_encode_time_ms > 0)
485 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
486 if (send_stats.encode_usage_percent > 0)
487 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
488 if (send_stats.media_bitrate_bps > 0)
489 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
490 size_t fec_bytes = 0;
491 for (const auto& kv : send_stats.substreams) {
492 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
493 kv.second.rtp_stats.fec.padding_bytes;
494 }
495 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
496 last_fec_bytes_ = fec_bytes;
497
498 if (receive_stream_ != nullptr) {
Tommif6f45432022-05-20 13:21:20499 VideoReceiveStreamInterface::Stats receive_stats =
500 receive_stream_->GetStats();
Sergey Silkined0dd8e2022-12-20 12:58:15501
502 // Freeze metrics.
503 freeze_count_ = receive_stats.freeze_count;
504 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
505 total_inter_frame_delay_ = receive_stats.total_inter_frame_delay;
506 total_squared_inter_frame_delay_ =
507 receive_stats.total_squared_inter_frame_delay;
508
Artem Titovab30d722021-07-27 14:22:11509 // `total_decode_time_ms` gives a good estimate of the mean decode time,
510 // `decode_ms` is used to keep track of the standard deviation.
Johannes Krona1b99b32019-07-30 13:08:16511 if (receive_stats.frames_decoded > 0)
Philipp Hancked970b092022-06-17 05:34:23512 mean_decode_time_ms_ = receive_stats.total_decode_time.ms<double>() /
513 receive_stats.frames_decoded;
Artem Titovff7730d2019-04-02 11:46:53514 if (receive_stats.decode_ms > 0)
515 decode_time_ms_.AddSample(receive_stats.decode_ms);
516 if (receive_stats.max_decode_ms > 0)
517 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
518 if (receive_stats.width > 0 && receive_stats.height > 0) {
519 pixels_.AddSample(receive_stats.width * receive_stats.height);
520 }
Elad Alon58e06572019-05-08 13:34:24521
Artem Titovab30d722021-07-27 14:22:11522 // `frames_decoded` and `frames_rendered` are used because they are more
523 // accurate than `decode_frame_rate` and `render_frame_rate`.
Elad Alon58e06572019-05-08 13:34:24524 // The latter two are calculated on a momentary basis.
Sergey Silkined0dd8e2022-12-20 12:58:15525 if (total_inter_frame_delay_ > 0) {
526 decode_frame_rate_ =
527 receive_stats.frames_decoded / total_inter_frame_delay_;
528 render_frame_rate_ =
529 receive_stats.frames_rendered / total_inter_frame_delay_;
Elad Alon58e06572019-05-08 13:34:24530 }
Artem Titovff7730d2019-04-02 11:46:53531 }
532
533 if (audio_receive_stream_ != nullptr) {
Tommi3176ef72022-05-22 18:47:28534 AudioReceiveStreamInterface::Stats receive_stats =
Niels Möller6b4d9622020-09-14 08:47:50535 audio_receive_stream_->GetStats(/*get_and_clear_legacy_stats=*/true);
Artem Titovff7730d2019-04-02 11:46:53536 audio_expand_rate_.AddSample(receive_stats.expand_rate);
537 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
538 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
539 }
540
541 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
Sebastian Janssond4c5d632018-07-10 10:57:37542}
543
Sebastian Janssond4c5d632018-07-10 10:57:37544bool VideoAnalyzer::CompareFrames() {
545 if (AllFramesRecorded())
546 return false;
547
548 FrameComparison comparison;
549
550 if (!PopComparison(&comparison)) {
551 // Wait until new comparison task is available, or test is done.
552 // If done, wake up remaining threads waiting.
Markus Handell2cfc1af2022-08-19 08:16:48553 comparison_available_event_.Wait(TimeDelta::Seconds(1));
Sebastian Janssond4c5d632018-07-10 10:57:37554 if (AllFramesRecorded()) {
555 comparison_available_event_.Set();
556 return false;
557 }
558 return true; // Try again.
559 }
560
561 StartExcludingCpuThreadTime();
562
563 PerformFrameComparison(comparison);
564
565 StopExcludingCpuThreadTime();
566
567 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 10:57:37568 done_.Set();
569 comparison_available_event_.Set();
570 return false;
571 }
572
573 return true;
574}
575
576bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
Markus Handella3765182020-07-08 11:13:32577 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37578 // If AllFramesRecorded() is true, it means we have already popped
579 // frames_to_process_ frames from comparisons_, so there is no more work
580 // for this thread to be done. frames_processed_ might still be lower if
581 // all comparisons are not done, but those frames are currently being
582 // worked on by other threads.
Markus Handelladbfd1d2020-07-08 07:32:42583 if (comparisons_.empty() || AllFramesRecordedLocked())
Sebastian Janssond4c5d632018-07-10 10:57:37584 return false;
585
586 *comparison = comparisons_.front();
587 comparisons_.pop_front();
588
589 FrameRecorded();
590 return true;
591}
592
593void VideoAnalyzer::FrameRecorded() {
Sebastian Janssond4c5d632018-07-10 10:57:37594 ++frames_recorded_;
595}
596
597bool VideoAnalyzer::AllFramesRecorded() {
Markus Handella3765182020-07-08 11:13:32598 MutexLock lock(&comparison_lock_);
Markus Handelladbfd1d2020-07-08 07:32:42599 return AllFramesRecordedLocked();
600}
601
602bool VideoAnalyzer::AllFramesRecordedLocked() {
Niels Möller4731f002019-05-03 07:34:24603 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
Ilya Nikolaevskiy06c70952020-03-16 12:01:25604 return frames_recorded_ == frames_to_process_ ||
605 (clock_->CurrentTime() > test_end_ && comparisons_.empty()) || quit_;
Sebastian Janssond4c5d632018-07-10 10:57:37606}
607
608bool VideoAnalyzer::FrameProcessed() {
Markus Handella3765182020-07-08 11:13:32609 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37610 ++frames_processed_;
Mirko Bonadei25ab3222021-07-08 18:08:20611 RTC_DCHECK_LE(frames_processed_, frames_to_process_);
Ilya Nikolaevskiy06c70952020-03-16 12:01:25612 return frames_processed_ == frames_to_process_ ||
613 (clock_->CurrentTime() > test_end_ && comparisons_.empty());
Sebastian Janssond4c5d632018-07-10 10:57:37614}
615
616void VideoAnalyzer::PrintResults() {
617 StopMeasuringCpuProcessTime();
Yves Gerey0c67c802019-08-01 15:45:54618 int dropped_frames_diff;
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04619 {
Markus Handella3765182020-07-08 11:13:32620 MutexLock lock(&lock_);
Yves Gerey0c67c802019-08-01 15:45:54621 dropped_frames_diff = dropped_frames_before_first_encode_ +
622 dropped_frames_before_rendering_ + frames_.size();
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04623 }
Markus Handella3765182020-07-08 11:13:32624 MutexLock lock(&comparison_lock_);
Artem Titov182044182022-09-24 23:47:04625 PrintResult("psnr_dB", psnr_, Unit::kUnitless,
626 ImprovementDirection::kBiggerIsBetter);
627 PrintResult("ssim", ssim_, Unit::kUnitless,
628 ImprovementDirection::kBiggerIsBetter);
629 PrintResult("sender_time", sender_time_, Unit::kMilliseconds,
630 ImprovementDirection::kSmallerIsBetter);
631 PrintResult("receiver_time", receiver_time_, Unit::kMilliseconds,
632 ImprovementDirection::kSmallerIsBetter);
633 PrintResult("network_time", network_time_, Unit::kMilliseconds,
634 ImprovementDirection::kSmallerIsBetter);
635 PrintResult("total_delay_incl_network", end_to_end_, Unit::kMilliseconds,
636 ImprovementDirection::kSmallerIsBetter);
637 PrintResult("time_between_rendered_frames", rendered_delta_,
638 Unit::kMilliseconds, ImprovementDirection::kSmallerIsBetter);
639 PrintResult("encode_frame_rate_fps", encode_frame_rate_, Unit::kHertz,
640 ImprovementDirection::kBiggerIsBetter);
641 PrintResult("encode_time", encode_time_ms_, Unit::kMilliseconds,
642 ImprovementDirection::kSmallerIsBetter);
643 PrintResult("media_bitrate", media_bitrate_bps_ / 1000.0,
644 Unit::kKilobitsPerSecond, ImprovementDirection::kNeitherIsBetter);
645 PrintResult("fec_bitrate", fec_bitrate_bps_ / 1000.0,
646 Unit::kKilobitsPerSecond, ImprovementDirection::kNeitherIsBetter);
647 PrintResult("send_bandwidth", send_bandwidth_bps_ / 1000.0,
648 Unit::kKilobitsPerSecond, ImprovementDirection::kNeitherIsBetter);
649 PrintResult("pixels_per_frame", pixels_, Unit::kCount,
650 ImprovementDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37651
Artem Titov182044182022-09-24 23:47:04652 GetGlobalMetricsLogger()->LogSingleValueMetric(
653 "decode_frame_rate_fps", test_label_, decode_frame_rate_, Unit::kHertz,
654 ImprovementDirection::kBiggerIsBetter);
655 GetGlobalMetricsLogger()->LogSingleValueMetric(
656 "render_frame_rate_fps", test_label_, render_frame_rate_, Unit::kHertz,
657 ImprovementDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 13:34:24658
Elad Alon8c513c72019-05-07 19:22:24659 // Record the time from the last freeze until the last rendered frame to
660 // ensure we cover the full timespan of the session. Otherwise the metric
661 // would penalize an early freeze followed by no freezes until the end.
662 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
663
664 // Freeze metrics.
Artem Titov182044182022-09-24 23:47:04665 PrintResult("time_between_freezes", time_between_freezes_,
666 Unit::kMilliseconds, ImprovementDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24667
668 const double freeze_count_double = static_cast<double>(freeze_count_);
669 const double total_freezes_duration_ms_double =
670 static_cast<double>(total_freezes_duration_ms_);
671 const double total_frames_duration_ms_double =
Sergey Silkined0dd8e2022-12-20 12:58:15672 total_inter_frame_delay_ * rtc::kNumMillisecsPerSec;
Elad Alon8c513c72019-05-07 19:22:24673
674 if (total_frames_duration_ms_double > 0) {
Artem Titov182044182022-09-24 23:47:04675 GetGlobalMetricsLogger()->LogSingleValueMetric(
676 "freeze_duration_ratio", test_label_,
Artem Titovea9798c2019-07-31 12:27:42677 total_freezes_duration_ms_double / total_frames_duration_ms_double,
Artem Titov182044182022-09-24 23:47:04678 Unit::kUnitless, ImprovementDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24679 RTC_DCHECK_LE(total_freezes_duration_ms_double,
680 total_frames_duration_ms_double);
681
682 constexpr double ms_per_minute = 60 * 1000;
683 const double total_frames_duration_min =
684 total_frames_duration_ms_double / ms_per_minute;
685 if (total_frames_duration_min > 0) {
Artem Titov182044182022-09-24 23:47:04686 GetGlobalMetricsLogger()->LogSingleValueMetric(
687 "freeze_count_per_minute", test_label_,
688 freeze_count_double / total_frames_duration_min, Unit::kUnitless,
689 ImprovementDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24690 }
691 }
692
Artem Titov182044182022-09-24 23:47:04693 GetGlobalMetricsLogger()->LogSingleValueMetric(
694 "freeze_duration_average", test_label_,
695 freeze_count_double > 0
696 ? total_freezes_duration_ms_double / freeze_count_double
697 : 0,
698 Unit::kMilliseconds, ImprovementDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24699
Sergey Silkined0dd8e2022-12-20 12:58:15700 if (total_squared_inter_frame_delay_ > 0) {
Artem Titov182044182022-09-24 23:47:04701 GetGlobalMetricsLogger()->LogSingleValueMetric(
702 "harmonic_frame_rate_fps", test_label_,
Sergey Silkined0dd8e2022-12-20 12:58:15703 total_frames_duration_ms_double /
704 (1000 * total_squared_inter_frame_delay_),
Artem Titov182044182022-09-24 23:47:04705 Unit::kHertz, ImprovementDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 19:22:24706 }
707
Sebastian Janssond4c5d632018-07-10 10:57:37708 if (worst_frame_) {
Artem Titov182044182022-09-24 23:47:04709 GetGlobalMetricsLogger()->LogSingleValueMetric(
710 "min_psnr_dB", test_label_, worst_frame_->psnr, Unit::kUnitless,
711 ImprovementDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37712 }
713
714 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 13:08:16715 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titov182044182022-09-24 23:47:04716 decode_time_ms_, Unit::kMilliseconds,
717 ImprovementDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37718 }
Yves Gerey0c67c802019-08-01 15:45:54719 dropped_frames_ += dropped_frames_diff;
Artem Titov182044182022-09-24 23:47:04720 GetGlobalMetricsLogger()->LogSingleValueMetric(
721 "dropped_frames", test_label_, dropped_frames_, Unit::kCount,
722 ImprovementDirection::kSmallerIsBetter);
723 GetGlobalMetricsLogger()->LogSingleValueMetric(
724 "cpu_usage_%", test_label_, GetCpuUsagePercent(), Unit::kUnitless,
725 ImprovementDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37726
727#if defined(WEBRTC_WIN)
728 // On Linux and Mac in Resident Set some unused pages may be counted.
729 // Therefore this metric will depend on order in which tests are run and
730 // will be flaky.
Artem Titov182044182022-09-24 23:47:04731 PrintResult("memory_usage", memory_usage_, Unit::kBytes,
732 ImprovementDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 10:57:37733#endif
734
735 // Saving only the worst frame for manual analysis. Intention here is to
736 // only detect video corruptions and not to track picture quality. Thus,
737 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 11:44:12738 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 10:57:37739 std::string output_dir;
740 test::GetTestArtifactsDir(&output_dir);
741 std::string output_path =
Niels Möller7b3c76b2018-11-07 08:54:28742 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 10:57:37743 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
744 test::JpegFrameWriter frame_writer(output_path);
745 RTC_CHECK(
746 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
747 }
748
Christoffer Rodbroc2a02882018-08-07 12:10:56749 if (audio_receive_stream_ != nullptr) {
Artem Titov182044182022-09-24 23:47:04750 PrintResult("audio_expand_rate", audio_expand_rate_, Unit::kUnitless,
751 ImprovementDirection::kSmallerIsBetter);
752 PrintResult("audio_accelerate_rate", audio_accelerate_rate_,
753 Unit::kUnitless, ImprovementDirection::kSmallerIsBetter);
754 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_,
755 Unit::kMilliseconds, ImprovementDirection::kNeitherIsBetter);
Christoffer Rodbroc2a02882018-08-07 12:10:56756 }
757
Sebastian Janssond4c5d632018-07-10 10:57:37758 // Disable quality check for quick test, as quality checks may fail
759 // because too few samples were collected.
760 if (!is_quick_test_enabled_) {
Artem Titov182044182022-09-24 23:47:04761 EXPECT_GT(psnr_.GetAverage(), avg_psnr_threshold_);
762 EXPECT_GT(ssim_.GetAverage(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 10:57:37763 }
764}
765
766void VideoAnalyzer::PerformFrameComparison(
767 const VideoAnalyzer::FrameComparison& comparison) {
768 // Perform expensive psnr and ssim calculations while not holding lock.
769 double psnr = -1.0;
770 double ssim = -1.0;
771 if (comparison.reference && !comparison.dropped) {
772 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
773 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
774 }
775
Markus Handella3765182020-07-08 11:13:32776 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37777
778 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
779 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
780 }
781
782 if (graph_data_output_file_) {
783 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
784 comparison.send_time_ms, comparison.recv_time_ms,
785 comparison.render_time_ms,
786 comparison.encoded_frame_size, psnr, ssim));
787 }
788 if (psnr >= 0.0)
789 psnr_.AddSample(psnr);
790 if (ssim >= 0.0)
791 ssim_.AddSample(ssim);
792
793 if (comparison.dropped) {
794 ++dropped_frames_;
795 return;
796 }
797 if (last_unfreeze_time_ms_ == 0)
798 last_unfreeze_time_ms_ = comparison.render_time_ms;
799 if (last_render_time_ != 0) {
800 const int64_t render_delta_ms =
801 comparison.render_time_ms - last_render_time_;
802 rendered_delta_.AddSample(render_delta_ms);
803 if (last_render_delta_ms_ != 0 &&
804 render_delta_ms - last_render_delta_ms_ > 150) {
805 time_between_freezes_.AddSample(last_render_time_ -
806 last_unfreeze_time_ms_);
807 last_unfreeze_time_ms_ = comparison.render_time_ms;
808 }
809 last_render_delta_ms_ = render_delta_ms;
810 }
811 last_render_time_ = comparison.render_time_ms;
812
813 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
814 if (comparison.recv_time_ms > 0) {
815 // If recv_time_ms == 0, this frame consisted of a packets which were all
816 // lost in the transport. Since we were able to render the frame, however,
817 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
818 // happens internally in Call, and we can therefore here not know which
819 // FEC packets that protected the lost media packets. Consequently, we
820 // were not able to record a meaningful recv_time_ms. We therefore skip
821 // this sample.
822 //
823 // The reasoning above does not hold for ULPFEC and RTX, as for those
824 // strategies the timestamp of the received packets is set to the
825 // timestamp of the protected/retransmitted media packet. I.e., then
826 // recv_time_ms != 0, even though the media packets were lost.
827 receiver_time_.AddSample(comparison.render_time_ms -
828 comparison.recv_time_ms);
829 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
830 }
831 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
832 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
833}
834
Artem Titov182044182022-09-24 23:47:04835void VideoAnalyzer::PrintResult(absl::string_view result_type,
836 const SamplesStatsCounter& stats,
837 Unit unit,
838 ImprovementDirection improvement_direction) {
839 GetGlobalMetricsLogger()->LogMetric(result_type, test_label_, stats, unit,
840 improvement_direction);
Sebastian Janssond4c5d632018-07-10 10:57:37841}
842
Artem Titov82ce3842019-09-23 15:55:52843void VideoAnalyzer::PrintResultWithExternalMean(
Artem Titov182044182022-09-24 23:47:04844 absl::string_view result_type,
Artem Titov82ce3842019-09-23 15:55:52845 double mean,
Artem Titov182044182022-09-24 23:47:04846 const SamplesStatsCounter& stats,
847 Unit unit,
848 ImprovementDirection improvement_direction) {
Johannes Krona1b99b32019-07-30 13:08:16849 // If the true mean is different than the sample mean, the sample variance is
850 // too low. The sample variance given a known mean is obtained by adding the
851 // squared error between the true mean and the sample mean.
852 double compensated_variance =
Artem Titov182044182022-09-24 23:47:04853 stats.IsEmpty()
854 ? 0.0
855 : stats.GetVariance() + pow(mean - stats.GetAverage(), 2.0);
856 GetGlobalMetricsLogger()->LogMetric(
857 result_type, test_label_,
858 Metric::Stats{.mean = mean, .stddev = std::sqrt(compensated_variance)},
859 unit, improvement_direction);
Johannes Krona1b99b32019-07-30 13:08:16860}
861
Sebastian Janssond4c5d632018-07-10 10:57:37862void VideoAnalyzer::PrintSamplesToFile() {
863 FILE* out = graph_data_output_file_;
Markus Handella3765182020-07-08 11:13:32864 MutexLock lock(&comparison_lock_);
Steve Antonbd631a02019-03-28 17:51:27865 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
866 return A.input_time_ms < B.input_time_ms;
867 });
Sebastian Janssond4c5d632018-07-10 10:57:37868
869 fprintf(out, "%s\n", graph_title_.c_str());
Niels Möllerea1e6f42022-05-09 07:21:14870 fprintf(out, "%zu\n", samples_.size());
Sebastian Janssond4c5d632018-07-10 10:57:37871 fprintf(out,
872 "dropped "
873 "input_time_ms "
874 "send_time_ms "
875 "recv_time_ms "
876 "render_time_ms "
877 "encoded_frame_size "
878 "psnr "
879 "ssim "
880 "encode_time_ms\n");
881 for (const Sample& sample : samples_) {
882 fprintf(out,
Niels Möllerea1e6f42022-05-09 07:21:14883 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %zu %lf %lf\n",
Sebastian Janssond4c5d632018-07-10 10:57:37884 sample.dropped, sample.input_time_ms, sample.send_time_ms,
885 sample.recv_time_ms, sample.render_time_ms,
886 sample.encoded_frame_size, sample.psnr, sample.ssim);
887 }
888}
889
Sebastian Janssond4c5d632018-07-10 10:57:37890void VideoAnalyzer::AddCapturedFrameForComparison(
891 const VideoFrame& video_frame) {
Yves Gerey0c67c802019-08-01 15:45:54892 bool must_capture = false;
893 {
Markus Handella3765182020-07-08 11:13:32894 MutexLock lock(&comparison_lock_);
Yves Gerey0c67c802019-08-01 15:45:54895 must_capture = captured_frames_ < frames_to_process_;
896 if (must_capture) {
897 ++captured_frames_;
898 }
899 }
900 if (must_capture) {
Markus Handella3765182020-07-08 11:13:32901 MutexLock lock(&lock_);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04902 frames_.push_back(video_frame);
903 }
Sebastian Janssond4c5d632018-07-10 10:57:37904}
905
906void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
907 const VideoFrame& render,
908 bool dropped,
909 int64_t render_time_ms) {
910 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
911 int64_t send_time_ms = send_times_[reference_timestamp];
912 send_times_.erase(reference_timestamp);
913 int64_t recv_time_ms = recv_times_[reference_timestamp];
914 recv_times_.erase(reference_timestamp);
915
916 // TODO(ivica): Make this work for > 2 streams.
917 auto it = encoded_frame_sizes_.find(reference_timestamp);
918 if (it == encoded_frame_sizes_.end())
919 it = encoded_frame_sizes_.find(reference_timestamp - 1);
920 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
921 if (it != encoded_frame_sizes_.end())
922 encoded_frame_sizes_.erase(it);
923
Markus Handella3765182020-07-08 11:13:32924 MutexLock lock(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 10:57:37925 if (comparisons_.size() < kMaxComparisons) {
926 comparisons_.push_back(FrameComparison(
927 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
928 recv_time_ms, render_time_ms, encoded_size));
929 } else {
930 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
931 send_time_ms, recv_time_ms,
932 render_time_ms, encoded_size));
933 }
934 comparison_available_event_.Set();
935}
936
937VideoAnalyzer::FrameComparison::FrameComparison()
938 : dropped(false),
939 input_time_ms(0),
940 send_time_ms(0),
941 recv_time_ms(0),
942 render_time_ms(0),
943 encoded_frame_size(0) {}
944
945VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
946 const VideoFrame& render,
947 bool dropped,
948 int64_t input_time_ms,
949 int64_t send_time_ms,
950 int64_t recv_time_ms,
951 int64_t render_time_ms,
952 size_t encoded_frame_size)
953 : reference(reference),
954 render(render),
955 dropped(dropped),
956 input_time_ms(input_time_ms),
957 send_time_ms(send_time_ms),
958 recv_time_ms(recv_time_ms),
959 render_time_ms(render_time_ms),
960 encoded_frame_size(encoded_frame_size) {}
961
962VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
963 int64_t input_time_ms,
964 int64_t send_time_ms,
965 int64_t recv_time_ms,
966 int64_t render_time_ms,
967 size_t encoded_frame_size)
968 : dropped(dropped),
969 input_time_ms(input_time_ms),
970 send_time_ms(send_time_ms),
971 recv_time_ms(recv_time_ms),
972 render_time_ms(render_time_ms),
973 encoded_frame_size(encoded_frame_size) {}
974
975VideoAnalyzer::Sample::Sample(int dropped,
976 int64_t input_time_ms,
977 int64_t send_time_ms,
978 int64_t recv_time_ms,
979 int64_t render_time_ms,
980 size_t encoded_frame_size,
981 double psnr,
982 double ssim)
983 : dropped(dropped),
984 input_time_ms(input_time_ms),
985 send_time_ms(send_time_ms),
986 recv_time_ms(recv_time_ms),
987 render_time_ms(render_time_ms),
988 encoded_frame_size(encoded_frame_size),
989 psnr(psnr),
990 ssim(ssim) {}
991
Sebastian Janssond4c5d632018-07-10 10:57:37992VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
993 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 15:33:04994 Clock* clock,
Ilya Nikolaevskiy06c70952020-03-16 12:01:25995 int frames_to_capture,
996 TimeDelta test_duration)
Sebastian Janssond4c5d632018-07-10 10:57:37997 : analyzer_(analyzer),
998 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 15:08:11999 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 15:33:041000 clock_(clock),
1001 captured_frames_(0),
Ilya Nikolaevskiy06c70952020-03-16 12:01:251002 frames_to_capture_(frames_to_capture),
1003 test_end_(clock->CurrentTime() + test_duration) {}
Sebastian Janssond4c5d632018-07-10 10:57:371004
1005void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 15:08:111006 VideoSourceInterface<VideoFrame>* video_source) {
1007 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 10:57:371008}
1009
1010void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
1011 const VideoFrame& video_frame) {
1012 VideoFrame copy = video_frame;
1013 // Frames from the capturer does not have a rtp timestamp.
1014 // Create one so it can be used for comparison.
1015 RTC_DCHECK_EQ(0, video_frame.timestamp());
1016 if (video_frame.ntp_time_ms() == 0)
1017 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
1018 copy.set_timestamp(copy.ntp_time_ms() * 90);
1019 analyzer_->AddCapturedFrameForComparison(copy);
Markus Handella3765182020-07-08 11:13:321020 MutexLock lock(&lock_);
Ilya Nikolaevskiy6957abe2019-01-29 15:33:041021 ++captured_frames_;
Ilya Nikolaevskiy06c70952020-03-16 12:01:251022 if (send_stream_input_ && clock_->CurrentTime() <= test_end_ &&
1023 captured_frames_ <= frames_to_capture_) {
Sebastian Janssond4c5d632018-07-10 10:57:371024 send_stream_input_->OnFrame(copy);
Ilya Nikolaevskiy06c70952020-03-16 12:01:251025 }
Sebastian Janssond4c5d632018-07-10 10:57:371026}
1027
1028void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1029 rtc::VideoSinkInterface<VideoFrame>* sink,
1030 const rtc::VideoSinkWants& wants) {
1031 {
Markus Handella3765182020-07-08 11:13:321032 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:371033 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1034 send_stream_input_ = sink;
1035 }
Niels Möller1c931c42018-12-18 15:08:111036 if (video_source_) {
1037 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 10:57:371038 }
1039}
1040
1041void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1042 rtc::VideoSinkInterface<VideoFrame>* sink) {
Markus Handella3765182020-07-08 11:13:321043 MutexLock lock(&lock_);
Sebastian Janssond4c5d632018-07-10 10:57:371044 RTC_DCHECK(sink == send_stream_input_);
1045 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 10:57:371046}
1047
1048} // namespace webrtc