blob: 018ec8b45854c9bb6ec297c7d622af889e20c9f4 [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"
Danil Chapovalov9cd53b42019-10-21 13:36:59 +020024#include "rtc_base/task_queue_for_test.h"
25#include "rtc_base/task_utils/repeating_task.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020026#include "system_wrappers/include/cpu_info.h"
27#include "test/call_test.h"
Steve Anton10542f22019-01-11 09:11:00 -080028#include "test/testsupport/file_utils.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020029#include "test/testsupport/frame_writer.h"
30#include "test/testsupport/perf_test.h"
31#include "test/testsupport/test_artifacts.h"
32
Mirko Bonadei2ab97f62019-07-18 13:44:12 +020033ABSL_FLAG(bool,
34 save_worst_frame,
35 false,
36 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
37 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 12:57:37 +020038
39namespace webrtc {
40namespace {
Danil Chapovalov9cd53b42019-10-21 13:36:59 +020041constexpr TimeDelta kSendStatsPollingInterval = TimeDelta::Seconds<1>();
Sebastian Janssond4c5d632018-07-10 12:57:37 +020042constexpr size_t kMaxComparisons = 10;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010043// How often is keep alive message printed.
44constexpr int kKeepAliveIntervalSeconds = 30;
45// Interval between checking that the test is over.
46constexpr int kProbingIntervalMs = 500;
47constexpr int kKeepAliveIntervalIterations =
48 kKeepAliveIntervalSeconds * 1000 / kProbingIntervalMs;
Sebastian Janssond4c5d632018-07-10 12:57:37 +020049
50bool IsFlexfec(int payload_type) {
51 return payload_type == test::CallTest::kFlexfecPayloadType;
52}
53} // namespace
54
Danil Chapovalov9cd53b42019-10-21 13:36:59 +020055VideoAnalyzer::VideoAnalyzer(test::LayerFilteringTransport* transport,
56 const std::string& test_label,
57 double avg_psnr_threshold,
58 double avg_ssim_threshold,
59 int duration_frames,
60 FILE* graph_data_output_file,
61 const std::string& graph_title,
62 uint32_t ssrc_to_analyze,
63 uint32_t rtx_ssrc_to_analyze,
64 size_t selected_stream,
65 int selected_sl,
66 int selected_tl,
67 bool is_quick_test_enabled,
68 Clock* clock,
69 std::string rtp_dump_name,
70 TaskQueueBase* task_queue)
Sebastian Janssond4c5d632018-07-10 12:57:37 +020071 : transport_(transport),
72 receiver_(nullptr),
73 call_(nullptr),
74 send_stream_(nullptr),
75 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 14:10:56 +020076 audio_receive_stream_(nullptr),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +010077 captured_frame_forwarder_(this, clock, duration_frames),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020078 test_label_(test_label),
79 graph_data_output_file_(graph_data_output_file),
80 graph_title_(graph_title),
81 ssrc_to_analyze_(ssrc_to_analyze),
82 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
83 selected_stream_(selected_stream),
84 selected_sl_(selected_sl),
85 selected_tl_(selected_tl),
Johannes Krona1b99b32019-07-30 15:08:16 +020086 mean_decode_time_ms_(0.0),
Elad Alon8c513c72019-05-07 21:22:24 +020087 freeze_count_(0),
88 total_freezes_duration_ms_(0),
89 total_frames_duration_ms_(0),
90 sum_squared_frame_durations_(0),
Elad Alon58e06572019-05-08 15:34:24 +020091 decode_frame_rate_(0),
92 render_frame_rate_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020093 last_fec_bytes_(0),
94 frames_to_process_(duration_frames),
95 frames_recorded_(0),
96 frames_processed_(0),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010097 captured_frames_(0),
Yves Gerey0c67c802019-08-01 17:45:54 +020098 dropped_frames_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020099 dropped_frames_before_first_encode_(0),
100 dropped_frames_before_rendering_(0),
101 last_render_time_(0),
102 last_render_delta_ms_(0),
103 last_unfreeze_time_ms_(0),
104 rtp_timestamp_delta_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200105 cpu_time_(0),
106 wallclock_time_(0),
107 avg_psnr_threshold_(avg_psnr_threshold),
108 avg_ssim_threshold_(avg_ssim_threshold),
109 is_quick_test_enabled_(is_quick_test_enabled),
Niels Möller4731f002019-05-03 09:34:24 +0200110 quit_(false),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200111 done_(true, false),
112 clock_(clock),
Artem Titovff7730d2019-04-02 13:46:53 +0200113 start_ms_(clock->TimeInMilliseconds()),
114 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200115 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
116
117 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
118 // so that we don't accidentally starve "real" worker threads (codec etc).
119 // Also, don't allocate more than kMaxComparisonThreads, even if there are
120 // spare cores.
121
122 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
123 RTC_DCHECK_GE(num_cores, 1);
124 static const uint32_t kMinCoresLeft = 4;
125 static const uint32_t kMaxComparisonThreads = 8;
126
127 if (num_cores <= kMinCoresLeft) {
128 num_cores = 1;
129 } else {
130 num_cores -= kMinCoresLeft;
131 num_cores = std::min(num_cores, kMaxComparisonThreads);
132 }
133
134 for (uint32_t i = 0; i < num_cores; ++i) {
135 rtc::PlatformThread* thread =
136 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
137 thread->Start();
138 comparison_thread_pool_.push_back(thread);
139 }
140
141 if (!rtp_dump_name.empty()) {
142 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
143 rtp_file_writer_.reset(test::RtpFileWriter::Create(
144 test::RtpFileWriter::kRtpDump, rtp_dump_name));
145 }
146}
147
148VideoAnalyzer::~VideoAnalyzer() {
Niels Möller4731f002019-05-03 09:34:24 +0200149 {
150 rtc::CritScope crit(&comparison_lock_);
151 quit_ = true;
152 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200153 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
154 thread->Stop();
155 delete thread;
156 }
157}
158
159void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
160 receiver_ = receiver;
161}
162
Niels Möller1c931c42018-12-18 16:08:11 +0100163void VideoAnalyzer::SetSource(
164 rtc::VideoSourceInterface<VideoFrame>* video_source,
165 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200166 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 16:08:11 +0100167 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200168 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 16:08:11 +0100169 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200170}
171
172void VideoAnalyzer::SetCall(Call* call) {
173 rtc::CritScope lock(&crit_);
174 RTC_DCHECK(!call_);
175 call_ = call;
176}
177
178void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
179 rtc::CritScope lock(&crit_);
180 RTC_DCHECK(!send_stream_);
181 send_stream_ = stream;
182}
183
184void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
185 rtc::CritScope lock(&crit_);
186 RTC_DCHECK(!receive_stream_);
187 receive_stream_ = stream;
188}
189
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200190void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
191 rtc::CritScope lock(&crit_);
192 RTC_CHECK(!audio_receive_stream_);
193 audio_receive_stream_ = recv_stream;
194}
195
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200196rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
197 return &captured_frame_forwarder_;
198}
199
200rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
201 return &captured_frame_forwarder_;
202}
203
204PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
205 MediaType media_type,
206 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 11:03:12 +0200207 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200208 // Ignore timestamps of RTCP packets. They're not synchronized with
209 // RTP packet timestamps and so they would confuse wrap_handler_.
210 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
Niels Möller70082872018-08-07 11:03:12 +0200211 return receiver_->DeliverPacket(media_type, std::move(packet),
212 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200213 }
214
215 if (rtp_file_writer_) {
216 test::RtpPacket p;
217 memcpy(p.data, packet.cdata(), packet.size());
218 p.length = packet.size();
219 p.original_length = packet.size();
220 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
221 rtp_file_writer_->WritePacket(&p);
222 }
223
224 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
225 RTPHeader header;
226 parser.Parse(&header);
227 if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
228 header.ssrc == rtx_ssrc_to_analyze_)) {
229 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
230 // (FlexFEC and media are sent on different SSRCs, which have different
231 // timestamps spaces.)
232 // Also ignore packets from wrong SSRC, but include retransmits.
233 rtc::CritScope lock(&crit_);
234 int64_t timestamp =
235 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100236 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200237 }
238
Niels Möller70082872018-08-07 11:03:12 +0200239 return receiver_->DeliverPacket(media_type, std::move(packet),
240 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200241}
242
243void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
244 rtc::CritScope lock(&crit_);
245 if (!first_encoded_timestamp_) {
246 while (frames_.front().timestamp() != video_frame.timestamp()) {
247 ++dropped_frames_before_first_encode_;
248 frames_.pop_front();
249 RTC_CHECK(!frames_.empty());
250 }
251 first_encoded_timestamp_ = video_frame.timestamp();
252 }
253}
254
Niels Möller88be9722018-10-10 10:58:52 +0200255void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200256 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200257 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
258 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200259 }
260}
261
262bool VideoAnalyzer::SendRtp(const uint8_t* packet,
263 size_t length,
264 const PacketOptions& options) {
265 RtpUtility::RtpHeaderParser parser(packet, length);
266 RTPHeader header;
267 parser.Parse(&header);
268
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100269 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200270
271 bool result = transport_->SendRtp(packet, length, options);
272 {
273 rtc::CritScope lock(&crit_);
274 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
275 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
276 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
277 }
278
279 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
280 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
281 // (FlexFEC and media are sent on different SSRCs, which have different
282 // timestamps spaces.)
283 // Also ignore packets from wrong SSRC and retransmits.
284 int64_t timestamp =
285 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
286 send_times_[timestamp] = current_time;
287
288 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
289 encoded_frame_sizes_[timestamp] +=
290 length - (header.headerLength + header.paddingLength);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200291 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200292 }
293 }
294 return result;
295}
296
297bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
298 return transport_->SendRtcp(packet, length);
299}
300
301void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100302 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200303
304 rtc::CritScope lock(&crit_);
305
306 StartExcludingCpuThreadTime();
307
308 int64_t send_timestamp =
309 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
310
311 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
312 if (!last_rendered_frame_) {
313 // No previous frame rendered, this one was dropped after sending but
314 // before rendering.
315 ++dropped_frames_before_rendering_;
316 } else {
317 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
318 render_time_ms);
319 }
320 frames_.pop_front();
321 RTC_DCHECK(!frames_.empty());
322 }
323
324 VideoFrame reference_frame = frames_.front();
325 frames_.pop_front();
326 int64_t reference_timestamp =
327 wrap_handler_.Unwrap(reference_frame.timestamp());
328 if (send_timestamp == reference_timestamp - 1) {
329 // TODO(ivica): Make this work for > 2 streams.
330 // Look at RTPSender::BuildRTPHeader.
331 ++send_timestamp;
332 }
333 ASSERT_EQ(reference_timestamp, send_timestamp);
334
335 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
336
337 last_rendered_frame_ = video_frame;
338
339 StopExcludingCpuThreadTime();
340}
341
342void VideoAnalyzer::Wait() {
343 // Frame comparisons can be very expensive. Wait for test to be done, but
344 // at time-out check if frames_processed is going up. If so, give it more
345 // time, otherwise fail. Hopefully this will reduce test flakiness.
346
Danil Chapovalov9cd53b42019-10-21 13:36:59 +0200347 RepeatingTaskHandle stats_polling_task = RepeatingTaskHandle::DelayedStart(
348 task_queue_, kSendStatsPollingInterval, [this] {
349 PollStats();
350 return kSendStatsPollingInterval;
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
Danil Chapovalov9cd53b42019-10-21 13:36:59 +0200396 SendTask(RTC_FROM_HERE, task_queue_, [&] { stats_polling_task.Stop(); });
Artem Titovff7730d2019-04-02 13:46:53 +0200397
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100398 PrintResults();
399 if (graph_data_output_file_)
400 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200401}
402
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200403void VideoAnalyzer::StartMeasuringCpuProcessTime() {
404 rtc::CritScope lock(&cpu_measurement_lock_);
405 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
406 wallclock_time_ -= rtc::SystemTimeNanos();
407}
408
409void VideoAnalyzer::StopMeasuringCpuProcessTime() {
410 rtc::CritScope lock(&cpu_measurement_lock_);
411 cpu_time_ += rtc::GetProcessCpuTimeNanos();
412 wallclock_time_ += rtc::SystemTimeNanos();
413}
414
415void VideoAnalyzer::StartExcludingCpuThreadTime() {
416 rtc::CritScope lock(&cpu_measurement_lock_);
417 cpu_time_ += rtc::GetThreadCpuTimeNanos();
418}
419
420void VideoAnalyzer::StopExcludingCpuThreadTime() {
421 rtc::CritScope lock(&cpu_measurement_lock_);
422 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
423}
424
425double VideoAnalyzer::GetCpuUsagePercent() {
426 rtc::CritScope lock(&cpu_measurement_lock_);
427 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
428}
429
430bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
431 const uint8_t* packet,
432 size_t length,
433 const RTPHeader& header) {
434 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
435 header.payloadType != test::CallTest::kPayloadTypeVP8) {
436 return true;
437 } else {
438 // Get VP8 and VP9 specific header to check layers indexes.
439 const uint8_t* payload = packet + header.headerLength;
440 const size_t payload_length = length - header.headerLength;
441 const size_t payload_data_length = payload_length - header.paddingLength;
442 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
443 std::unique_ptr<RtpDepacketizer> depacketizer(
444 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
445 RtpDepacketizer::ParsedPayload parsed_payload;
446 bool result =
447 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
448 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200449
450 int temporal_idx;
451 int spatial_idx;
452 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000453 temporal_idx = absl::get<RTPVideoHeaderVP8>(
454 parsed_payload.video_header().video_type_header)
455 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200456 spatial_idx = kNoTemporalIdx;
457 } else {
458 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
459 parsed_payload.video_header().video_type_header);
460 temporal_idx = vp9_header.temporal_idx;
461 spatial_idx = vp9_header.spatial_idx;
462 }
463
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200464 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
465 temporal_idx <= selected_tl_) &&
466 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
467 spatial_idx <= selected_sl_);
468 }
469}
470
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200471void VideoAnalyzer::PollStats() {
Artem Titovff7730d2019-04-02 13:46:53 +0200472 rtc::CritScope crit(&comparison_lock_);
Artem Titovff7730d2019-04-02 13:46:53 +0200473
474 Call::Stats call_stats = call_->GetStats();
475 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
476
477 VideoSendStream::Stats send_stats = send_stream_->GetStats();
478 // It's not certain that we yet have estimates for any of these stats.
479 // Check that they are positive before mixing them in.
480 if (send_stats.encode_frame_rate > 0)
481 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
482 if (send_stats.avg_encode_time_ms > 0)
483 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
484 if (send_stats.encode_usage_percent > 0)
485 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
486 if (send_stats.media_bitrate_bps > 0)
487 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
488 size_t fec_bytes = 0;
489 for (const auto& kv : send_stats.substreams) {
490 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
491 kv.second.rtp_stats.fec.padding_bytes;
492 }
493 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
494 last_fec_bytes_ = fec_bytes;
495
496 if (receive_stream_ != nullptr) {
497 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
Johannes Krona1b99b32019-07-30 15:08:16 +0200498 // |total_decode_time_ms| gives a good estimate of the mean decode time,
499 // |decode_ms| is used to keep track of the standard deviation.
500 if (receive_stats.frames_decoded > 0)
501 mean_decode_time_ms_ =
502 static_cast<double>(receive_stats.total_decode_time_ms) /
503 receive_stats.frames_decoded;
Artem Titovff7730d2019-04-02 13:46:53 +0200504 if (receive_stats.decode_ms > 0)
505 decode_time_ms_.AddSample(receive_stats.decode_ms);
506 if (receive_stats.max_decode_ms > 0)
507 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
508 if (receive_stats.width > 0 && receive_stats.height > 0) {
509 pixels_.AddSample(receive_stats.width * receive_stats.height);
510 }
Elad Alon58e06572019-05-08 15:34:24 +0200511
512 // |frames_decoded| and |frames_rendered| are used because they are more
513 // accurate than |decode_frame_rate| and |render_frame_rate|.
514 // The latter two are calculated on a momentary basis.
515 const double total_frames_duration_sec_double =
516 static_cast<double>(receive_stats.total_frames_duration_ms) / 1000.0;
517 if (total_frames_duration_sec_double > 0) {
518 decode_frame_rate_ = static_cast<double>(receive_stats.frames_decoded) /
519 total_frames_duration_sec_double;
520 render_frame_rate_ = static_cast<double>(receive_stats.frames_rendered) /
521 total_frames_duration_sec_double;
522 }
523
524 // Freeze metrics.
Elad Alon8c513c72019-05-07 21:22:24 +0200525 freeze_count_ = receive_stats.freeze_count;
526 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
527 total_frames_duration_ms_ = receive_stats.total_frames_duration_ms;
528 sum_squared_frame_durations_ = receive_stats.sum_squared_frame_durations;
Artem Titovff7730d2019-04-02 13:46:53 +0200529 }
530
531 if (audio_receive_stream_ != nullptr) {
532 AudioReceiveStream::Stats receive_stats = audio_receive_stream_->GetStats();
533 audio_expand_rate_.AddSample(receive_stats.expand_rate);
534 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
535 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
536 }
537
538 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200539}
540
Niels Möller4731f002019-05-03 09:34:24 +0200541void VideoAnalyzer::FrameComparisonThread(void* obj) {
542 VideoAnalyzer* analyzer = static_cast<VideoAnalyzer*>(obj);
543 while (analyzer->CompareFrames()) {
544 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200545}
546
547bool VideoAnalyzer::CompareFrames() {
548 if (AllFramesRecorded())
549 return false;
550
551 FrameComparison comparison;
552
553 if (!PopComparison(&comparison)) {
554 // Wait until new comparison task is available, or test is done.
555 // If done, wake up remaining threads waiting.
556 comparison_available_event_.Wait(1000);
557 if (AllFramesRecorded()) {
558 comparison_available_event_.Set();
559 return false;
560 }
561 return true; // Try again.
562 }
563
564 StartExcludingCpuThreadTime();
565
566 PerformFrameComparison(comparison);
567
568 StopExcludingCpuThreadTime();
569
570 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200571 done_.Set();
572 comparison_available_event_.Set();
573 return false;
574 }
575
576 return true;
577}
578
579bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
580 rtc::CritScope crit(&comparison_lock_);
581 // If AllFramesRecorded() is true, it means we have already popped
582 // frames_to_process_ frames from comparisons_, so there is no more work
583 // for this thread to be done. frames_processed_ might still be lower if
584 // all comparisons are not done, but those frames are currently being
585 // worked on by other threads.
586 if (comparisons_.empty() || AllFramesRecorded())
587 return false;
588
589 *comparison = comparisons_.front();
590 comparisons_.pop_front();
591
592 FrameRecorded();
593 return true;
594}
595
596void VideoAnalyzer::FrameRecorded() {
597 rtc::CritScope crit(&comparison_lock_);
598 ++frames_recorded_;
599}
600
601bool VideoAnalyzer::AllFramesRecorded() {
602 rtc::CritScope crit(&comparison_lock_);
Niels Möller4731f002019-05-03 09:34:24 +0200603 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
604 return frames_recorded_ == frames_to_process_ || quit_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200605}
606
607bool VideoAnalyzer::FrameProcessed() {
608 rtc::CritScope crit(&comparison_lock_);
609 ++frames_processed_;
610 assert(frames_processed_ <= frames_to_process_);
611 return frames_processed_ == frames_to_process_;
612}
613
614void VideoAnalyzer::PrintResults() {
Artem Titov82ce3842019-09-23 17:55:52 +0200615 using ::webrtc::test::ImproveDirection;
616
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200617 StopMeasuringCpuProcessTime();
Yves Gerey0c67c802019-08-01 17:45:54 +0200618 int dropped_frames_diff;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100619 {
620 rtc::CritScope crit(&crit_);
Yves Gerey0c67c802019-08-01 17:45:54 +0200621 dropped_frames_diff = dropped_frames_before_first_encode_ +
622 dropped_frames_before_rendering_ + frames_.size();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100623 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200624 rtc::CritScope crit(&comparison_lock_);
Artem Titov82ce3842019-09-23 17:55:52 +0200625 PrintResult("psnr", psnr_, "dB", ImproveDirection::kBiggerIsBetter);
626 PrintResult("ssim", ssim_, "unitless", ImproveDirection::kBiggerIsBetter);
627 PrintResult("sender_time", sender_time_, "ms",
628 ImproveDirection::kSmallerIsBetter);
629 PrintResult("receiver_time", receiver_time_, "ms",
630 ImproveDirection::kSmallerIsBetter);
631 PrintResult("network_time", network_time_, "ms",
632 ImproveDirection::kSmallerIsBetter);
633 PrintResult("total_delay_incl_network", end_to_end_, "ms",
634 ImproveDirection::kSmallerIsBetter);
635 PrintResult("time_between_rendered_frames", rendered_delta_, "ms",
636 ImproveDirection::kSmallerIsBetter);
637 PrintResult("encode_frame_rate", encode_frame_rate_, "fps",
638 ImproveDirection::kBiggerIsBetter);
639 PrintResult("encode_time", encode_time_ms_, "ms",
640 ImproveDirection::kSmallerIsBetter);
641 PrintResult("media_bitrate", media_bitrate_bps_, "bps",
642 ImproveDirection::kNone);
643 PrintResult("fec_bitrate", fec_bitrate_bps_, "bps", ImproveDirection::kNone);
644 PrintResult("send_bandwidth", send_bandwidth_bps_, "bps",
645 ImproveDirection::kNone);
646 PrintResult("pixels_per_frame", pixels_, "count",
647 ImproveDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200648
Elad Alon58e06572019-05-08 15:34:24 +0200649 test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
Artem Titov82ce3842019-09-23 17:55:52 +0200650 decode_frame_rate_, "fps", false,
651 ImproveDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 15:34:24 +0200652 test::PrintResult("render_frame_rate", "", test_label_.c_str(),
Artem Titov82ce3842019-09-23 17:55:52 +0200653 render_frame_rate_, "fps", false,
654 ImproveDirection::kBiggerIsBetter);
Elad Alon58e06572019-05-08 15:34:24 +0200655
Elad Alon8c513c72019-05-07 21:22:24 +0200656 // Record the time from the last freeze until the last rendered frame to
657 // ensure we cover the full timespan of the session. Otherwise the metric
658 // would penalize an early freeze followed by no freezes until the end.
659 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
660
661 // Freeze metrics.
Artem Titov82ce3842019-09-23 17:55:52 +0200662 PrintResult("time_between_freezes", time_between_freezes_, "ms",
663 ImproveDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200664
665 const double freeze_count_double = static_cast<double>(freeze_count_);
666 const double total_freezes_duration_ms_double =
667 static_cast<double>(total_freezes_duration_ms_);
668 const double total_frames_duration_ms_double =
669 static_cast<double>(total_frames_duration_ms_);
670
671 if (total_frames_duration_ms_double > 0) {
672 test::PrintResult(
673 "freeze_duration_ratio", "", test_label_.c_str(),
Artem Titovea9798c2019-07-31 14:27:42 +0200674 total_freezes_duration_ms_double / total_frames_duration_ms_double,
Artem Titov82ce3842019-09-23 17:55:52 +0200675 "unitless", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200676 RTC_DCHECK_LE(total_freezes_duration_ms_double,
677 total_frames_duration_ms_double);
678
679 constexpr double ms_per_minute = 60 * 1000;
680 const double total_frames_duration_min =
681 total_frames_duration_ms_double / ms_per_minute;
682 if (total_frames_duration_min > 0) {
683 test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
684 freeze_count_double / total_frames_duration_min,
Artem Titov82ce3842019-09-23 17:55:52 +0200685 "unitless", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200686 }
687 }
688
Elad Alon133f7e72019-05-08 09:51:56 +0200689 test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
Elad Alon8c513c72019-05-07 21:22:24 +0200690 freeze_count_double > 0
691 ? total_freezes_duration_ms_double / freeze_count_double
692 : 0,
Artem Titov82ce3842019-09-23 17:55:52 +0200693 "ms", false, ImproveDirection::kSmallerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200694
695 if (1000 * sum_squared_frame_durations_ > 0) {
696 test::PrintResult(
697 "harmonic_frame_rate", "", test_label_.c_str(),
698 total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
Artem Titov82ce3842019-09-23 17:55:52 +0200699 "fps", false, ImproveDirection::kBiggerIsBetter);
Elad Alon8c513c72019-05-07 21:22:24 +0200700 }
701
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200702 if (worst_frame_) {
703 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
Artem Titov82ce3842019-09-23 17:55:52 +0200704 "dB", false, ImproveDirection::kBiggerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200705 }
706
707 if (receive_stream_ != nullptr) {
Johannes Krona1b99b32019-07-30 15:08:16 +0200708 PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
Artem Titov82ce3842019-09-23 17:55:52 +0200709 decode_time_ms_, "ms",
710 ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200711 }
Yves Gerey0c67c802019-08-01 17:45:54 +0200712 dropped_frames_ += dropped_frames_diff;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200713 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
Artem Titov82ce3842019-09-23 17:55:52 +0200714 "count", false, ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200715 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
Artem Titov82ce3842019-09-23 17:55:52 +0200716 "%", false, ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200717
718#if defined(WEBRTC_WIN)
719 // On Linux and Mac in Resident Set some unused pages may be counted.
720 // Therefore this metric will depend on order in which tests are run and
721 // will be flaky.
Artem Titov82ce3842019-09-23 17:55:52 +0200722 PrintResult("memory_usage", memory_usage_, "sizeInBytes",
723 ImproveDirection::kSmallerIsBetter);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200724#endif
725
726 // Saving only the worst frame for manual analysis. Intention here is to
727 // only detect video corruptions and not to track picture quality. Thus,
728 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 13:44:12 +0200729 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200730 std::string output_dir;
731 test::GetTestArtifactsDir(&output_dir);
732 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100733 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200734 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
735 test::JpegFrameWriter frame_writer(output_path);
736 RTC_CHECK(
737 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
738 }
739
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200740 if (audio_receive_stream_ != nullptr) {
Artem Titov82ce3842019-09-23 17:55:52 +0200741 PrintResult("audio_expand_rate", audio_expand_rate_, "unitless",
742 ImproveDirection::kSmallerIsBetter);
743 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "unitless",
744 ImproveDirection::kSmallerIsBetter);
745 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, "ms",
746 ImproveDirection::kNone);
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200747 }
748
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200749 // Disable quality check for quick test, as quality checks may fail
750 // because too few samples were collected.
751 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200752 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
753 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200754 }
755}
756
757void VideoAnalyzer::PerformFrameComparison(
758 const VideoAnalyzer::FrameComparison& comparison) {
759 // Perform expensive psnr and ssim calculations while not holding lock.
760 double psnr = -1.0;
761 double ssim = -1.0;
762 if (comparison.reference && !comparison.dropped) {
763 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
764 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
765 }
766
767 rtc::CritScope crit(&comparison_lock_);
768
769 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
770 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
771 }
772
773 if (graph_data_output_file_) {
774 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
775 comparison.send_time_ms, comparison.recv_time_ms,
776 comparison.render_time_ms,
777 comparison.encoded_frame_size, psnr, ssim));
778 }
779 if (psnr >= 0.0)
780 psnr_.AddSample(psnr);
781 if (ssim >= 0.0)
782 ssim_.AddSample(ssim);
783
784 if (comparison.dropped) {
785 ++dropped_frames_;
786 return;
787 }
788 if (last_unfreeze_time_ms_ == 0)
789 last_unfreeze_time_ms_ = comparison.render_time_ms;
790 if (last_render_time_ != 0) {
791 const int64_t render_delta_ms =
792 comparison.render_time_ms - last_render_time_;
793 rendered_delta_.AddSample(render_delta_ms);
794 if (last_render_delta_ms_ != 0 &&
795 render_delta_ms - last_render_delta_ms_ > 150) {
796 time_between_freezes_.AddSample(last_render_time_ -
797 last_unfreeze_time_ms_);
798 last_unfreeze_time_ms_ = comparison.render_time_ms;
799 }
800 last_render_delta_ms_ = render_delta_ms;
801 }
802 last_render_time_ = comparison.render_time_ms;
803
804 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
805 if (comparison.recv_time_ms > 0) {
806 // If recv_time_ms == 0, this frame consisted of a packets which were all
807 // lost in the transport. Since we were able to render the frame, however,
808 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
809 // happens internally in Call, and we can therefore here not know which
810 // FEC packets that protected the lost media packets. Consequently, we
811 // were not able to record a meaningful recv_time_ms. We therefore skip
812 // this sample.
813 //
814 // The reasoning above does not hold for ULPFEC and RTX, as for those
815 // strategies the timestamp of the received packets is set to the
816 // timestamp of the protected/retransmitted media packet. I.e., then
817 // recv_time_ms != 0, even though the media packets were lost.
818 receiver_time_.AddSample(comparison.render_time_ms -
819 comparison.recv_time_ms);
820 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
821 }
822 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
823 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
824}
825
Artem Titov82ce3842019-09-23 17:55:52 +0200826void VideoAnalyzer::PrintResult(
827 const char* result_type,
828 Statistics stats,
829 const char* unit,
830 webrtc::test::ImproveDirection improve_direction) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200831 test::PrintResultMeanAndError(
832 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
Artem Titov82ce3842019-09-23 17:55:52 +0200833 stats.GetStandardDeviation().value_or(0), unit, false, improve_direction);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200834}
835
Artem Titov82ce3842019-09-23 17:55:52 +0200836void VideoAnalyzer::PrintResultWithExternalMean(
837 const char* result_type,
838 double mean,
839 Statistics stats,
840 const char* unit,
841 webrtc::test::ImproveDirection improve_direction) {
Johannes Krona1b99b32019-07-30 15:08:16 +0200842 // If the true mean is different than the sample mean, the sample variance is
843 // too low. The sample variance given a known mean is obtained by adding the
844 // squared error between the true mean and the sample mean.
845 double compensated_variance =
846 stats.Size() > 0
847 ? *stats.GetVariance() + pow(mean - *stats.GetMean(), 2.0)
848 : 0.0;
849 test::PrintResultMeanAndError(result_type, "", test_label_.c_str(), mean,
Artem Titov82ce3842019-09-23 17:55:52 +0200850 std::sqrt(compensated_variance), unit, false,
851 improve_direction);
Johannes Krona1b99b32019-07-30 15:08:16 +0200852}
853
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200854void VideoAnalyzer::PrintSamplesToFile() {
855 FILE* out = graph_data_output_file_;
856 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700857 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
858 return A.input_time_ms < B.input_time_ms;
859 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200860
861 fprintf(out, "%s\n", graph_title_.c_str());
Oleh Prypinb1686782019-08-02 09:36:47 +0200862 fprintf(out, "%" RTC_PRIuS "\n", samples_.size());
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200863 fprintf(out,
864 "dropped "
865 "input_time_ms "
866 "send_time_ms "
867 "recv_time_ms "
868 "render_time_ms "
869 "encoded_frame_size "
870 "psnr "
871 "ssim "
872 "encode_time_ms\n");
873 for (const Sample& sample : samples_) {
874 fprintf(out,
Oleh Prypinb1686782019-08-02 09:36:47 +0200875 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" RTC_PRIuS
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200876 " %lf %lf\n",
877 sample.dropped, sample.input_time_ms, sample.send_time_ms,
878 sample.recv_time_ms, sample.render_time_ms,
879 sample.encoded_frame_size, sample.psnr, sample.ssim);
880 }
881}
882
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200883void VideoAnalyzer::AddCapturedFrameForComparison(
884 const VideoFrame& video_frame) {
Yves Gerey0c67c802019-08-01 17:45:54 +0200885 bool must_capture = false;
886 {
887 rtc::CritScope lock(&comparison_lock_);
888 must_capture = captured_frames_ < frames_to_process_;
889 if (must_capture) {
890 ++captured_frames_;
891 }
892 }
893 if (must_capture) {
894 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100895 frames_.push_back(video_frame);
896 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200897}
898
899void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
900 const VideoFrame& render,
901 bool dropped,
902 int64_t render_time_ms) {
903 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
904 int64_t send_time_ms = send_times_[reference_timestamp];
905 send_times_.erase(reference_timestamp);
906 int64_t recv_time_ms = recv_times_[reference_timestamp];
907 recv_times_.erase(reference_timestamp);
908
909 // TODO(ivica): Make this work for > 2 streams.
910 auto it = encoded_frame_sizes_.find(reference_timestamp);
911 if (it == encoded_frame_sizes_.end())
912 it = encoded_frame_sizes_.find(reference_timestamp - 1);
913 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
914 if (it != encoded_frame_sizes_.end())
915 encoded_frame_sizes_.erase(it);
916
917 rtc::CritScope crit(&comparison_lock_);
918 if (comparisons_.size() < kMaxComparisons) {
919 comparisons_.push_back(FrameComparison(
920 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
921 recv_time_ms, render_time_ms, encoded_size));
922 } else {
923 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
924 send_time_ms, recv_time_ms,
925 render_time_ms, encoded_size));
926 }
927 comparison_available_event_.Set();
928}
929
930VideoAnalyzer::FrameComparison::FrameComparison()
931 : dropped(false),
932 input_time_ms(0),
933 send_time_ms(0),
934 recv_time_ms(0),
935 render_time_ms(0),
936 encoded_frame_size(0) {}
937
938VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
939 const VideoFrame& render,
940 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 : reference(reference),
947 render(render),
948 dropped(dropped),
949 input_time_ms(input_time_ms),
950 send_time_ms(send_time_ms),
951 recv_time_ms(recv_time_ms),
952 render_time_ms(render_time_ms),
953 encoded_frame_size(encoded_frame_size) {}
954
955VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
956 int64_t input_time_ms,
957 int64_t send_time_ms,
958 int64_t recv_time_ms,
959 int64_t render_time_ms,
960 size_t encoded_frame_size)
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
968VideoAnalyzer::Sample::Sample(int dropped,
969 int64_t input_time_ms,
970 int64_t send_time_ms,
971 int64_t recv_time_ms,
972 int64_t render_time_ms,
973 size_t encoded_frame_size,
974 double psnr,
975 double ssim)
976 : dropped(dropped),
977 input_time_ms(input_time_ms),
978 send_time_ms(send_time_ms),
979 recv_time_ms(recv_time_ms),
980 render_time_ms(render_time_ms),
981 encoded_frame_size(encoded_frame_size),
982 psnr(psnr),
983 ssim(ssim) {}
984
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200985VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
986 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100987 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100988 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200989 : analyzer_(analyzer),
990 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100991 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100992 clock_(clock),
993 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100994 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200995
996void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100997 VideoSourceInterface<VideoFrame>* video_source) {
998 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200999}
1000
1001void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
1002 const VideoFrame& video_frame) {
1003 VideoFrame copy = video_frame;
1004 // Frames from the capturer does not have a rtp timestamp.
1005 // Create one so it can be used for comparison.
1006 RTC_DCHECK_EQ(0, video_frame.timestamp());
1007 if (video_frame.ntp_time_ms() == 0)
1008 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
1009 copy.set_timestamp(copy.ntp_time_ms() * 90);
1010 analyzer_->AddCapturedFrameForComparison(copy);
1011 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +01001012 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +01001013 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001014 send_stream_input_->OnFrame(copy);
1015}
1016
1017void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
1018 rtc::VideoSinkInterface<VideoFrame>* sink,
1019 const rtc::VideoSinkWants& wants) {
1020 {
1021 rtc::CritScope lock(&crit_);
1022 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
1023 send_stream_input_ = sink;
1024 }
Niels Möller1c931c42018-12-18 16:08:11 +01001025 if (video_source_) {
1026 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001027 }
1028}
1029
1030void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1031 rtc::VideoSinkInterface<VideoFrame>* sink) {
1032 rtc::CritScope lock(&crit_);
1033 RTC_DCHECK(sink == send_stream_input_);
1034 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001035}
1036
1037} // namespace webrtc