blob: 2e79c2489f1f294f43c78a4ac04eebe0c31a2022 [file] [log] [blame]
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001/*
2 * Copyright 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10#include "video/video_analyzer.h"
11
12#include <algorithm>
13#include <utility>
14
Steve Antonbd631a02019-03-28 10:51:27 -070015#include "absl/algorithm/container.h"
Mirko Bonadei2ab97f62019-07-18 13:44:12 +020016#include "absl/flags/flag.h"
17#include "absl/flags/parse.h"
Niels Möller1c931c42018-12-18 16:08:11 +010018#include "common_video/libyuv/include/webrtc_libyuv.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020019#include "modules/rtp_rtcp/source/rtp_format.h"
20#include "modules/rtp_rtcp/source/rtp_utility.h"
21#include "rtc_base/cpu_time.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020022#include "rtc_base/format_macros.h"
23#include "rtc_base/memory_usage.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020024#include "system_wrappers/include/cpu_info.h"
25#include "test/call_test.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "test/testsupport/file_utils.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020027#include "test/testsupport/frame_writer.h"
28#include "test/testsupport/perf_test.h"
29#include "test/testsupport/test_artifacts.h"
30
Mirko Bonadei2ab97f62019-07-18 13:44:12 +020031ABSL_FLAG(bool,
32 save_worst_frame,
33 false,
34 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
35 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 12:57:37 +020036
37namespace webrtc {
38namespace {
39constexpr int kSendStatsPollingIntervalMs = 1000;
40constexpr size_t kMaxComparisons = 10;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010041// How often is keep alive message printed.
42constexpr int kKeepAliveIntervalSeconds = 30;
43// Interval between checking that the test is over.
44constexpr int kProbingIntervalMs = 500;
45constexpr int kKeepAliveIntervalIterations =
46 kKeepAliveIntervalSeconds * 1000 / kProbingIntervalMs;
Sebastian Janssond4c5d632018-07-10 12:57:37 +020047
48bool IsFlexfec(int payload_type) {
49 return payload_type == test::CallTest::kFlexfecPayloadType;
50}
51} // namespace
52
Artem Titovff7730d2019-04-02 13:46:53 +020053VideoAnalyzer::VideoAnalyzer(
54 test::LayerFilteringTransport* transport,
55 const std::string& test_label,
56 double avg_psnr_threshold,
57 double avg_ssim_threshold,
58 int duration_frames,
59 FILE* graph_data_output_file,
60 const std::string& graph_title,
61 uint32_t ssrc_to_analyze,
62 uint32_t rtx_ssrc_to_analyze,
63 size_t selected_stream,
64 int selected_sl,
65 int selected_tl,
66 bool is_quick_test_enabled,
67 Clock* clock,
68 std::string rtp_dump_name,
Yves Gerey6516f762019-08-29 11:50:23 +020069 test::DEPRECATED_SingleThreadedTaskQueueForTesting* task_queue)
Sebastian Janssond4c5d632018-07-10 12:57:37 +020070 : transport_(transport),
71 receiver_(nullptr),
72 call_(nullptr),
73 send_stream_(nullptr),
74 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 14:10:56 +020075 audio_receive_stream_(nullptr),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +010076 captured_frame_forwarder_(this, clock, duration_frames),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020077 test_label_(test_label),
78 graph_data_output_file_(graph_data_output_file),
79 graph_title_(graph_title),
80 ssrc_to_analyze_(ssrc_to_analyze),
81 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
82 selected_stream_(selected_stream),
83 selected_sl_(selected_sl),
84 selected_tl_(selected_tl),
Johannes Krona1b99b32019-07-30 15:08:16 +020085 mean_decode_time_ms_(0.0),
Elad Alon8c513c72019-05-07 21:22:24 +020086 freeze_count_(0),
87 total_freezes_duration_ms_(0),
88 total_frames_duration_ms_(0),
89 sum_squared_frame_durations_(0),
Elad Alon58e06572019-05-08 15:34:24 +020090 decode_frame_rate_(0),
91 render_frame_rate_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020092 last_fec_bytes_(0),
93 frames_to_process_(duration_frames),
94 frames_recorded_(0),
95 frames_processed_(0),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010096 captured_frames_(0),
Yves Gerey0c67c802019-08-01 17:45:54 +020097 dropped_frames_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020098 dropped_frames_before_first_encode_(0),
99 dropped_frames_before_rendering_(0),
100 last_render_time_(0),
101 last_render_delta_ms_(0),
102 last_unfreeze_time_ms_(0),
103 rtp_timestamp_delta_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200104 cpu_time_(0),
105 wallclock_time_(0),
106 avg_psnr_threshold_(avg_psnr_threshold),
107 avg_ssim_threshold_(avg_ssim_threshold),
108 is_quick_test_enabled_(is_quick_test_enabled),
Niels Möller4731f002019-05-03 09:34:24 +0200109 quit_(false),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200110 done_(true, false),
111 clock_(clock),
Artem Titovff7730d2019-04-02 13:46:53 +0200112 start_ms_(clock->TimeInMilliseconds()),
113 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200114 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
115
116 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
117 // so that we don't accidentally starve "real" worker threads (codec etc).
118 // Also, don't allocate more than kMaxComparisonThreads, even if there are
119 // spare cores.
120
121 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
122 RTC_DCHECK_GE(num_cores, 1);
123 static const uint32_t kMinCoresLeft = 4;
124 static const uint32_t kMaxComparisonThreads = 8;
125
126 if (num_cores <= kMinCoresLeft) {
127 num_cores = 1;
128 } else {
129 num_cores -= kMinCoresLeft;
130 num_cores = std::min(num_cores, kMaxComparisonThreads);
131 }
132
133 for (uint32_t i = 0; i < num_cores; ++i) {
134 rtc::PlatformThread* thread =
135 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
136 thread->Start();
137 comparison_thread_pool_.push_back(thread);
138 }
139
140 if (!rtp_dump_name.empty()) {
141 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
142 rtp_file_writer_.reset(test::RtpFileWriter::Create(
143 test::RtpFileWriter::kRtpDump, rtp_dump_name));
144 }
145}
146
147VideoAnalyzer::~VideoAnalyzer() {
Niels Möller4731f002019-05-03 09:34:24 +0200148 {
149 rtc::CritScope crit(&comparison_lock_);
150 quit_ = true;
151 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200152 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
153 thread->Stop();
154 delete thread;
155 }
156}
157
158void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
159 receiver_ = receiver;
160}
161
Niels Möller1c931c42018-12-18 16:08:11 +0100162void VideoAnalyzer::SetSource(
163 rtc::VideoSourceInterface<VideoFrame>* video_source,
164 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200165 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 16:08:11 +0100166 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200167 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 16:08:11 +0100168 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200169}
170
171void VideoAnalyzer::SetCall(Call* call) {
172 rtc::CritScope lock(&crit_);
173 RTC_DCHECK(!call_);
174 call_ = call;
175}
176
177void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
178 rtc::CritScope lock(&crit_);
179 RTC_DCHECK(!send_stream_);
180 send_stream_ = stream;
181}
182
183void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
184 rtc::CritScope lock(&crit_);
185 RTC_DCHECK(!receive_stream_);
186 receive_stream_ = stream;
187}
188
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200189void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
190 rtc::CritScope lock(&crit_);
191 RTC_CHECK(!audio_receive_stream_);
192 audio_receive_stream_ = recv_stream;
193}
194
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200195rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
196 return &captured_frame_forwarder_;
197}
198
199rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
200 return &captured_frame_forwarder_;
201}
202
203PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
204 MediaType media_type,
205 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 11:03:12 +0200206 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200207 // Ignore timestamps of RTCP packets. They're not synchronized with
208 // RTP packet timestamps and so they would confuse wrap_handler_.
209 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
Niels Möller70082872018-08-07 11:03:12 +0200210 return receiver_->DeliverPacket(media_type, std::move(packet),
211 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200212 }
213
214 if (rtp_file_writer_) {
215 test::RtpPacket p;
216 memcpy(p.data, packet.cdata(), packet.size());
217 p.length = packet.size();
218 p.original_length = packet.size();
219 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
220 rtp_file_writer_->WritePacket(&p);
221 }
222
223 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
224 RTPHeader header;
225 parser.Parse(&header);
226 if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
227 header.ssrc == rtx_ssrc_to_analyze_)) {
228 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
229 // (FlexFEC and media are sent on different SSRCs, which have different
230 // timestamps spaces.)
231 // Also ignore packets from wrong SSRC, but include retransmits.
232 rtc::CritScope lock(&crit_);
233 int64_t timestamp =
234 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100235 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200236 }
237
Niels Möller70082872018-08-07 11:03:12 +0200238 return receiver_->DeliverPacket(media_type, std::move(packet),
239 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200240}
241
242void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
243 rtc::CritScope lock(&crit_);
244 if (!first_encoded_timestamp_) {
245 while (frames_.front().timestamp() != video_frame.timestamp()) {
246 ++dropped_frames_before_first_encode_;
247 frames_.pop_front();
248 RTC_CHECK(!frames_.empty());
249 }
250 first_encoded_timestamp_ = video_frame.timestamp();
251 }
252}
253
Niels Möller88be9722018-10-10 10:58:52 +0200254void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200255 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200256 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
257 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200258 }
259}
260
261bool VideoAnalyzer::SendRtp(const uint8_t* packet,
262 size_t length,
263 const PacketOptions& options) {
264 RtpUtility::RtpHeaderParser parser(packet, length);
265 RTPHeader header;
266 parser.Parse(&header);
267
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100268 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200269
270 bool result = transport_->SendRtp(packet, length, options);
271 {
272 rtc::CritScope lock(&crit_);
273 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
274 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
275 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
276 }
277
278 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
279 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
280 // (FlexFEC and media are sent on different SSRCs, which have different
281 // timestamps spaces.)
282 // Also ignore packets from wrong SSRC and retransmits.
283 int64_t timestamp =
284 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
285 send_times_[timestamp] = current_time;
286
287 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
288 encoded_frame_sizes_[timestamp] +=
289 length - (header.headerLength + header.paddingLength);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200290 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200291 }
292 }
293 return result;
294}
295
296bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
297 return transport_->SendRtcp(packet, length);
298}
299
300void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100301 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200302
303 rtc::CritScope lock(&crit_);
304
305 StartExcludingCpuThreadTime();
306
307 int64_t send_timestamp =
308 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
309
310 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
311 if (!last_rendered_frame_) {
312 // No previous frame rendered, this one was dropped after sending but
313 // before rendering.
314 ++dropped_frames_before_rendering_;
315 } else {
316 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
317 render_time_ms);
318 }
319 frames_.pop_front();
320 RTC_DCHECK(!frames_.empty());
321 }
322
323 VideoFrame reference_frame = frames_.front();
324 frames_.pop_front();
325 int64_t reference_timestamp =
326 wrap_handler_.Unwrap(reference_frame.timestamp());
327 if (send_timestamp == reference_timestamp - 1) {
328 // TODO(ivica): Make this work for > 2 streams.
329 // Look at RTPSender::BuildRTPHeader.
330 ++send_timestamp;
331 }
332 ASSERT_EQ(reference_timestamp, send_timestamp);
333
334 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
335
336 last_rendered_frame_ = video_frame;
337
338 StopExcludingCpuThreadTime();
339}
340
341void VideoAnalyzer::Wait() {
342 // Frame comparisons can be very expensive. Wait for test to be done, but
343 // at time-out check if frames_processed is going up. If so, give it more
344 // time, otherwise fail. Hopefully this will reduce test flakiness.
345
Artem Titovff7730d2019-04-02 13:46:53 +0200346 {
347 rtc::CritScope lock(&comparison_lock_);
348 stop_stats_poller_ = false;
349 stats_polling_task_id_ = task_queue_->PostDelayedTask(
350 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
351 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200352
353 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100354 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200355 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100356
357 while (!done_.Wait(kProbingIntervalMs)) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200358 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100359 int frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200360 {
361 rtc::CritScope crit(&comparison_lock_);
362 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100363 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200364 }
365
366 // Print some output so test infrastructure won't think we've crashed.
367 const char* kKeepAliveMessages[3] = {
368 "Uh, I'm-I'm not quite dead, sir.",
369 "Uh, I-I think uh, I could pull through, sir.",
370 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100371 if (++iteration % kKeepAliveIntervalIterations == 0) {
372 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
373 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200374
375 if (last_frames_processed == -1) {
376 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100377 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200378 continue;
379 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100380 if (frames_processed == last_frames_processed &&
381 last_frames_captured == frames_captured) {
382 if (frames_captured < frames_to_process_) {
383 EXPECT_GT(frames_processed, last_frames_processed)
384 << "Analyzer stalled while waiting for test to finish.";
385 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200386 done_.Set();
387 break;
388 }
389 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100390 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200391 }
392
393 if (iteration > 0)
394 printf("- Farewell, sweet Concorde!\n");
395
Artem Titovff7730d2019-04-02 13:46:53 +0200396 {
397 rtc::CritScope lock(&comparison_lock_);
398 stop_stats_poller_ = true;
399 task_queue_->CancelTask(stats_polling_task_id_);
400 }
401
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100402 PrintResults();
403 if (graph_data_output_file_)
404 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200405}
406
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200407void VideoAnalyzer::StartMeasuringCpuProcessTime() {
408 rtc::CritScope lock(&cpu_measurement_lock_);
409 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
410 wallclock_time_ -= rtc::SystemTimeNanos();
411}
412
413void VideoAnalyzer::StopMeasuringCpuProcessTime() {
414 rtc::CritScope lock(&cpu_measurement_lock_);
415 cpu_time_ += rtc::GetProcessCpuTimeNanos();
416 wallclock_time_ += rtc::SystemTimeNanos();
417}
418
419void VideoAnalyzer::StartExcludingCpuThreadTime() {
420 rtc::CritScope lock(&cpu_measurement_lock_);
421 cpu_time_ += rtc::GetThreadCpuTimeNanos();
422}
423
424void VideoAnalyzer::StopExcludingCpuThreadTime() {
425 rtc::CritScope lock(&cpu_measurement_lock_);
426 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
427}
428
429double VideoAnalyzer::GetCpuUsagePercent() {
430 rtc::CritScope lock(&cpu_measurement_lock_);
431 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
432}
433
434bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
435 const uint8_t* packet,
436 size_t length,
437 const RTPHeader& header) {
438 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
439 header.payloadType != test::CallTest::kPayloadTypeVP8) {
440 return true;
441 } else {
442 // Get VP8 and VP9 specific header to check layers indexes.
443 const uint8_t* payload = packet + header.headerLength;
444 const size_t payload_length = length - header.headerLength;
445 const size_t payload_data_length = payload_length - header.paddingLength;
446 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
447 std::unique_ptr<RtpDepacketizer> depacketizer(
448 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
449 RtpDepacketizer::ParsedPayload parsed_payload;
450 bool result =
451 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
452 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200453
454 int temporal_idx;
455 int spatial_idx;
456 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000457 temporal_idx = absl::get<RTPVideoHeaderVP8>(
458 parsed_payload.video_header().video_type_header)
459 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200460 spatial_idx = kNoTemporalIdx;
461 } else {
462 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
463 parsed_payload.video_header().video_type_header);
464 temporal_idx = vp9_header.temporal_idx;
465 spatial_idx = vp9_header.spatial_idx;
466 }
467
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200468 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
469 temporal_idx <= selected_tl_) &&
470 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
471 spatial_idx <= selected_sl_);
472 }
473}
474
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200475void VideoAnalyzer::PollStats() {
Artem Titovff7730d2019-04-02 13:46:53 +0200476 rtc::CritScope crit(&comparison_lock_);
477 if (stop_stats_poller_) {
478 return;
Artem Titovf537da62019-04-02 13:46:53 +0200479 }
Artem Titovff7730d2019-04-02 13:46:53 +0200480
481 Call::Stats call_stats = call_->GetStats();
482 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
483
484 VideoSendStream::Stats send_stats = send_stream_->GetStats();
485 // It's not certain that we yet have estimates for any of these stats.
486 // Check that they are positive before mixing them in.
487 if (send_stats.encode_frame_rate > 0)
488 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
489 if (send_stats.avg_encode_time_ms > 0)
490 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
491 if (send_stats.encode_usage_percent > 0)
492 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
493 if (send_stats.media_bitrate_bps > 0)
494 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
495 size_t fec_bytes = 0;
496 for (const auto& kv : send_stats.substreams) {
497 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
498 kv.second.rtp_stats.fec.padding_bytes;
499 }
500 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
501 last_fec_bytes_ = fec_bytes;
502
503 if (receive_stream_ != nullptr) {
504 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
Johannes Krona1b99b32019-07-30 15:08:16 +0200505 // |total_decode_time_ms| gives a good estimate of the mean decode time,
506 // |decode_ms| is used to keep track of the standard deviation.
507 if (receive_stats.frames_decoded > 0)
508 mean_decode_time_ms_ =
509 static_cast<double>(receive_stats.total_decode_time_ms) /
510 receive_stats.frames_decoded;
Artem Titovff7730d2019-04-02 13:46:53 +0200511 if (receive_stats.decode_ms > 0)
512 decode_time_ms_.AddSample(receive_stats.decode_ms);
513 if (receive_stats.max_decode_ms > 0)
514 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
515 if (receive_stats.width > 0 && receive_stats.height > 0) {
516 pixels_.AddSample(receive_stats.width * receive_stats.height);
517 }
Elad Alon58e06572019-05-08 15:34:24 +0200518
519 // |frames_decoded| and |frames_rendered| are used because they are more
520 // accurate than |decode_frame_rate| and |render_frame_rate|.
521 // The latter two are calculated on a momentary basis.
522 const double total_frames_duration_sec_double =
523 static_cast<double>(receive_stats.total_frames_duration_ms) / 1000.0;
524 if (total_frames_duration_sec_double > 0) {
525 decode_frame_rate_ = static_cast<double>(receive_stats.frames_decoded) /
526 total_frames_duration_sec_double;
527 render_frame_rate_ = static_cast<double>(receive_stats.frames_rendered) /
528 total_frames_duration_sec_double;
529 }
530
531 // Freeze metrics.
Elad Alon8c513c72019-05-07 21:22:24 +0200532 freeze_count_ = receive_stats.freeze_count;
533 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
534 total_frames_duration_ms_ = receive_stats.total_frames_duration_ms;
535 sum_squared_frame_durations_ = receive_stats.sum_squared_frame_durations;
Artem Titovff7730d2019-04-02 13:46:53 +0200536 }
537
538 if (audio_receive_stream_ != nullptr) {
539 AudioReceiveStream::Stats receive_stats = audio_receive_stream_->GetStats();
540 audio_expand_rate_.AddSample(receive_stats.expand_rate);
541 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
542 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
543 }
544
545 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
546
547 stats_polling_task_id_ = task_queue_->PostDelayedTask(
548 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200549}
550
Niels Möller4731f002019-05-03 09:34:24 +0200551void VideoAnalyzer::FrameComparisonThread(void* obj) {
552 VideoAnalyzer* analyzer = static_cast<VideoAnalyzer*>(obj);
553 while (analyzer->CompareFrames()) {
554 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200555}
556
557bool VideoAnalyzer::CompareFrames() {
558 if (AllFramesRecorded())
559 return false;
560
561 FrameComparison comparison;
562
563 if (!PopComparison(&comparison)) {
564 // Wait until new comparison task is available, or test is done.
565 // If done, wake up remaining threads waiting.
566 comparison_available_event_.Wait(1000);
567 if (AllFramesRecorded()) {
568 comparison_available_event_.Set();
569 return false;
570 }
571 return true; // Try again.
572 }
573
574 StartExcludingCpuThreadTime();
575
576 PerformFrameComparison(comparison);
577
578 StopExcludingCpuThreadTime();
579
580 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200581 done_.Set();
582 comparison_available_event_.Set();
583 return false;
584 }
585
586 return true;
587}
588
589bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
590 rtc::CritScope crit(&comparison_lock_);
591 // If AllFramesRecorded() is true, it means we have already popped
592 // frames_to_process_ frames from comparisons_, so there is no more work
593 // for this thread to be done. frames_processed_ might still be lower if
594 // all comparisons are not done, but those frames are currently being
595 // worked on by other threads.
596 if (comparisons_.empty() || AllFramesRecorded())
597 return false;
598
599 *comparison = comparisons_.front();
600 comparisons_.pop_front();
601
602 FrameRecorded();
603 return true;
604}
605
606void VideoAnalyzer::FrameRecorded() {
607 rtc::CritScope crit(&comparison_lock_);
608 ++frames_recorded_;
609}
610
611bool VideoAnalyzer::AllFramesRecorded() {
612 rtc::CritScope crit(&comparison_lock_);
Niels Möller4731f002019-05-03 09:34:24 +0200613 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
614 return frames_recorded_ == frames_to_process_ || quit_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200615}
616
617bool VideoAnalyzer::FrameProcessed() {
618 rtc::CritScope crit(&comparison_lock_);
619 ++frames_processed_;
620 assert(frames_processed_ <= frames_to_process_);
621 return frames_processed_ == frames_to_process_;
622}
623
624void VideoAnalyzer::PrintResults() {
625 StopMeasuringCpuProcessTime();
Yves Gerey0c67c802019-08-01 17:45:54 +0200626 int dropped_frames_diff;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100627 {
628 rtc::CritScope crit(&crit_);
Yves Gerey0c67c802019-08-01 17:45:54 +0200629 dropped_frames_diff = dropped_frames_before_first_encode_ +
630 dropped_frames_before_rendering_ + frames_.size();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100631 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200632 rtc::CritScope crit(&comparison_lock_);
Artem Titovea9798c2019-07-31 14:27:42 +0200633 PrintResult("psnr", psnr_, "dB");
634 PrintResult("ssim", ssim_, "unitless");
635 PrintResult("sender_time", sender_time_, "ms");
636 PrintResult("receiver_time", receiver_time_, "ms");
637 PrintResult("network_time", network_time_, "ms");
638 PrintResult("total_delay_incl_network", end_to_end_, "ms");
639 PrintResult("time_between_rendered_frames", rendered_delta_, "ms");
640 PrintResult("encode_frame_rate", encode_frame_rate_, "fps");
641 PrintResult("encode_time", encode_time_ms_, "ms");
642 PrintResult("media_bitrate", media_bitrate_bps_, "bps");
643 PrintResult("fec_bitrate", fec_bitrate_bps_, "bps");
644 PrintResult("send_bandwidth", send_bandwidth_bps_, "bps");
645 PrintResult("pixels_per_frame", pixels_, "count");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200646
Elad Alon58e06572019-05-08 15:34:24 +0200647 test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
648 decode_frame_rate_, "fps", false);
649 test::PrintResult("render_frame_rate", "", test_label_.c_str(),
650 render_frame_rate_, "fps", false);
651
Elad Alon8c513c72019-05-07 21:22:24 +0200652 // Record the time from the last freeze until the last rendered frame to
653 // ensure we cover the full timespan of the session. Otherwise the metric
654 // would penalize an early freeze followed by no freezes until the end.
655 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
656
657 // Freeze metrics.
Artem Titovea9798c2019-07-31 14:27:42 +0200658 PrintResult("time_between_freezes", time_between_freezes_, "ms");
Elad Alon8c513c72019-05-07 21:22:24 +0200659
660 const double freeze_count_double = static_cast<double>(freeze_count_);
661 const double total_freezes_duration_ms_double =
662 static_cast<double>(total_freezes_duration_ms_);
663 const double total_frames_duration_ms_double =
664 static_cast<double>(total_frames_duration_ms_);
665
666 if (total_frames_duration_ms_double > 0) {
667 test::PrintResult(
668 "freeze_duration_ratio", "", test_label_.c_str(),
Artem Titovea9798c2019-07-31 14:27:42 +0200669 total_freezes_duration_ms_double / total_frames_duration_ms_double,
670 "unitless", false);
Elad Alon8c513c72019-05-07 21:22:24 +0200671 RTC_DCHECK_LE(total_freezes_duration_ms_double,
672 total_frames_duration_ms_double);
673
674 constexpr double ms_per_minute = 60 * 1000;
675 const double total_frames_duration_min =
676 total_frames_duration_ms_double / ms_per_minute;
677 if (total_frames_duration_min > 0) {
678 test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
679 freeze_count_double / total_frames_duration_min,
Artem Titovea9798c2019-07-31 14:27:42 +0200680 "unitless", false);
Elad Alon8c513c72019-05-07 21:22:24 +0200681 }
682 }
683
Elad Alon133f7e72019-05-08 09:51:56 +0200684 test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
Elad Alon8c513c72019-05-07 21:22:24 +0200685 freeze_count_double > 0
686 ? total_freezes_duration_ms_double / freeze_count_double
687 : 0,
688 "ms", false);
689
690 if (1000 * sum_squared_frame_durations_ > 0) {
691 test::PrintResult(
692 "harmonic_frame_rate", "", test_label_.c_str(),
693 total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
Artem Titovea9798c2019-07-31 14:27:42 +0200694 "fps", false);
Elad Alon8c513c72019-05-07 21:22:24 +0200695 }
696
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200697 if (worst_frame_) {
698 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
699 "dB", false);
700 }
701
702 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 15:08:16 +0200703 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titovea9798c2019-07-31 14:27:42 +0200704 decode_time_ms_, "ms");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200705 }
Yves Gerey0c67c802019-08-01 17:45:54 +0200706 dropped_frames_ += dropped_frames_diff;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200707 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
Artem Titovea9798c2019-07-31 14:27:42 +0200708 "count", false);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200709 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
710 "%", false);
711
712#if defined(WEBRTC_WIN)
713 // On Linux and Mac in Resident Set some unused pages may be counted.
714 // Therefore this metric will depend on order in which tests are run and
715 // will be flaky.
Artem Titovea9798c2019-07-31 14:27:42 +0200716 PrintResult("memory_usage", memory_usage_, "sizeInBytes");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200717#endif
718
719 // Saving only the worst frame for manual analysis. Intention here is to
720 // only detect video corruptions and not to track picture quality. Thus,
721 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 13:44:12 +0200722 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200723 std::string output_dir;
724 test::GetTestArtifactsDir(&output_dir);
725 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100726 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200727 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
728 test::JpegFrameWriter frame_writer(output_path);
729 RTC_CHECK(
730 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
731 }
732
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200733 if (audio_receive_stream_ != nullptr) {
Artem Titovea9798c2019-07-31 14:27:42 +0200734 PrintResult("audio_expand_rate", audio_expand_rate_, "unitless");
735 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "unitless");
736 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, "ms");
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200737 }
738
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200739 // Disable quality check for quick test, as quality checks may fail
740 // because too few samples were collected.
741 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200742 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
743 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200744 }
745}
746
747void VideoAnalyzer::PerformFrameComparison(
748 const VideoAnalyzer::FrameComparison& comparison) {
749 // Perform expensive psnr and ssim calculations while not holding lock.
750 double psnr = -1.0;
751 double ssim = -1.0;
752 if (comparison.reference && !comparison.dropped) {
753 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
754 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
755 }
756
757 rtc::CritScope crit(&comparison_lock_);
758
759 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
760 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
761 }
762
763 if (graph_data_output_file_) {
764 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
765 comparison.send_time_ms, comparison.recv_time_ms,
766 comparison.render_time_ms,
767 comparison.encoded_frame_size, psnr, ssim));
768 }
769 if (psnr >= 0.0)
770 psnr_.AddSample(psnr);
771 if (ssim >= 0.0)
772 ssim_.AddSample(ssim);
773
774 if (comparison.dropped) {
775 ++dropped_frames_;
776 return;
777 }
778 if (last_unfreeze_time_ms_ == 0)
779 last_unfreeze_time_ms_ = comparison.render_time_ms;
780 if (last_render_time_ != 0) {
781 const int64_t render_delta_ms =
782 comparison.render_time_ms - last_render_time_;
783 rendered_delta_.AddSample(render_delta_ms);
784 if (last_render_delta_ms_ != 0 &&
785 render_delta_ms - last_render_delta_ms_ > 150) {
786 time_between_freezes_.AddSample(last_render_time_ -
787 last_unfreeze_time_ms_);
788 last_unfreeze_time_ms_ = comparison.render_time_ms;
789 }
790 last_render_delta_ms_ = render_delta_ms;
791 }
792 last_render_time_ = comparison.render_time_ms;
793
794 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
795 if (comparison.recv_time_ms > 0) {
796 // If recv_time_ms == 0, this frame consisted of a packets which were all
797 // lost in the transport. Since we were able to render the frame, however,
798 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
799 // happens internally in Call, and we can therefore here not know which
800 // FEC packets that protected the lost media packets. Consequently, we
801 // were not able to record a meaningful recv_time_ms. We therefore skip
802 // this sample.
803 //
804 // The reasoning above does not hold for ULPFEC and RTX, as for those
805 // strategies the timestamp of the received packets is set to the
806 // timestamp of the protected/retransmitted media packet. I.e., then
807 // recv_time_ms != 0, even though the media packets were lost.
808 receiver_time_.AddSample(comparison.render_time_ms -
809 comparison.recv_time_ms);
810 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
811 }
812 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
813 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
814}
815
816void VideoAnalyzer::PrintResult(const char* result_type,
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200817 Statistics stats,
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200818 const char* unit) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200819 test::PrintResultMeanAndError(
820 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
821 stats.GetStandardDeviation().value_or(0), unit, false);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200822}
823
Johannes Krona1b99b32019-07-30 15:08:16 +0200824void VideoAnalyzer::PrintResultWithExternalMean(const char* result_type,
825 double mean,
826 Statistics stats,
827 const char* unit) {
828 // If the true mean is different than the sample mean, the sample variance is
829 // too low. The sample variance given a known mean is obtained by adding the
830 // squared error between the true mean and the sample mean.
831 double compensated_variance =
832 stats.Size() > 0
833 ? *stats.GetVariance() + pow(mean - *stats.GetMean(), 2.0)
834 : 0.0;
835 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(), mean,
836 std::sqrt(compensated_variance), unit, false);
837}
838
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200839void VideoAnalyzer::PrintSamplesToFile() {
840 FILE* out = graph_data_output_file_;
841 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700842 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
843 return A.input_time_ms < B.input_time_ms;
844 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200845
846 fprintf(out, "%s\n", graph_title_.c_str());
Oleh Prypinb1686782019-08-02 09:36:47 +0200847 fprintf(out, "%" RTC_PRIuS "\n", samples_.size());
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200848 fprintf(out,
849 "dropped "
850 "input_time_ms "
851 "send_time_ms "
852 "recv_time_ms "
853 "render_time_ms "
854 "encoded_frame_size "
855 "psnr "
856 "ssim "
857 "encode_time_ms\n");
858 for (const Sample& sample : samples_) {
859 fprintf(out,
Oleh Prypinb1686782019-08-02 09:36:47 +0200860 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" RTC_PRIuS
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200861 " %lf %lf\n",
862 sample.dropped, sample.input_time_ms, sample.send_time_ms,
863 sample.recv_time_ms, sample.render_time_ms,
864 sample.encoded_frame_size, sample.psnr, sample.ssim);
865 }
866}
867
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200868void VideoAnalyzer::AddCapturedFrameForComparison(
869 const VideoFrame& video_frame) {
Yves Gerey0c67c802019-08-01 17:45:54 +0200870 bool must_capture = false;
871 {
872 rtc::CritScope lock(&comparison_lock_);
873 must_capture = captured_frames_ < frames_to_process_;
874 if (must_capture) {
875 ++captured_frames_;
876 }
877 }
878 if (must_capture) {
879 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100880 frames_.push_back(video_frame);
881 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200882}
883
884void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
885 const VideoFrame& render,
886 bool dropped,
887 int64_t render_time_ms) {
888 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
889 int64_t send_time_ms = send_times_[reference_timestamp];
890 send_times_.erase(reference_timestamp);
891 int64_t recv_time_ms = recv_times_[reference_timestamp];
892 recv_times_.erase(reference_timestamp);
893
894 // TODO(ivica): Make this work for > 2 streams.
895 auto it = encoded_frame_sizes_.find(reference_timestamp);
896 if (it == encoded_frame_sizes_.end())
897 it = encoded_frame_sizes_.find(reference_timestamp - 1);
898 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
899 if (it != encoded_frame_sizes_.end())
900 encoded_frame_sizes_.erase(it);
901
902 rtc::CritScope crit(&comparison_lock_);
903 if (comparisons_.size() < kMaxComparisons) {
904 comparisons_.push_back(FrameComparison(
905 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
906 recv_time_ms, render_time_ms, encoded_size));
907 } else {
908 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
909 send_time_ms, recv_time_ms,
910 render_time_ms, encoded_size));
911 }
912 comparison_available_event_.Set();
913}
914
915VideoAnalyzer::FrameComparison::FrameComparison()
916 : dropped(false),
917 input_time_ms(0),
918 send_time_ms(0),
919 recv_time_ms(0),
920 render_time_ms(0),
921 encoded_frame_size(0) {}
922
923VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
924 const VideoFrame& render,
925 bool dropped,
926 int64_t input_time_ms,
927 int64_t send_time_ms,
928 int64_t recv_time_ms,
929 int64_t render_time_ms,
930 size_t encoded_frame_size)
931 : reference(reference),
932 render(render),
933 dropped(dropped),
934 input_time_ms(input_time_ms),
935 send_time_ms(send_time_ms),
936 recv_time_ms(recv_time_ms),
937 render_time_ms(render_time_ms),
938 encoded_frame_size(encoded_frame_size) {}
939
940VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
941 int64_t input_time_ms,
942 int64_t send_time_ms,
943 int64_t recv_time_ms,
944 int64_t render_time_ms,
945 size_t encoded_frame_size)
946 : dropped(dropped),
947 input_time_ms(input_time_ms),
948 send_time_ms(send_time_ms),
949 recv_time_ms(recv_time_ms),
950 render_time_ms(render_time_ms),
951 encoded_frame_size(encoded_frame_size) {}
952
953VideoAnalyzer::Sample::Sample(int dropped,
954 int64_t input_time_ms,
955 int64_t send_time_ms,
956 int64_t recv_time_ms,
957 int64_t render_time_ms,
958 size_t encoded_frame_size,
959 double psnr,
960 double ssim)
961 : dropped(dropped),
962 input_time_ms(input_time_ms),
963 send_time_ms(send_time_ms),
964 recv_time_ms(recv_time_ms),
965 render_time_ms(render_time_ms),
966 encoded_frame_size(encoded_frame_size),
967 psnr(psnr),
968 ssim(ssim) {}
969
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200970VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
971 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100972 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100973 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200974 : analyzer_(analyzer),
975 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100976 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100977 clock_(clock),
978 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100979 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200980
981void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100982 VideoSourceInterface<VideoFrame>* video_source) {
983 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200984}
985
986void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
987 const VideoFrame& video_frame) {
988 VideoFrame copy = video_frame;
989 // Frames from the capturer does not have a rtp timestamp.
990 // Create one so it can be used for comparison.
991 RTC_DCHECK_EQ(0, video_frame.timestamp());
992 if (video_frame.ntp_time_ms() == 0)
993 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
994 copy.set_timestamp(copy.ntp_time_ms() * 90);
995 analyzer_->AddCapturedFrameForComparison(copy);
996 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100997 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100998 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200999 send_stream_input_->OnFrame(copy);
1000}
1001
1002void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1003 rtc::VideoSinkInterface<VideoFrame>* sink,
1004 const rtc::VideoSinkWants& wants) {
1005 {
1006 rtc::CritScope lock(&crit_);
1007 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1008 send_stream_input_ = sink;
1009 }
Niels Möller1c931c42018-12-18 16:08:11 +01001010 if (video_source_) {
1011 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001012 }
1013}
1014
1015void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1016 rtc::VideoSinkInterface<VideoFrame>* sink) {
1017 rtc::CritScope lock(&crit_);
1018 RTC_DCHECK(sink == send_stream_input_);
1019 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001020}
1021
1022} // namespace webrtc