blob: 0430faa5ddc9cd9cf7aeac72ad501f4e5ed8eef1 [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() {
Artem Titov82ce3842019-09-23 17:55:52 +0200625 using ::webrtc::test::ImproveDirection;
626
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200627 StopMeasuringCpuProcessTime();
Yves Gerey0c67c802019-08-01 17:45:54 +0200628 int dropped_frames_diff;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100629 {
630 rtc::CritScope crit(&crit_);
Yves Gerey0c67c802019-08-01 17:45:54 +0200631 dropped_frames_diff = dropped_frames_before_first_encode_ +
632 dropped_frames_before_rendering_ + frames_.size();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100633 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200634 rtc::CritScope crit(&comparison_lock_);
Artem Titov82ce3842019-09-23 17:55:52 +0200635 PrintResult("psnr", psnr_, "dB", ImproveDirection::kBiggerIsBetter);
636 PrintResult("ssim", ssim_, "unitless", ImproveDirection::kBiggerIsBetter);
637 PrintResult("sender_time", sender_time_, "ms",
638 ImproveDirection::kSmallerIsBetter);
639 PrintResult("receiver_time", receiver_time_, "ms",
640 ImproveDirection::kSmallerIsBetter);
641 PrintResult("network_time", network_time_, "ms",
642 ImproveDirection::kSmallerIsBetter);
643 PrintResult("total_delay_incl_network", end_to_end_, "ms",
644 ImproveDirection::kSmallerIsBetter);
645 PrintResult("time_between_rendered_frames", rendered_delta_, "ms",
646 ImproveDirection::kSmallerIsBetter);
647 PrintResult("encode_frame_rate", encode_frame_rate_, "fps",
648 ImproveDirection::kBiggerIsBetter);
649 PrintResult("encode_time", encode_time_ms_, "ms",
650 ImproveDirection::kSmallerIsBetter);
651 PrintResult("media_bitrate", media_bitrate_bps_, "bps",
652 ImproveDirection::kNone);
653 PrintResult("fec_bitrate", fec_bitrate_bps_, "bps", ImproveDirection::kNone);
654 PrintResult("send_bandwidth", send_bandwidth_bps_, "bps",
655 ImproveDirection::kNone);
656 PrintResult("pixels_per_frame", pixels_, "count",
657 ImproveDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200658
Elad Alon58e06572019-05-08 15:34:24 +0200659 test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
Artem Titov82ce3842019-09-23 17:55:52 +0200660 decode_frame_rate_, "fps", false,
661 ImproveDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 15:34:24 +0200662 test::PrintResult("render_frame_rate", "", test_label_.c_str(),
Artem Titov82ce3842019-09-23 17:55:52 +0200663 render_frame_rate_, "fps", false,
664 ImproveDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 15:34:24 +0200665
Elad Alon8c513c72019-05-07 21:22:24 +0200666 // Record the time from the last freeze until the last rendered frame to
667 // ensure we cover the full timespan of the session. Otherwise the metric
668 // would penalize an early freeze followed by no freezes until the end.
669 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
670
671 // Freeze metrics.
Artem Titov82ce3842019-09-23 17:55:52 +0200672 PrintResult("time_between_freezes", time_between_freezes_, "ms",
673 ImproveDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200674
675 const double freeze_count_double = static_cast<double>(freeze_count_);
676 const double total_freezes_duration_ms_double =
677 static_cast<double>(total_freezes_duration_ms_);
678 const double total_frames_duration_ms_double =
679 static_cast<double>(total_frames_duration_ms_);
680
681 if (total_frames_duration_ms_double > 0) {
682 test::PrintResult(
683 "freeze_duration_ratio", "", test_label_.c_str(),
Artem Titovea9798c2019-07-31 14:27:42 +0200684 total_freezes_duration_ms_double / total_frames_duration_ms_double,
Artem Titov82ce3842019-09-23 17:55:52 +0200685 "unitless", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200686 RTC_DCHECK_LE(total_freezes_duration_ms_double,
687 total_frames_duration_ms_double);
688
689 constexpr double ms_per_minute = 60 * 1000;
690 const double total_frames_duration_min =
691 total_frames_duration_ms_double / ms_per_minute;
692 if (total_frames_duration_min > 0) {
693 test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
694 freeze_count_double / total_frames_duration_min,
Artem Titov82ce3842019-09-23 17:55:52 +0200695 "unitless", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200696 }
697 }
698
Elad Alon133f7e72019-05-08 09:51:56 +0200699 test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
Elad Alon8c513c72019-05-07 21:22:24 +0200700 freeze_count_double > 0
701 ? total_freezes_duration_ms_double / freeze_count_double
702 : 0,
Artem Titov82ce3842019-09-23 17:55:52 +0200703 "ms", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200704
705 if (1000 * sum_squared_frame_durations_ > 0) {
706 test::PrintResult(
707 "harmonic_frame_rate", "", test_label_.c_str(),
708 total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
Artem Titov82ce3842019-09-23 17:55:52 +0200709 "fps", false, ImproveDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200710 }
711
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200712 if (worst_frame_) {
713 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
Artem Titov82ce3842019-09-23 17:55:52 +0200714 "dB", false, ImproveDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200715 }
716
717 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 15:08:16 +0200718 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titov82ce3842019-09-23 17:55:52 +0200719 decode_time_ms_, "ms",
720 ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200721 }
Yves Gerey0c67c802019-08-01 17:45:54 +0200722 dropped_frames_ += dropped_frames_diff;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200723 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
Artem Titov82ce3842019-09-23 17:55:52 +0200724 "count", false, ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200725 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
Artem Titov82ce3842019-09-23 17:55:52 +0200726 "%", false, ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200727
728#if defined(WEBRTC_WIN)
729 // On Linux and Mac in Resident Set some unused pages may be counted.
730 // Therefore this metric will depend on order in which tests are run and
731 // will be flaky.
Artem Titov82ce3842019-09-23 17:55:52 +0200732 PrintResult("memory_usage", memory_usage_, "sizeInBytes",
733 ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200734#endif
735
736 // Saving only the worst frame for manual analysis. Intention here is to
737 // only detect video corruptions and not to track picture quality. Thus,
738 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 13:44:12 +0200739 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200740 std::string output_dir;
741 test::GetTestArtifactsDir(&output_dir);
742 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100743 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200744 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
745 test::JpegFrameWriter frame_writer(output_path);
746 RTC_CHECK(
747 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
748 }
749
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200750 if (audio_receive_stream_ != nullptr) {
Artem Titov82ce3842019-09-23 17:55:52 +0200751 PrintResult("audio_expand_rate", audio_expand_rate_, "unitless",
752 ImproveDirection::kSmallerIsBetter);
753 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "unitless",
754 ImproveDirection::kSmallerIsBetter);
755 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, "ms",
756 ImproveDirection::kNone);
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200757 }
758
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200759 // Disable quality check for quick test, as quality checks may fail
760 // because too few samples were collected.
761 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200762 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
763 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200764 }
765}
766
767void VideoAnalyzer::PerformFrameComparison(
768 const VideoAnalyzer::FrameComparison& comparison) {
769 // Perform expensive psnr and ssim calculations while not holding lock.
770 double psnr = -1.0;
771 double ssim = -1.0;
772 if (comparison.reference && !comparison.dropped) {
773 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
774 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
775 }
776
777 rtc::CritScope crit(&comparison_lock_);
778
779 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
780 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
781 }
782
783 if (graph_data_output_file_) {
784 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
785 comparison.send_time_ms, comparison.recv_time_ms,
786 comparison.render_time_ms,
787 comparison.encoded_frame_size, psnr, ssim));
788 }
789 if (psnr >= 0.0)
790 psnr_.AddSample(psnr);
791 if (ssim >= 0.0)
792 ssim_.AddSample(ssim);
793
794 if (comparison.dropped) {
795 ++dropped_frames_;
796 return;
797 }
798 if (last_unfreeze_time_ms_ == 0)
799 last_unfreeze_time_ms_ = comparison.render_time_ms;
800 if (last_render_time_ != 0) {
801 const int64_t render_delta_ms =
802 comparison.render_time_ms - last_render_time_;
803 rendered_delta_.AddSample(render_delta_ms);
804 if (last_render_delta_ms_ != 0 &&
805 render_delta_ms - last_render_delta_ms_ > 150) {
806 time_between_freezes_.AddSample(last_render_time_ -
807 last_unfreeze_time_ms_);
808 last_unfreeze_time_ms_ = comparison.render_time_ms;
809 }
810 last_render_delta_ms_ = render_delta_ms;
811 }
812 last_render_time_ = comparison.render_time_ms;
813
814 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
815 if (comparison.recv_time_ms > 0) {
816 // If recv_time_ms == 0, this frame consisted of a packets which were all
817 // lost in the transport. Since we were able to render the frame, however,
818 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
819 // happens internally in Call, and we can therefore here not know which
820 // FEC packets that protected the lost media packets. Consequently, we
821 // were not able to record a meaningful recv_time_ms. We therefore skip
822 // this sample.
823 //
824 // The reasoning above does not hold for ULPFEC and RTX, as for those
825 // strategies the timestamp of the received packets is set to the
826 // timestamp of the protected/retransmitted media packet. I.e., then
827 // recv_time_ms != 0, even though the media packets were lost.
828 receiver_time_.AddSample(comparison.render_time_ms -
829 comparison.recv_time_ms);
830 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
831 }
832 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
833 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
834}
835
Artem Titov82ce3842019-09-23 17:55:52 +0200836void VideoAnalyzer::PrintResult(
837 const char* result_type,
838 Statistics stats,
839 const char* unit,
840 webrtc::test::ImproveDirection improve_direction) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200841 test::PrintResultMeanAndError(
842 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
Artem Titov82ce3842019-09-23 17:55:52 +0200843 stats.GetStandardDeviation().value_or(0), unit, false, improve_direction);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200844}
845
Artem Titov82ce3842019-09-23 17:55:52 +0200846void VideoAnalyzer::PrintResultWithExternalMean(
847 const char* result_type,
848 double mean,
849 Statistics stats,
850 const char* unit,
851 webrtc::test::ImproveDirection improve_direction) {
Johannes Krona1b99b32019-07-30 15:08:16 +0200852 // If the true mean is different than the sample mean, the sample variance is
853 // too low. The sample variance given a known mean is obtained by adding the
854 // squared error between the true mean and the sample mean.
855 double compensated_variance =
856 stats.Size() > 0
857 ? *stats.GetVariance() + pow(mean - *stats.GetMean(), 2.0)
858 : 0.0;
859 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(), mean,
Artem Titov82ce3842019-09-23 17:55:52 +0200860 std::sqrt(compensated_variance), unit, false,
861 improve_direction);
Johannes Krona1b99b32019-07-30 15:08:16 +0200862}
863
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200864void VideoAnalyzer::PrintSamplesToFile() {
865 FILE* out = graph_data_output_file_;
866 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700867 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
868 return A.input_time_ms < B.input_time_ms;
869 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200870
871 fprintf(out, "%s\n", graph_title_.c_str());
Oleh Prypinb1686782019-08-02 09:36:47 +0200872 fprintf(out, "%" RTC_PRIuS "\n", samples_.size());
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200873 fprintf(out,
874 "dropped "
875 "input_time_ms "
876 "send_time_ms "
877 "recv_time_ms "
878 "render_time_ms "
879 "encoded_frame_size "
880 "psnr "
881 "ssim "
882 "encode_time_ms\n");
883 for (const Sample& sample : samples_) {
884 fprintf(out,
Oleh Prypinb1686782019-08-02 09:36:47 +0200885 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" RTC_PRIuS
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200886 " %lf %lf\n",
887 sample.dropped, sample.input_time_ms, sample.send_time_ms,
888 sample.recv_time_ms, sample.render_time_ms,
889 sample.encoded_frame_size, sample.psnr, sample.ssim);
890 }
891}
892
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200893void VideoAnalyzer::AddCapturedFrameForComparison(
894 const VideoFrame& video_frame) {
Yves Gerey0c67c802019-08-01 17:45:54 +0200895 bool must_capture = false;
896 {
897 rtc::CritScope lock(&comparison_lock_);
898 must_capture = captured_frames_ < frames_to_process_;
899 if (must_capture) {
900 ++captured_frames_;
901 }
902 }
903 if (must_capture) {
904 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100905 frames_.push_back(video_frame);
906 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200907}
908
909void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
910 const VideoFrame& render,
911 bool dropped,
912 int64_t render_time_ms) {
913 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
914 int64_t send_time_ms = send_times_[reference_timestamp];
915 send_times_.erase(reference_timestamp);
916 int64_t recv_time_ms = recv_times_[reference_timestamp];
917 recv_times_.erase(reference_timestamp);
918
919 // TODO(ivica): Make this work for > 2 streams.
920 auto it = encoded_frame_sizes_.find(reference_timestamp);
921 if (it == encoded_frame_sizes_.end())
922 it = encoded_frame_sizes_.find(reference_timestamp - 1);
923 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
924 if (it != encoded_frame_sizes_.end())
925 encoded_frame_sizes_.erase(it);
926
927 rtc::CritScope crit(&comparison_lock_);
928 if (comparisons_.size() < kMaxComparisons) {
929 comparisons_.push_back(FrameComparison(
930 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
931 recv_time_ms, render_time_ms, encoded_size));
932 } else {
933 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
934 send_time_ms, recv_time_ms,
935 render_time_ms, encoded_size));
936 }
937 comparison_available_event_.Set();
938}
939
940VideoAnalyzer::FrameComparison::FrameComparison()
941 : dropped(false),
942 input_time_ms(0),
943 send_time_ms(0),
944 recv_time_ms(0),
945 render_time_ms(0),
946 encoded_frame_size(0) {}
947
948VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
949 const VideoFrame& render,
950 bool dropped,
951 int64_t input_time_ms,
952 int64_t send_time_ms,
953 int64_t recv_time_ms,
954 int64_t render_time_ms,
955 size_t encoded_frame_size)
956 : reference(reference),
957 render(render),
958 dropped(dropped),
959 input_time_ms(input_time_ms),
960 send_time_ms(send_time_ms),
961 recv_time_ms(recv_time_ms),
962 render_time_ms(render_time_ms),
963 encoded_frame_size(encoded_frame_size) {}
964
965VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
966 int64_t input_time_ms,
967 int64_t send_time_ms,
968 int64_t recv_time_ms,
969 int64_t render_time_ms,
970 size_t encoded_frame_size)
971 : dropped(dropped),
972 input_time_ms(input_time_ms),
973 send_time_ms(send_time_ms),
974 recv_time_ms(recv_time_ms),
975 render_time_ms(render_time_ms),
976 encoded_frame_size(encoded_frame_size) {}
977
978VideoAnalyzer::Sample::Sample(int dropped,
979 int64_t input_time_ms,
980 int64_t send_time_ms,
981 int64_t recv_time_ms,
982 int64_t render_time_ms,
983 size_t encoded_frame_size,
984 double psnr,
985 double ssim)
986 : dropped(dropped),
987 input_time_ms(input_time_ms),
988 send_time_ms(send_time_ms),
989 recv_time_ms(recv_time_ms),
990 render_time_ms(render_time_ms),
991 encoded_frame_size(encoded_frame_size),
992 psnr(psnr),
993 ssim(ssim) {}
994
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200995VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
996 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100997 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100998 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200999 : analyzer_(analyzer),
1000 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +01001001 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +01001002 clock_(clock),
1003 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +01001004 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001005
1006void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +01001007 VideoSourceInterface<VideoFrame>* video_source) {
1008 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001009}
1010
1011void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
1012 const VideoFrame& video_frame) {
1013 VideoFrame copy = video_frame;
1014 // Frames from the capturer does not have a rtp timestamp.
1015 // Create one so it can be used for comparison.
1016 RTC_DCHECK_EQ(0, video_frame.timestamp());
1017 if (video_frame.ntp_time_ms() == 0)
1018 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
1019 copy.set_timestamp(copy.ntp_time_ms() * 90);
1020 analyzer_->AddCapturedFrameForComparison(copy);
1021 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +01001022 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +01001023 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001024 send_stream_input_->OnFrame(copy);
1025}
1026
1027void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1028 rtc::VideoSinkInterface<VideoFrame>* sink,
1029 const rtc::VideoSinkWants& wants) {
1030 {
1031 rtc::CritScope lock(&crit_);
1032 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1033 send_stream_input_ = sink;
1034 }
Niels Möller1c931c42018-12-18 16:08:11 +01001035 if (video_source_) {
1036 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001037 }
1038}
1039
1040void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1041 rtc::VideoSinkInterface<VideoFrame>* sink) {
1042 rtc::CritScope lock(&crit_);
1043 RTC_DCHECK(sink == send_stream_input_);
1044 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001045}
1046
1047} // namespace webrtc