blob: be4872681404d40b94012e1c871470e88ac3fafc [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,
69 test::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),
96 dropped_frames_(0),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010097 captured_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),
104 total_media_bytes_(0),
105 first_sending_time_(0),
106 last_sending_time_(0),
107 cpu_time_(0),
108 wallclock_time_(0),
109 avg_psnr_threshold_(avg_psnr_threshold),
110 avg_ssim_threshold_(avg_ssim_threshold),
111 is_quick_test_enabled_(is_quick_test_enabled),
Niels Möller4731f002019-05-03 09:34:24 +0200112 quit_(false),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200113 done_(true, false),
114 clock_(clock),
Artem Titovff7730d2019-04-02 13:46:53 +0200115 start_ms_(clock->TimeInMilliseconds()),
116 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200117 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
118
119 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
120 // so that we don't accidentally starve "real" worker threads (codec etc).
121 // Also, don't allocate more than kMaxComparisonThreads, even if there are
122 // spare cores.
123
124 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
125 RTC_DCHECK_GE(num_cores, 1);
126 static const uint32_t kMinCoresLeft = 4;
127 static const uint32_t kMaxComparisonThreads = 8;
128
129 if (num_cores <= kMinCoresLeft) {
130 num_cores = 1;
131 } else {
132 num_cores -= kMinCoresLeft;
133 num_cores = std::min(num_cores, kMaxComparisonThreads);
134 }
135
136 for (uint32_t i = 0; i < num_cores; ++i) {
137 rtc::PlatformThread* thread =
138 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
139 thread->Start();
140 comparison_thread_pool_.push_back(thread);
141 }
142
143 if (!rtp_dump_name.empty()) {
144 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
145 rtp_file_writer_.reset(test::RtpFileWriter::Create(
146 test::RtpFileWriter::kRtpDump, rtp_dump_name));
147 }
148}
149
150VideoAnalyzer::~VideoAnalyzer() {
Niels Möller4731f002019-05-03 09:34:24 +0200151 {
152 rtc::CritScope crit(&comparison_lock_);
153 quit_ = true;
154 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200155 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
156 thread->Stop();
157 delete thread;
158 }
159}
160
161void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
162 receiver_ = receiver;
163}
164
Niels Möller1c931c42018-12-18 16:08:11 +0100165void VideoAnalyzer::SetSource(
166 rtc::VideoSourceInterface<VideoFrame>* video_source,
167 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200168 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 16:08:11 +0100169 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200170 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 16:08:11 +0100171 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200172}
173
174void VideoAnalyzer::SetCall(Call* call) {
175 rtc::CritScope lock(&crit_);
176 RTC_DCHECK(!call_);
177 call_ = call;
178}
179
180void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
181 rtc::CritScope lock(&crit_);
182 RTC_DCHECK(!send_stream_);
183 send_stream_ = stream;
184}
185
186void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
187 rtc::CritScope lock(&crit_);
188 RTC_DCHECK(!receive_stream_);
189 receive_stream_ = stream;
190}
191
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200192void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
193 rtc::CritScope lock(&crit_);
194 RTC_CHECK(!audio_receive_stream_);
195 audio_receive_stream_ = recv_stream;
196}
197
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200198rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
199 return &captured_frame_forwarder_;
200}
201
202rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
203 return &captured_frame_forwarder_;
204}
205
206PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
207 MediaType media_type,
208 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 11:03:12 +0200209 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200210 // Ignore timestamps of RTCP packets. They're not synchronized with
211 // RTP packet timestamps and so they would confuse wrap_handler_.
212 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
Niels Möller70082872018-08-07 11:03:12 +0200213 return receiver_->DeliverPacket(media_type, std::move(packet),
214 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200215 }
216
217 if (rtp_file_writer_) {
218 test::RtpPacket p;
219 memcpy(p.data, packet.cdata(), packet.size());
220 p.length = packet.size();
221 p.original_length = packet.size();
222 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
223 rtp_file_writer_->WritePacket(&p);
224 }
225
226 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
227 RTPHeader header;
228 parser.Parse(&header);
229 if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
230 header.ssrc == rtx_ssrc_to_analyze_)) {
231 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
232 // (FlexFEC and media are sent on different SSRCs, which have different
233 // timestamps spaces.)
234 // Also ignore packets from wrong SSRC, but include retransmits.
235 rtc::CritScope lock(&crit_);
236 int64_t timestamp =
237 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100238 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200239 }
240
Niels Möller70082872018-08-07 11:03:12 +0200241 return receiver_->DeliverPacket(media_type, std::move(packet),
242 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200243}
244
245void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
246 rtc::CritScope lock(&crit_);
247 if (!first_encoded_timestamp_) {
248 while (frames_.front().timestamp() != video_frame.timestamp()) {
249 ++dropped_frames_before_first_encode_;
250 frames_.pop_front();
251 RTC_CHECK(!frames_.empty());
252 }
253 first_encoded_timestamp_ = video_frame.timestamp();
254 }
255}
256
Niels Möller88be9722018-10-10 10:58:52 +0200257void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200258 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200259 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
260 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200261 }
262}
263
264bool VideoAnalyzer::SendRtp(const uint8_t* packet,
265 size_t length,
266 const PacketOptions& options) {
267 RtpUtility::RtpHeaderParser parser(packet, length);
268 RTPHeader header;
269 parser.Parse(&header);
270
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100271 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200272
273 bool result = transport_->SendRtp(packet, length, options);
274 {
275 rtc::CritScope lock(&crit_);
276 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
277 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
278 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
279 }
280
281 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
282 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
283 // (FlexFEC and media are sent on different SSRCs, which have different
284 // timestamps spaces.)
285 // Also ignore packets from wrong SSRC and retransmits.
286 int64_t timestamp =
287 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
288 send_times_[timestamp] = current_time;
289
290 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
291 encoded_frame_sizes_[timestamp] +=
292 length - (header.headerLength + header.paddingLength);
293 total_media_bytes_ +=
294 length - (header.headerLength + header.paddingLength);
295 }
296 if (first_sending_time_ == 0)
297 first_sending_time_ = current_time;
298 last_sending_time_ = current_time;
299 }
300 }
301 return result;
302}
303
304bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
305 return transport_->SendRtcp(packet, length);
306}
307
308void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100309 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200310
311 rtc::CritScope lock(&crit_);
312
313 StartExcludingCpuThreadTime();
314
315 int64_t send_timestamp =
316 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
317
318 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
319 if (!last_rendered_frame_) {
320 // No previous frame rendered, this one was dropped after sending but
321 // before rendering.
322 ++dropped_frames_before_rendering_;
323 } else {
324 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
325 render_time_ms);
326 }
327 frames_.pop_front();
328 RTC_DCHECK(!frames_.empty());
329 }
330
331 VideoFrame reference_frame = frames_.front();
332 frames_.pop_front();
333 int64_t reference_timestamp =
334 wrap_handler_.Unwrap(reference_frame.timestamp());
335 if (send_timestamp == reference_timestamp - 1) {
336 // TODO(ivica): Make this work for > 2 streams.
337 // Look at RTPSender::BuildRTPHeader.
338 ++send_timestamp;
339 }
340 ASSERT_EQ(reference_timestamp, send_timestamp);
341
342 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
343
344 last_rendered_frame_ = video_frame;
345
346 StopExcludingCpuThreadTime();
347}
348
349void VideoAnalyzer::Wait() {
350 // Frame comparisons can be very expensive. Wait for test to be done, but
351 // at time-out check if frames_processed is going up. If so, give it more
352 // time, otherwise fail. Hopefully this will reduce test flakiness.
353
Artem Titovff7730d2019-04-02 13:46:53 +0200354 {
355 rtc::CritScope lock(&comparison_lock_);
356 stop_stats_poller_ = false;
357 stats_polling_task_id_ = task_queue_->PostDelayedTask(
358 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
359 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200360
361 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100362 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200363 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100364
365 while (!done_.Wait(kProbingIntervalMs)) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200366 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100367 int frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200368 {
369 rtc::CritScope crit(&comparison_lock_);
370 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100371 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200372 }
373
374 // Print some output so test infrastructure won't think we've crashed.
375 const char* kKeepAliveMessages[3] = {
376 "Uh, I'm-I'm not quite dead, sir.",
377 "Uh, I-I think uh, I could pull through, sir.",
378 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100379 if (++iteration % kKeepAliveIntervalIterations == 0) {
380 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
381 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200382
383 if (last_frames_processed == -1) {
384 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100385 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200386 continue;
387 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100388 if (frames_processed == last_frames_processed &&
389 last_frames_captured == frames_captured) {
390 if (frames_captured < frames_to_process_) {
391 EXPECT_GT(frames_processed, last_frames_processed)
392 << "Analyzer stalled while waiting for test to finish.";
393 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200394 done_.Set();
395 break;
396 }
397 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100398 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200399 }
400
401 if (iteration > 0)
402 printf("- Farewell, sweet Concorde!\n");
403
Artem Titovff7730d2019-04-02 13:46:53 +0200404 {
405 rtc::CritScope lock(&comparison_lock_);
406 stop_stats_poller_ = true;
407 task_queue_->CancelTask(stats_polling_task_id_);
408 }
409
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100410 PrintResults();
411 if (graph_data_output_file_)
412 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200413}
414
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200415void VideoAnalyzer::StartMeasuringCpuProcessTime() {
416 rtc::CritScope lock(&cpu_measurement_lock_);
417 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
418 wallclock_time_ -= rtc::SystemTimeNanos();
419}
420
421void VideoAnalyzer::StopMeasuringCpuProcessTime() {
422 rtc::CritScope lock(&cpu_measurement_lock_);
423 cpu_time_ += rtc::GetProcessCpuTimeNanos();
424 wallclock_time_ += rtc::SystemTimeNanos();
425}
426
427void VideoAnalyzer::StartExcludingCpuThreadTime() {
428 rtc::CritScope lock(&cpu_measurement_lock_);
429 cpu_time_ += rtc::GetThreadCpuTimeNanos();
430}
431
432void VideoAnalyzer::StopExcludingCpuThreadTime() {
433 rtc::CritScope lock(&cpu_measurement_lock_);
434 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
435}
436
437double VideoAnalyzer::GetCpuUsagePercent() {
438 rtc::CritScope lock(&cpu_measurement_lock_);
439 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
440}
441
442bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
443 const uint8_t* packet,
444 size_t length,
445 const RTPHeader& header) {
446 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
447 header.payloadType != test::CallTest::kPayloadTypeVP8) {
448 return true;
449 } else {
450 // Get VP8 and VP9 specific header to check layers indexes.
451 const uint8_t* payload = packet + header.headerLength;
452 const size_t payload_length = length - header.headerLength;
453 const size_t payload_data_length = payload_length - header.paddingLength;
454 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
455 std::unique_ptr<RtpDepacketizer> depacketizer(
456 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
457 RtpDepacketizer::ParsedPayload parsed_payload;
458 bool result =
459 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
460 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200461
462 int temporal_idx;
463 int spatial_idx;
464 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000465 temporal_idx = absl::get<RTPVideoHeaderVP8>(
466 parsed_payload.video_header().video_type_header)
467 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200468 spatial_idx = kNoTemporalIdx;
469 } else {
470 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
471 parsed_payload.video_header().video_type_header);
472 temporal_idx = vp9_header.temporal_idx;
473 spatial_idx = vp9_header.spatial_idx;
474 }
475
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200476 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
477 temporal_idx <= selected_tl_) &&
478 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
479 spatial_idx <= selected_sl_);
480 }
481}
482
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200483void VideoAnalyzer::PollStats() {
Artem Titovff7730d2019-04-02 13:46:53 +0200484 rtc::CritScope crit(&comparison_lock_);
485 if (stop_stats_poller_) {
486 return;
Artem Titovf537da62019-04-02 13:46:53 +0200487 }
Artem Titovff7730d2019-04-02 13:46:53 +0200488
489 Call::Stats call_stats = call_->GetStats();
490 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
491
492 VideoSendStream::Stats send_stats = send_stream_->GetStats();
493 // It's not certain that we yet have estimates for any of these stats.
494 // Check that they are positive before mixing them in.
495 if (send_stats.encode_frame_rate > 0)
496 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
497 if (send_stats.avg_encode_time_ms > 0)
498 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
499 if (send_stats.encode_usage_percent > 0)
500 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
501 if (send_stats.media_bitrate_bps > 0)
502 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
503 size_t fec_bytes = 0;
504 for (const auto& kv : send_stats.substreams) {
505 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
506 kv.second.rtp_stats.fec.padding_bytes;
507 }
508 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
509 last_fec_bytes_ = fec_bytes;
510
511 if (receive_stream_ != nullptr) {
512 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
Johannes Krona1b99b32019-07-30 15:08:16 +0200513 // |total_decode_time_ms| gives a good estimate of the mean decode time,
514 // |decode_ms| is used to keep track of the standard deviation.
515 if (receive_stats.frames_decoded > 0)
516 mean_decode_time_ms_ =
517 static_cast<double>(receive_stats.total_decode_time_ms) /
518 receive_stats.frames_decoded;
Artem Titovff7730d2019-04-02 13:46:53 +0200519 if (receive_stats.decode_ms > 0)
520 decode_time_ms_.AddSample(receive_stats.decode_ms);
521 if (receive_stats.max_decode_ms > 0)
522 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
523 if (receive_stats.width > 0 && receive_stats.height > 0) {
524 pixels_.AddSample(receive_stats.width * receive_stats.height);
525 }
Elad Alon58e06572019-05-08 15:34:24 +0200526
527 // |frames_decoded| and |frames_rendered| are used because they are more
528 // accurate than |decode_frame_rate| and |render_frame_rate|.
529 // The latter two are calculated on a momentary basis.
530 const double total_frames_duration_sec_double =
531 static_cast<double>(receive_stats.total_frames_duration_ms) / 1000.0;
532 if (total_frames_duration_sec_double > 0) {
533 decode_frame_rate_ = static_cast<double>(receive_stats.frames_decoded) /
534 total_frames_duration_sec_double;
535 render_frame_rate_ = static_cast<double>(receive_stats.frames_rendered) /
536 total_frames_duration_sec_double;
537 }
538
539 // Freeze metrics.
Elad Alon8c513c72019-05-07 21:22:24 +0200540 freeze_count_ = receive_stats.freeze_count;
541 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
542 total_frames_duration_ms_ = receive_stats.total_frames_duration_ms;
543 sum_squared_frame_durations_ = receive_stats.sum_squared_frame_durations;
Artem Titovff7730d2019-04-02 13:46:53 +0200544 }
545
546 if (audio_receive_stream_ != nullptr) {
547 AudioReceiveStream::Stats receive_stats = audio_receive_stream_->GetStats();
548 audio_expand_rate_.AddSample(receive_stats.expand_rate);
549 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
550 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
551 }
552
553 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
554
555 stats_polling_task_id_ = task_queue_->PostDelayedTask(
556 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200557}
558
Niels Möller4731f002019-05-03 09:34:24 +0200559void VideoAnalyzer::FrameComparisonThread(void* obj) {
560 VideoAnalyzer* analyzer = static_cast<VideoAnalyzer*>(obj);
561 while (analyzer->CompareFrames()) {
562 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200563}
564
565bool VideoAnalyzer::CompareFrames() {
566 if (AllFramesRecorded())
567 return false;
568
569 FrameComparison comparison;
570
571 if (!PopComparison(&comparison)) {
572 // Wait until new comparison task is available, or test is done.
573 // If done, wake up remaining threads waiting.
574 comparison_available_event_.Wait(1000);
575 if (AllFramesRecorded()) {
576 comparison_available_event_.Set();
577 return false;
578 }
579 return true; // Try again.
580 }
581
582 StartExcludingCpuThreadTime();
583
584 PerformFrameComparison(comparison);
585
586 StopExcludingCpuThreadTime();
587
588 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200589 done_.Set();
590 comparison_available_event_.Set();
591 return false;
592 }
593
594 return true;
595}
596
597bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
598 rtc::CritScope crit(&comparison_lock_);
599 // If AllFramesRecorded() is true, it means we have already popped
600 // frames_to_process_ frames from comparisons_, so there is no more work
601 // for this thread to be done. frames_processed_ might still be lower if
602 // all comparisons are not done, but those frames are currently being
603 // worked on by other threads.
604 if (comparisons_.empty() || AllFramesRecorded())
605 return false;
606
607 *comparison = comparisons_.front();
608 comparisons_.pop_front();
609
610 FrameRecorded();
611 return true;
612}
613
614void VideoAnalyzer::FrameRecorded() {
615 rtc::CritScope crit(&comparison_lock_);
616 ++frames_recorded_;
617}
618
619bool VideoAnalyzer::AllFramesRecorded() {
620 rtc::CritScope crit(&comparison_lock_);
Niels Möller4731f002019-05-03 09:34:24 +0200621 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
622 return frames_recorded_ == frames_to_process_ || quit_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200623}
624
625bool VideoAnalyzer::FrameProcessed() {
626 rtc::CritScope crit(&comparison_lock_);
627 ++frames_processed_;
628 assert(frames_processed_ <= frames_to_process_);
629 return frames_processed_ == frames_to_process_;
630}
631
632void VideoAnalyzer::PrintResults() {
633 StopMeasuringCpuProcessTime();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100634 int frames_left;
635 {
636 rtc::CritScope crit(&crit_);
637 frames_left = frames_.size();
638 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200639 rtc::CritScope crit(&comparison_lock_);
Artem Titovea9798c2019-07-31 14:27:42 +0200640 PrintResult("psnr", psnr_, "dB");
641 PrintResult("ssim", ssim_, "unitless");
642 PrintResult("sender_time", sender_time_, "ms");
643 PrintResult("receiver_time", receiver_time_, "ms");
644 PrintResult("network_time", network_time_, "ms");
645 PrintResult("total_delay_incl_network", end_to_end_, "ms");
646 PrintResult("time_between_rendered_frames", rendered_delta_, "ms");
647 PrintResult("encode_frame_rate", encode_frame_rate_, "fps");
648 PrintResult("encode_time", encode_time_ms_, "ms");
649 PrintResult("media_bitrate", media_bitrate_bps_, "bps");
650 PrintResult("fec_bitrate", fec_bitrate_bps_, "bps");
651 PrintResult("send_bandwidth", send_bandwidth_bps_, "bps");
652 PrintResult("pixels_per_frame", pixels_, "count");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200653
Elad Alon58e06572019-05-08 15:34:24 +0200654 test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
655 decode_frame_rate_, "fps", false);
656 test::PrintResult("render_frame_rate", "", test_label_.c_str(),
657 render_frame_rate_, "fps", false);
658
Elad Alon8c513c72019-05-07 21:22:24 +0200659 // 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 Titovea9798c2019-07-31 14:27:42 +0200665 PrintResult("time_between_freezes", time_between_freezes_, "ms");
Elad Alon8c513c72019-05-07 21:22:24 +0200666
667 const double freeze_count_double = static_cast<double>(freeze_count_);
668 const double total_freezes_duration_ms_double =
669 static_cast<double>(total_freezes_duration_ms_);
670 const double total_frames_duration_ms_double =
671 static_cast<double>(total_frames_duration_ms_);
672
673 if (total_frames_duration_ms_double > 0) {
674 test::PrintResult(
675 "freeze_duration_ratio", "", test_label_.c_str(),
Artem Titovea9798c2019-07-31 14:27:42 +0200676 total_freezes_duration_ms_double / total_frames_duration_ms_double,
677 "unitless", false);
Elad Alon8c513c72019-05-07 21:22:24 +0200678 RTC_DCHECK_LE(total_freezes_duration_ms_double,
679 total_frames_duration_ms_double);
680
681 constexpr double ms_per_minute = 60 * 1000;
682 const double total_frames_duration_min =
683 total_frames_duration_ms_double / ms_per_minute;
684 if (total_frames_duration_min > 0) {
685 test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
686 freeze_count_double / total_frames_duration_min,
Artem Titovea9798c2019-07-31 14:27:42 +0200687 "unitless", false);
Elad Alon8c513c72019-05-07 21:22:24 +0200688 }
689 }
690
Elad Alon133f7e72019-05-08 09:51:56 +0200691 test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
Elad Alon8c513c72019-05-07 21:22:24 +0200692 freeze_count_double > 0
693 ? total_freezes_duration_ms_double / freeze_count_double
694 : 0,
695 "ms", false);
696
697 if (1000 * sum_squared_frame_durations_ > 0) {
698 test::PrintResult(
699 "harmonic_frame_rate", "", test_label_.c_str(),
700 total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
Artem Titovea9798c2019-07-31 14:27:42 +0200701 "fps", false);
Elad Alon8c513c72019-05-07 21:22:24 +0200702 }
703
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200704 if (worst_frame_) {
705 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
706 "dB", false);
707 }
708
709 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 15:08:16 +0200710 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titovea9798c2019-07-31 14:27:42 +0200711 decode_time_ms_, "ms");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200712 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100713 dropped_frames_ += dropped_frames_before_first_encode_ +
714 dropped_frames_before_rendering_ + frames_left;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200715 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
Artem Titovea9798c2019-07-31 14:27:42 +0200716 "count", false);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200717 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
718 "%", false);
719
720#if defined(WEBRTC_WIN)
721 // On Linux and Mac in Resident Set some unused pages may be counted.
722 // Therefore this metric will depend on order in which tests are run and
723 // will be flaky.
Artem Titovea9798c2019-07-31 14:27:42 +0200724 PrintResult("memory_usage", memory_usage_, "sizeInBytes");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200725#endif
726
727 // Saving only the worst frame for manual analysis. Intention here is to
728 // only detect video corruptions and not to track picture quality. Thus,
729 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 13:44:12 +0200730 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200731 std::string output_dir;
732 test::GetTestArtifactsDir(&output_dir);
733 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100734 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200735 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
736 test::JpegFrameWriter frame_writer(output_path);
737 RTC_CHECK(
738 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
739 }
740
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200741 if (audio_receive_stream_ != nullptr) {
Artem Titovea9798c2019-07-31 14:27:42 +0200742 PrintResult("audio_expand_rate", audio_expand_rate_, "unitless");
743 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "unitless");
744 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, "ms");
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200745 }
746
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200747 // Disable quality check for quick test, as quality checks may fail
748 // because too few samples were collected.
749 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200750 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
751 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200752 }
753}
754
755void VideoAnalyzer::PerformFrameComparison(
756 const VideoAnalyzer::FrameComparison& comparison) {
757 // Perform expensive psnr and ssim calculations while not holding lock.
758 double psnr = -1.0;
759 double ssim = -1.0;
760 if (comparison.reference && !comparison.dropped) {
761 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
762 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
763 }
764
765 rtc::CritScope crit(&comparison_lock_);
766
767 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
768 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
769 }
770
771 if (graph_data_output_file_) {
772 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
773 comparison.send_time_ms, comparison.recv_time_ms,
774 comparison.render_time_ms,
775 comparison.encoded_frame_size, psnr, ssim));
776 }
777 if (psnr >= 0.0)
778 psnr_.AddSample(psnr);
779 if (ssim >= 0.0)
780 ssim_.AddSample(ssim);
781
782 if (comparison.dropped) {
783 ++dropped_frames_;
784 return;
785 }
786 if (last_unfreeze_time_ms_ == 0)
787 last_unfreeze_time_ms_ = comparison.render_time_ms;
788 if (last_render_time_ != 0) {
789 const int64_t render_delta_ms =
790 comparison.render_time_ms - last_render_time_;
791 rendered_delta_.AddSample(render_delta_ms);
792 if (last_render_delta_ms_ != 0 &&
793 render_delta_ms - last_render_delta_ms_ > 150) {
794 time_between_freezes_.AddSample(last_render_time_ -
795 last_unfreeze_time_ms_);
796 last_unfreeze_time_ms_ = comparison.render_time_ms;
797 }
798 last_render_delta_ms_ = render_delta_ms;
799 }
800 last_render_time_ = comparison.render_time_ms;
801
802 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
803 if (comparison.recv_time_ms > 0) {
804 // If recv_time_ms == 0, this frame consisted of a packets which were all
805 // lost in the transport. Since we were able to render the frame, however,
806 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
807 // happens internally in Call, and we can therefore here not know which
808 // FEC packets that protected the lost media packets. Consequently, we
809 // were not able to record a meaningful recv_time_ms. We therefore skip
810 // this sample.
811 //
812 // The reasoning above does not hold for ULPFEC and RTX, as for those
813 // strategies the timestamp of the received packets is set to the
814 // timestamp of the protected/retransmitted media packet. I.e., then
815 // recv_time_ms != 0, even though the media packets were lost.
816 receiver_time_.AddSample(comparison.render_time_ms -
817 comparison.recv_time_ms);
818 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
819 }
820 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
821 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
822}
823
824void VideoAnalyzer::PrintResult(const char* result_type,
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200825 Statistics stats,
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200826 const char* unit) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200827 test::PrintResultMeanAndError(
828 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
829 stats.GetStandardDeviation().value_or(0), unit, false);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200830}
831
Johannes Krona1b99b32019-07-30 15:08:16 +0200832void VideoAnalyzer::PrintResultWithExternalMean(const char* result_type,
833 double mean,
834 Statistics stats,
835 const char* unit) {
836 // If the true mean is different than the sample mean, the sample variance is
837 // too low. The sample variance given a known mean is obtained by adding the
838 // squared error between the true mean and the sample mean.
839 double compensated_variance =
840 stats.Size() > 0
841 ? *stats.GetVariance() + pow(mean - *stats.GetMean(), 2.0)
842 : 0.0;
843 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(), mean,
844 std::sqrt(compensated_variance), unit, false);
845}
846
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200847void VideoAnalyzer::PrintSamplesToFile() {
848 FILE* out = graph_data_output_file_;
849 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700850 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
851 return A.input_time_ms < B.input_time_ms;
852 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200853
854 fprintf(out, "%s\n", graph_title_.c_str());
855 fprintf(out, "%" PRIuS "\n", samples_.size());
856 fprintf(out,
857 "dropped "
858 "input_time_ms "
859 "send_time_ms "
860 "recv_time_ms "
861 "render_time_ms "
862 "encoded_frame_size "
863 "psnr "
864 "ssim "
865 "encode_time_ms\n");
866 for (const Sample& sample : samples_) {
867 fprintf(out,
868 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
869 " %lf %lf\n",
870 sample.dropped, sample.input_time_ms, sample.send_time_ms,
871 sample.recv_time_ms, sample.render_time_ms,
872 sample.encoded_frame_size, sample.psnr, sample.ssim);
873 }
874}
875
876double VideoAnalyzer::GetAverageMediaBitrateBps() {
877 if (last_sending_time_ == first_sending_time_) {
878 return 0;
879 } else {
880 return static_cast<double>(total_media_bytes_) * 8 /
881 (last_sending_time_ - first_sending_time_) *
882 rtc::kNumMillisecsPerSec;
883 }
884}
885
886void VideoAnalyzer::AddCapturedFrameForComparison(
887 const VideoFrame& video_frame) {
888 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100889 if (captured_frames_ < frames_to_process_) {
890 ++captured_frames_;
891 frames_.push_back(video_frame);
892 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200893}
894
895void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
896 const VideoFrame& render,
897 bool dropped,
898 int64_t render_time_ms) {
899 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
900 int64_t send_time_ms = send_times_[reference_timestamp];
901 send_times_.erase(reference_timestamp);
902 int64_t recv_time_ms = recv_times_[reference_timestamp];
903 recv_times_.erase(reference_timestamp);
904
905 // TODO(ivica): Make this work for > 2 streams.
906 auto it = encoded_frame_sizes_.find(reference_timestamp);
907 if (it == encoded_frame_sizes_.end())
908 it = encoded_frame_sizes_.find(reference_timestamp - 1);
909 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
910 if (it != encoded_frame_sizes_.end())
911 encoded_frame_sizes_.erase(it);
912
913 rtc::CritScope crit(&comparison_lock_);
914 if (comparisons_.size() < kMaxComparisons) {
915 comparisons_.push_back(FrameComparison(
916 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
917 recv_time_ms, render_time_ms, encoded_size));
918 } else {
919 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
920 send_time_ms, recv_time_ms,
921 render_time_ms, encoded_size));
922 }
923 comparison_available_event_.Set();
924}
925
926VideoAnalyzer::FrameComparison::FrameComparison()
927 : dropped(false),
928 input_time_ms(0),
929 send_time_ms(0),
930 recv_time_ms(0),
931 render_time_ms(0),
932 encoded_frame_size(0) {}
933
934VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
935 const VideoFrame& render,
936 bool dropped,
937 int64_t input_time_ms,
938 int64_t send_time_ms,
939 int64_t recv_time_ms,
940 int64_t render_time_ms,
941 size_t encoded_frame_size)
942 : reference(reference),
943 render(render),
944 dropped(dropped),
945 input_time_ms(input_time_ms),
946 send_time_ms(send_time_ms),
947 recv_time_ms(recv_time_ms),
948 render_time_ms(render_time_ms),
949 encoded_frame_size(encoded_frame_size) {}
950
951VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
952 int64_t input_time_ms,
953 int64_t send_time_ms,
954 int64_t recv_time_ms,
955 int64_t render_time_ms,
956 size_t encoded_frame_size)
957 : dropped(dropped),
958 input_time_ms(input_time_ms),
959 send_time_ms(send_time_ms),
960 recv_time_ms(recv_time_ms),
961 render_time_ms(render_time_ms),
962 encoded_frame_size(encoded_frame_size) {}
963
964VideoAnalyzer::Sample::Sample(int dropped,
965 int64_t input_time_ms,
966 int64_t send_time_ms,
967 int64_t recv_time_ms,
968 int64_t render_time_ms,
969 size_t encoded_frame_size,
970 double psnr,
971 double ssim)
972 : dropped(dropped),
973 input_time_ms(input_time_ms),
974 send_time_ms(send_time_ms),
975 recv_time_ms(recv_time_ms),
976 render_time_ms(render_time_ms),
977 encoded_frame_size(encoded_frame_size),
978 psnr(psnr),
979 ssim(ssim) {}
980
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200981VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
982 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100983 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100984 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200985 : analyzer_(analyzer),
986 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100987 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100988 clock_(clock),
989 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100990 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200991
992void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100993 VideoSourceInterface<VideoFrame>* video_source) {
994 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200995}
996
997void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
998 const VideoFrame& video_frame) {
999 VideoFrame copy = video_frame;
1000 // Frames from the capturer does not have a rtp timestamp.
1001 // Create one so it can be used for comparison.
1002 RTC_DCHECK_EQ(0, video_frame.timestamp());
1003 if (video_frame.ntp_time_ms() == 0)
1004 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
1005 copy.set_timestamp(copy.ntp_time_ms() * 90);
1006 analyzer_->AddCapturedFrameForComparison(copy);
1007 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +01001008 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +01001009 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001010 send_stream_input_->OnFrame(copy);
1011}
1012
1013void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1014 rtc::VideoSinkInterface<VideoFrame>* sink,
1015 const rtc::VideoSinkWants& wants) {
1016 {
1017 rtc::CritScope lock(&crit_);
1018 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1019 send_stream_input_ = sink;
1020 }
Niels Möller1c931c42018-12-18 16:08:11 +01001021 if (video_source_) {
1022 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001023 }
1024}
1025
1026void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1027 rtc::VideoSinkInterface<VideoFrame>* sink) {
1028 rtc::CritScope lock(&crit_);
1029 RTC_DCHECK(sink == send_stream_input_);
1030 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001031}
1032
1033} // namespace webrtc