blob: fa18d0000056cb3ab4c934477a77545987479ee5 [file] [log] [blame]
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001/*
2 * Copyright 2018 The WebRTC project authors. All Rights Reserved.
3 *
4 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
9 */
10#include "video/video_analyzer.h"
11
12#include <algorithm>
13#include <utility>
14
Steve Antonbd631a02019-03-28 10:51:27 -070015#include "absl/algorithm/container.h"
Mirko Bonadei2ab97f62019-07-18 13:44:12 +020016#include "absl/flags/flag.h"
17#include "absl/flags/parse.h"
Niels Möller1c931c42018-12-18 16:08:11 +010018#include "common_video/libyuv/include/webrtc_libyuv.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020019#include "modules/rtp_rtcp/source/rtp_format.h"
20#include "modules/rtp_rtcp/source/rtp_utility.h"
21#include "rtc_base/cpu_time.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020022#include "rtc_base/format_macros.h"
23#include "rtc_base/memory_usage.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020024#include "system_wrappers/include/cpu_info.h"
25#include "test/call_test.h"
Steve Anton10542f22019-01-11 09:11:00 -080026#include "test/testsupport/file_utils.h"
Sebastian Janssond4c5d632018-07-10 12:57:37 +020027#include "test/testsupport/frame_writer.h"
28#include "test/testsupport/perf_test.h"
29#include "test/testsupport/test_artifacts.h"
30
Mirko Bonadei2ab97f62019-07-18 13:44:12 +020031ABSL_FLAG(bool,
32 save_worst_frame,
33 false,
34 "Enable saving a frame with the lowest PSNR to a jpeg file in the "
35 "test_artifacts_dir");
Sebastian Janssond4c5d632018-07-10 12:57:37 +020036
37namespace webrtc {
38namespace {
39constexpr int kSendStatsPollingIntervalMs = 1000;
40constexpr size_t kMaxComparisons = 10;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010041// How often is keep alive message printed.
42constexpr int kKeepAliveIntervalSeconds = 30;
43// Interval between checking that the test is over.
44constexpr int kProbingIntervalMs = 500;
45constexpr int kKeepAliveIntervalIterations =
46 kKeepAliveIntervalSeconds * 1000 / kProbingIntervalMs;
Sebastian Janssond4c5d632018-07-10 12:57:37 +020047
48bool IsFlexfec(int payload_type) {
49 return payload_type == test::CallTest::kFlexfecPayloadType;
50}
51} // namespace
52
Artem Titovff7730d2019-04-02 13:46:53 +020053VideoAnalyzer::VideoAnalyzer(
54 test::LayerFilteringTransport* transport,
55 const std::string& test_label,
56 double avg_psnr_threshold,
57 double avg_ssim_threshold,
58 int duration_frames,
59 FILE* graph_data_output_file,
60 const std::string& graph_title,
61 uint32_t ssrc_to_analyze,
62 uint32_t rtx_ssrc_to_analyze,
63 size_t selected_stream,
64 int selected_sl,
65 int selected_tl,
66 bool is_quick_test_enabled,
67 Clock* clock,
68 std::string rtp_dump_name,
69 test::SingleThreadedTaskQueueForTesting* task_queue)
Sebastian Janssond4c5d632018-07-10 12:57:37 +020070 : transport_(transport),
71 receiver_(nullptr),
72 call_(nullptr),
73 send_stream_(nullptr),
74 receive_stream_(nullptr),
Christoffer Rodbroc2a02882018-08-07 14:10:56 +020075 audio_receive_stream_(nullptr),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +010076 captured_frame_forwarder_(this, clock, duration_frames),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020077 test_label_(test_label),
78 graph_data_output_file_(graph_data_output_file),
79 graph_title_(graph_title),
80 ssrc_to_analyze_(ssrc_to_analyze),
81 rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
82 selected_stream_(selected_stream),
83 selected_sl_(selected_sl),
84 selected_tl_(selected_tl),
Elad Alon8c513c72019-05-07 21:22:24 +020085 freeze_count_(0),
86 total_freezes_duration_ms_(0),
87 total_frames_duration_ms_(0),
88 sum_squared_frame_durations_(0),
Elad Alon58e06572019-05-08 15:34:24 +020089 decode_frame_rate_(0),
90 render_frame_rate_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020091 last_fec_bytes_(0),
92 frames_to_process_(duration_frames),
93 frames_recorded_(0),
94 frames_processed_(0),
95 dropped_frames_(0),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +010096 captured_frames_(0),
Sebastian Janssond4c5d632018-07-10 12:57:37 +020097 dropped_frames_before_first_encode_(0),
98 dropped_frames_before_rendering_(0),
99 last_render_time_(0),
100 last_render_delta_ms_(0),
101 last_unfreeze_time_ms_(0),
102 rtp_timestamp_delta_(0),
103 total_media_bytes_(0),
104 first_sending_time_(0),
105 last_sending_time_(0),
106 cpu_time_(0),
107 wallclock_time_(0),
108 avg_psnr_threshold_(avg_psnr_threshold),
109 avg_ssim_threshold_(avg_ssim_threshold),
110 is_quick_test_enabled_(is_quick_test_enabled),
Niels Möller4731f002019-05-03 09:34:24 +0200111 quit_(false),
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200112 done_(true, false),
113 clock_(clock),
Artem Titovff7730d2019-04-02 13:46:53 +0200114 start_ms_(clock->TimeInMilliseconds()),
115 task_queue_(task_queue) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200116 // Create thread pool for CPU-expensive PSNR/SSIM calculations.
117
118 // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
119 // so that we don't accidentally starve "real" worker threads (codec etc).
120 // Also, don't allocate more than kMaxComparisonThreads, even if there are
121 // spare cores.
122
123 uint32_t num_cores = CpuInfo::DetectNumberOfCores();
124 RTC_DCHECK_GE(num_cores, 1);
125 static const uint32_t kMinCoresLeft = 4;
126 static const uint32_t kMaxComparisonThreads = 8;
127
128 if (num_cores <= kMinCoresLeft) {
129 num_cores = 1;
130 } else {
131 num_cores -= kMinCoresLeft;
132 num_cores = std::min(num_cores, kMaxComparisonThreads);
133 }
134
135 for (uint32_t i = 0; i < num_cores; ++i) {
136 rtc::PlatformThread* thread =
137 new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
138 thread->Start();
139 comparison_thread_pool_.push_back(thread);
140 }
141
142 if (!rtp_dump_name.empty()) {
143 fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
144 rtp_file_writer_.reset(test::RtpFileWriter::Create(
145 test::RtpFileWriter::kRtpDump, rtp_dump_name));
146 }
147}
148
149VideoAnalyzer::~VideoAnalyzer() {
Niels Möller4731f002019-05-03 09:34:24 +0200150 {
151 rtc::CritScope crit(&comparison_lock_);
152 quit_ = true;
153 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200154 for (rtc::PlatformThread* thread : comparison_thread_pool_) {
155 thread->Stop();
156 delete thread;
157 }
158}
159
160void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
161 receiver_ = receiver;
162}
163
Niels Möller1c931c42018-12-18 16:08:11 +0100164void VideoAnalyzer::SetSource(
165 rtc::VideoSourceInterface<VideoFrame>* video_source,
166 bool respect_sink_wants) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200167 if (respect_sink_wants)
Niels Möller1c931c42018-12-18 16:08:11 +0100168 captured_frame_forwarder_.SetSource(video_source);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200169 rtc::VideoSinkWants wants;
Niels Möller1c931c42018-12-18 16:08:11 +0100170 video_source->AddOrUpdateSink(InputInterface(), wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200171}
172
173void VideoAnalyzer::SetCall(Call* call) {
174 rtc::CritScope lock(&crit_);
175 RTC_DCHECK(!call_);
176 call_ = call;
177}
178
179void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
180 rtc::CritScope lock(&crit_);
181 RTC_DCHECK(!send_stream_);
182 send_stream_ = stream;
183}
184
185void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
186 rtc::CritScope lock(&crit_);
187 RTC_DCHECK(!receive_stream_);
188 receive_stream_ = stream;
189}
190
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200191void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
192 rtc::CritScope lock(&crit_);
193 RTC_CHECK(!audio_receive_stream_);
194 audio_receive_stream_ = recv_stream;
195}
196
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200197rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
198 return &captured_frame_forwarder_;
199}
200
201rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
202 return &captured_frame_forwarder_;
203}
204
205PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
206 MediaType media_type,
207 rtc::CopyOnWriteBuffer packet,
Niels Möller70082872018-08-07 11:03:12 +0200208 int64_t packet_time_us) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200209 // Ignore timestamps of RTCP packets. They're not synchronized with
210 // RTP packet timestamps and so they would confuse wrap_handler_.
211 if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
Niels Möller70082872018-08-07 11:03:12 +0200212 return receiver_->DeliverPacket(media_type, std::move(packet),
213 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200214 }
215
216 if (rtp_file_writer_) {
217 test::RtpPacket p;
218 memcpy(p.data, packet.cdata(), packet.size());
219 p.length = packet.size();
220 p.original_length = packet.size();
221 p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
222 rtp_file_writer_->WritePacket(&p);
223 }
224
225 RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
226 RTPHeader header;
227 parser.Parse(&header);
228 if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
229 header.ssrc == rtx_ssrc_to_analyze_)) {
230 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
231 // (FlexFEC and media are sent on different SSRCs, which have different
232 // timestamps spaces.)
233 // Also ignore packets from wrong SSRC, but include retransmits.
234 rtc::CritScope lock(&crit_);
235 int64_t timestamp =
236 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100237 recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200238 }
239
Niels Möller70082872018-08-07 11:03:12 +0200240 return receiver_->DeliverPacket(media_type, std::move(packet),
241 packet_time_us);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200242}
243
244void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
245 rtc::CritScope lock(&crit_);
246 if (!first_encoded_timestamp_) {
247 while (frames_.front().timestamp() != video_frame.timestamp()) {
248 ++dropped_frames_before_first_encode_;
249 frames_.pop_front();
250 RTC_CHECK(!frames_.empty());
251 }
252 first_encoded_timestamp_ = video_frame.timestamp();
253 }
254}
255
Niels Möller88be9722018-10-10 10:58:52 +0200256void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200257 rtc::CritScope lock(&crit_);
Niels Möller88be9722018-10-10 10:58:52 +0200258 if (!first_sent_timestamp_ && stream_id == selected_stream_) {
259 first_sent_timestamp_ = timestamp;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200260 }
261}
262
263bool VideoAnalyzer::SendRtp(const uint8_t* packet,
264 size_t length,
265 const PacketOptions& options) {
266 RtpUtility::RtpHeaderParser parser(packet, length);
267 RTPHeader header;
268 parser.Parse(&header);
269
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100270 int64_t current_time = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200271
272 bool result = transport_->SendRtp(packet, length, options);
273 {
274 rtc::CritScope lock(&crit_);
275 if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
276 RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
277 rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
278 }
279
280 if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
281 // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
282 // (FlexFEC and media are sent on different SSRCs, which have different
283 // timestamps spaces.)
284 // Also ignore packets from wrong SSRC and retransmits.
285 int64_t timestamp =
286 wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
287 send_times_[timestamp] = current_time;
288
289 if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
290 encoded_frame_sizes_[timestamp] +=
291 length - (header.headerLength + header.paddingLength);
292 total_media_bytes_ +=
293 length - (header.headerLength + header.paddingLength);
294 }
295 if (first_sending_time_ == 0)
296 first_sending_time_ = current_time;
297 last_sending_time_ = current_time;
298 }
299 }
300 return result;
301}
302
303bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
304 return transport_->SendRtcp(packet, length);
305}
306
307void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
Sebastian Jansson11c012a2019-03-29 14:17:26 +0100308 int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200309
310 rtc::CritScope lock(&crit_);
311
312 StartExcludingCpuThreadTime();
313
314 int64_t send_timestamp =
315 wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
316
317 while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
318 if (!last_rendered_frame_) {
319 // No previous frame rendered, this one was dropped after sending but
320 // before rendering.
321 ++dropped_frames_before_rendering_;
322 } else {
323 AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
324 render_time_ms);
325 }
326 frames_.pop_front();
327 RTC_DCHECK(!frames_.empty());
328 }
329
330 VideoFrame reference_frame = frames_.front();
331 frames_.pop_front();
332 int64_t reference_timestamp =
333 wrap_handler_.Unwrap(reference_frame.timestamp());
334 if (send_timestamp == reference_timestamp - 1) {
335 // TODO(ivica): Make this work for > 2 streams.
336 // Look at RTPSender::BuildRTPHeader.
337 ++send_timestamp;
338 }
339 ASSERT_EQ(reference_timestamp, send_timestamp);
340
341 AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
342
343 last_rendered_frame_ = video_frame;
344
345 StopExcludingCpuThreadTime();
346}
347
348void VideoAnalyzer::Wait() {
349 // Frame comparisons can be very expensive. Wait for test to be done, but
350 // at time-out check if frames_processed is going up. If so, give it more
351 // time, otherwise fail. Hopefully this will reduce test flakiness.
352
Artem Titovff7730d2019-04-02 13:46:53 +0200353 {
354 rtc::CritScope lock(&comparison_lock_);
355 stop_stats_poller_ = false;
356 stats_polling_task_id_ = task_queue_->PostDelayedTask(
357 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
358 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200359
360 int last_frames_processed = -1;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100361 int last_frames_captured = -1;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200362 int iteration = 0;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100363
364 while (!done_.Wait(kProbingIntervalMs)) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200365 int frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100366 int frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200367 {
368 rtc::CritScope crit(&comparison_lock_);
369 frames_processed = frames_processed_;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100370 frames_captured = captured_frames_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200371 }
372
373 // Print some output so test infrastructure won't think we've crashed.
374 const char* kKeepAliveMessages[3] = {
375 "Uh, I'm-I'm not quite dead, sir.",
376 "Uh, I-I think uh, I could pull through, sir.",
377 "Actually, I think I'm all right to come with you--"};
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100378 if (++iteration % kKeepAliveIntervalIterations == 0) {
379 printf("- %s\n", kKeepAliveMessages[iteration % 3]);
380 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200381
382 if (last_frames_processed == -1) {
383 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100384 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200385 continue;
386 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100387 if (frames_processed == last_frames_processed &&
388 last_frames_captured == frames_captured) {
389 if (frames_captured < frames_to_process_) {
390 EXPECT_GT(frames_processed, last_frames_processed)
391 << "Analyzer stalled while waiting for test to finish.";
392 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200393 done_.Set();
394 break;
395 }
396 last_frames_processed = frames_processed;
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100397 last_frames_captured = frames_captured;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200398 }
399
400 if (iteration > 0)
401 printf("- Farewell, sweet Concorde!\n");
402
Artem Titovff7730d2019-04-02 13:46:53 +0200403 {
404 rtc::CritScope lock(&comparison_lock_);
405 stop_stats_poller_ = true;
406 task_queue_->CancelTask(stats_polling_task_id_);
407 }
408
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100409 PrintResults();
410 if (graph_data_output_file_)
411 PrintSamplesToFile();
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200412}
413
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200414void VideoAnalyzer::StartMeasuringCpuProcessTime() {
415 rtc::CritScope lock(&cpu_measurement_lock_);
416 cpu_time_ -= rtc::GetProcessCpuTimeNanos();
417 wallclock_time_ -= rtc::SystemTimeNanos();
418}
419
420void VideoAnalyzer::StopMeasuringCpuProcessTime() {
421 rtc::CritScope lock(&cpu_measurement_lock_);
422 cpu_time_ += rtc::GetProcessCpuTimeNanos();
423 wallclock_time_ += rtc::SystemTimeNanos();
424}
425
426void VideoAnalyzer::StartExcludingCpuThreadTime() {
427 rtc::CritScope lock(&cpu_measurement_lock_);
428 cpu_time_ += rtc::GetThreadCpuTimeNanos();
429}
430
431void VideoAnalyzer::StopExcludingCpuThreadTime() {
432 rtc::CritScope lock(&cpu_measurement_lock_);
433 cpu_time_ -= rtc::GetThreadCpuTimeNanos();
434}
435
436double VideoAnalyzer::GetCpuUsagePercent() {
437 rtc::CritScope lock(&cpu_measurement_lock_);
438 return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
439}
440
441bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
442 const uint8_t* packet,
443 size_t length,
444 const RTPHeader& header) {
445 if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
446 header.payloadType != test::CallTest::kPayloadTypeVP8) {
447 return true;
448 } else {
449 // Get VP8 and VP9 specific header to check layers indexes.
450 const uint8_t* payload = packet + header.headerLength;
451 const size_t payload_length = length - header.headerLength;
452 const size_t payload_data_length = payload_length - header.paddingLength;
453 const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
454 std::unique_ptr<RtpDepacketizer> depacketizer(
455 RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
456 RtpDepacketizer::ParsedPayload parsed_payload;
457 bool result =
458 depacketizer->Parse(&parsed_payload, payload, payload_data_length);
459 RTC_DCHECK(result);
philipel29d88462018-08-08 14:26:00 +0200460
461 int temporal_idx;
462 int spatial_idx;
463 if (is_vp8) {
Philip Eliassond52a1a62018-09-07 13:03:55 +0000464 temporal_idx = absl::get<RTPVideoHeaderVP8>(
465 parsed_payload.video_header().video_type_header)
466 .temporalIdx;
philipel29d88462018-08-08 14:26:00 +0200467 spatial_idx = kNoTemporalIdx;
468 } else {
469 const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
470 parsed_payload.video_header().video_type_header);
471 temporal_idx = vp9_header.temporal_idx;
472 spatial_idx = vp9_header.spatial_idx;
473 }
474
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200475 return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
476 temporal_idx <= selected_tl_) &&
477 (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
478 spatial_idx <= selected_sl_);
479 }
480}
481
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200482void VideoAnalyzer::PollStats() {
Artem Titovff7730d2019-04-02 13:46:53 +0200483 rtc::CritScope crit(&comparison_lock_);
484 if (stop_stats_poller_) {
485 return;
Artem Titovf537da62019-04-02 13:46:53 +0200486 }
Artem Titovff7730d2019-04-02 13:46:53 +0200487
488 Call::Stats call_stats = call_->GetStats();
489 send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
490
491 VideoSendStream::Stats send_stats = send_stream_->GetStats();
492 // It's not certain that we yet have estimates for any of these stats.
493 // Check that they are positive before mixing them in.
494 if (send_stats.encode_frame_rate > 0)
495 encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
496 if (send_stats.avg_encode_time_ms > 0)
497 encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
498 if (send_stats.encode_usage_percent > 0)
499 encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
500 if (send_stats.media_bitrate_bps > 0)
501 media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
502 size_t fec_bytes = 0;
503 for (const auto& kv : send_stats.substreams) {
504 fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
505 kv.second.rtp_stats.fec.padding_bytes;
506 }
507 fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
508 last_fec_bytes_ = fec_bytes;
509
510 if (receive_stream_ != nullptr) {
511 VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
512 if (receive_stats.decode_ms > 0)
513 decode_time_ms_.AddSample(receive_stats.decode_ms);
514 if (receive_stats.max_decode_ms > 0)
515 decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
516 if (receive_stats.width > 0 && receive_stats.height > 0) {
517 pixels_.AddSample(receive_stats.width * receive_stats.height);
518 }
Elad Alon58e06572019-05-08 15:34:24 +0200519
520 // |frames_decoded| and |frames_rendered| are used because they are more
521 // accurate than |decode_frame_rate| and |render_frame_rate|.
522 // The latter two are calculated on a momentary basis.
523 const double total_frames_duration_sec_double =
524 static_cast<double>(receive_stats.total_frames_duration_ms) / 1000.0;
525 if (total_frames_duration_sec_double > 0) {
526 decode_frame_rate_ = static_cast<double>(receive_stats.frames_decoded) /
527 total_frames_duration_sec_double;
528 render_frame_rate_ = static_cast<double>(receive_stats.frames_rendered) /
529 total_frames_duration_sec_double;
530 }
531
532 // Freeze metrics.
Elad Alon8c513c72019-05-07 21:22:24 +0200533 freeze_count_ = receive_stats.freeze_count;
534 total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
535 total_frames_duration_ms_ = receive_stats.total_frames_duration_ms;
536 sum_squared_frame_durations_ = receive_stats.sum_squared_frame_durations;
Artem Titovff7730d2019-04-02 13:46:53 +0200537 }
538
539 if (audio_receive_stream_ != nullptr) {
540 AudioReceiveStream::Stats receive_stats = audio_receive_stream_->GetStats();
541 audio_expand_rate_.AddSample(receive_stats.expand_rate);
542 audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
543 audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
544 }
545
546 memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
547
548 stats_polling_task_id_ = task_queue_->PostDelayedTask(
549 [this]() { PollStats(); }, kSendStatsPollingIntervalMs);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200550}
551
Niels Möller4731f002019-05-03 09:34:24 +0200552void VideoAnalyzer::FrameComparisonThread(void* obj) {
553 VideoAnalyzer* analyzer = static_cast<VideoAnalyzer*>(obj);
554 while (analyzer->CompareFrames()) {
555 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200556}
557
558bool VideoAnalyzer::CompareFrames() {
559 if (AllFramesRecorded())
560 return false;
561
562 FrameComparison comparison;
563
564 if (!PopComparison(&comparison)) {
565 // Wait until new comparison task is available, or test is done.
566 // If done, wake up remaining threads waiting.
567 comparison_available_event_.Wait(1000);
568 if (AllFramesRecorded()) {
569 comparison_available_event_.Set();
570 return false;
571 }
572 return true; // Try again.
573 }
574
575 StartExcludingCpuThreadTime();
576
577 PerformFrameComparison(comparison);
578
579 StopExcludingCpuThreadTime();
580
581 if (FrameProcessed()) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200582 done_.Set();
583 comparison_available_event_.Set();
584 return false;
585 }
586
587 return true;
588}
589
590bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
591 rtc::CritScope crit(&comparison_lock_);
592 // If AllFramesRecorded() is true, it means we have already popped
593 // frames_to_process_ frames from comparisons_, so there is no more work
594 // for this thread to be done. frames_processed_ might still be lower if
595 // all comparisons are not done, but those frames are currently being
596 // worked on by other threads.
597 if (comparisons_.empty() || AllFramesRecorded())
598 return false;
599
600 *comparison = comparisons_.front();
601 comparisons_.pop_front();
602
603 FrameRecorded();
604 return true;
605}
606
607void VideoAnalyzer::FrameRecorded() {
608 rtc::CritScope crit(&comparison_lock_);
609 ++frames_recorded_;
610}
611
612bool VideoAnalyzer::AllFramesRecorded() {
613 rtc::CritScope crit(&comparison_lock_);
Niels Möller4731f002019-05-03 09:34:24 +0200614 RTC_DCHECK(frames_recorded_ <= frames_to_process_);
615 return frames_recorded_ == frames_to_process_ || quit_;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200616}
617
618bool VideoAnalyzer::FrameProcessed() {
619 rtc::CritScope crit(&comparison_lock_);
620 ++frames_processed_;
621 assert(frames_processed_ <= frames_to_process_);
622 return frames_processed_ == frames_to_process_;
623}
624
625void VideoAnalyzer::PrintResults() {
626 StopMeasuringCpuProcessTime();
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100627 int frames_left;
628 {
629 rtc::CritScope crit(&crit_);
630 frames_left = frames_.size();
631 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200632 rtc::CritScope crit(&comparison_lock_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200633 PrintResult("psnr", psnr_, " dB");
634 PrintResult("ssim", ssim_, " score");
635 PrintResult("sender_time", sender_time_, " ms");
636 PrintResult("receiver_time", receiver_time_, " ms");
637 PrintResult("network_time", network_time_, " ms");
638 PrintResult("total_delay_incl_network", end_to_end_, " ms");
639 PrintResult("time_between_rendered_frames", rendered_delta_, " ms");
640 PrintResult("encode_frame_rate", encode_frame_rate_, " fps");
641 PrintResult("encode_time", encode_time_ms_, " ms");
642 PrintResult("media_bitrate", media_bitrate_bps_, " bps");
643 PrintResult("fec_bitrate", fec_bitrate_bps_, " bps");
644 PrintResult("send_bandwidth", send_bandwidth_bps_, " bps");
Ilya Nikolaevskiyd47d3eb2019-01-21 16:27:17 +0100645 PrintResult("pixels_per_frame", pixels_, " px");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200646
Elad Alon58e06572019-05-08 15:34:24 +0200647 test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
648 decode_frame_rate_, "fps", false);
649 test::PrintResult("render_frame_rate", "", test_label_.c_str(),
650 render_frame_rate_, "fps", false);
651
Elad Alon8c513c72019-05-07 21:22:24 +0200652 // Record the time from the last freeze until the last rendered frame to
653 // ensure we cover the full timespan of the session. Otherwise the metric
654 // would penalize an early freeze followed by no freezes until the end.
655 time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
656
657 // Freeze metrics.
658 PrintResult("time_between_freezes", time_between_freezes_, " ms");
659
660 const double freeze_count_double = static_cast<double>(freeze_count_);
661 const double total_freezes_duration_ms_double =
662 static_cast<double>(total_freezes_duration_ms_);
663 const double total_frames_duration_ms_double =
664 static_cast<double>(total_frames_duration_ms_);
665
666 if (total_frames_duration_ms_double > 0) {
667 test::PrintResult(
668 "freeze_duration_ratio", "", test_label_.c_str(),
669 total_freezes_duration_ms_double / total_frames_duration_ms_double, "",
670 false);
671 RTC_DCHECK_LE(total_freezes_duration_ms_double,
672 total_frames_duration_ms_double);
673
674 constexpr double ms_per_minute = 60 * 1000;
675 const double total_frames_duration_min =
676 total_frames_duration_ms_double / ms_per_minute;
677 if (total_frames_duration_min > 0) {
678 test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
679 freeze_count_double / total_frames_duration_min,
680 "freezes", false);
681 }
682 }
683
Elad Alon133f7e72019-05-08 09:51:56 +0200684 test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
Elad Alon8c513c72019-05-07 21:22:24 +0200685 freeze_count_double > 0
686 ? total_freezes_duration_ms_double / freeze_count_double
687 : 0,
688 "ms", false);
689
690 if (1000 * sum_squared_frame_durations_ > 0) {
691 test::PrintResult(
692 "harmonic_frame_rate", "", test_label_.c_str(),
693 total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
694 "", false);
695 }
696
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200697 if (worst_frame_) {
698 test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
699 "dB", false);
700 }
701
702 if (receive_stream_ != nullptr) {
703 PrintResult("decode_time", decode_time_ms_, " ms");
704 }
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100705 dropped_frames_ += dropped_frames_before_first_encode_ +
706 dropped_frames_before_rendering_ + frames_left;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200707 test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
708 "frames", false);
709 test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
710 "%", false);
711
712#if defined(WEBRTC_WIN)
713 // On Linux and Mac in Resident Set some unused pages may be counted.
714 // Therefore this metric will depend on order in which tests are run and
715 // will be flaky.
716 PrintResult("memory_usage", memory_usage_, " bytes");
717#endif
718
719 // Saving only the worst frame for manual analysis. Intention here is to
720 // only detect video corruptions and not to track picture quality. Thus,
721 // jpeg is used here.
Mirko Bonadei2ab97f62019-07-18 13:44:12 +0200722 if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200723 std::string output_dir;
724 test::GetTestArtifactsDir(&output_dir);
725 std::string output_path =
Niels Möller7b3c76b2018-11-07 09:54:28 +0100726 test::JoinFilename(output_dir, test_label_ + ".jpg");
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200727 RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
728 test::JpegFrameWriter frame_writer(output_path);
729 RTC_CHECK(
730 frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
731 }
732
Christoffer Rodbroc2a02882018-08-07 14:10:56 +0200733 if (audio_receive_stream_ != nullptr) {
734 PrintResult("audio_expand_rate", audio_expand_rate_, "");
735 PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "");
736 PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, " ms");
737 }
738
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200739 // Disable quality check for quick test, as quality checks may fail
740 // because too few samples were collected.
741 if (!is_quick_test_enabled_) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200742 EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
743 EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200744 }
745}
746
747void VideoAnalyzer::PerformFrameComparison(
748 const VideoAnalyzer::FrameComparison& comparison) {
749 // Perform expensive psnr and ssim calculations while not holding lock.
750 double psnr = -1.0;
751 double ssim = -1.0;
752 if (comparison.reference && !comparison.dropped) {
753 psnr = I420PSNR(&*comparison.reference, &*comparison.render);
754 ssim = I420SSIM(&*comparison.reference, &*comparison.render);
755 }
756
757 rtc::CritScope crit(&comparison_lock_);
758
759 if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
760 worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
761 }
762
763 if (graph_data_output_file_) {
764 samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
765 comparison.send_time_ms, comparison.recv_time_ms,
766 comparison.render_time_ms,
767 comparison.encoded_frame_size, psnr, ssim));
768 }
769 if (psnr >= 0.0)
770 psnr_.AddSample(psnr);
771 if (ssim >= 0.0)
772 ssim_.AddSample(ssim);
773
774 if (comparison.dropped) {
775 ++dropped_frames_;
776 return;
777 }
778 if (last_unfreeze_time_ms_ == 0)
779 last_unfreeze_time_ms_ = comparison.render_time_ms;
780 if (last_render_time_ != 0) {
781 const int64_t render_delta_ms =
782 comparison.render_time_ms - last_render_time_;
783 rendered_delta_.AddSample(render_delta_ms);
784 if (last_render_delta_ms_ != 0 &&
785 render_delta_ms - last_render_delta_ms_ > 150) {
786 time_between_freezes_.AddSample(last_render_time_ -
787 last_unfreeze_time_ms_);
788 last_unfreeze_time_ms_ = comparison.render_time_ms;
789 }
790 last_render_delta_ms_ = render_delta_ms;
791 }
792 last_render_time_ = comparison.render_time_ms;
793
794 sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
795 if (comparison.recv_time_ms > 0) {
796 // If recv_time_ms == 0, this frame consisted of a packets which were all
797 // lost in the transport. Since we were able to render the frame, however,
798 // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
799 // happens internally in Call, and we can therefore here not know which
800 // FEC packets that protected the lost media packets. Consequently, we
801 // were not able to record a meaningful recv_time_ms. We therefore skip
802 // this sample.
803 //
804 // The reasoning above does not hold for ULPFEC and RTX, as for those
805 // strategies the timestamp of the received packets is set to the
806 // timestamp of the protected/retransmitted media packet. I.e., then
807 // recv_time_ms != 0, even though the media packets were lost.
808 receiver_time_.AddSample(comparison.render_time_ms -
809 comparison.recv_time_ms);
810 network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
811 }
812 end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
813 encoded_frame_size_.AddSample(comparison.encoded_frame_size);
814}
815
816void VideoAnalyzer::PrintResult(const char* result_type,
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200817 Statistics stats,
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200818 const char* unit) {
Yves Gerey79e9f4b2019-04-13 18:59:53 +0200819 test::PrintResultMeanAndError(
820 result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
821 stats.GetStandardDeviation().value_or(0), unit, false);
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200822}
823
824void VideoAnalyzer::PrintSamplesToFile() {
825 FILE* out = graph_data_output_file_;
826 rtc::CritScope crit(&comparison_lock_);
Steve Antonbd631a02019-03-28 10:51:27 -0700827 absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
828 return A.input_time_ms < B.input_time_ms;
829 });
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200830
831 fprintf(out, "%s\n", graph_title_.c_str());
832 fprintf(out, "%" PRIuS "\n", samples_.size());
833 fprintf(out,
834 "dropped "
835 "input_time_ms "
836 "send_time_ms "
837 "recv_time_ms "
838 "render_time_ms "
839 "encoded_frame_size "
840 "psnr "
841 "ssim "
842 "encode_time_ms\n");
843 for (const Sample& sample : samples_) {
844 fprintf(out,
845 "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRIuS
846 " %lf %lf\n",
847 sample.dropped, sample.input_time_ms, sample.send_time_ms,
848 sample.recv_time_ms, sample.render_time_ms,
849 sample.encoded_frame_size, sample.psnr, sample.ssim);
850 }
851}
852
853double VideoAnalyzer::GetAverageMediaBitrateBps() {
854 if (last_sending_time_ == first_sending_time_) {
855 return 0;
856 } else {
857 return static_cast<double>(total_media_bytes_) * 8 /
858 (last_sending_time_ - first_sending_time_) *
859 rtc::kNumMillisecsPerSec;
860 }
861}
862
863void VideoAnalyzer::AddCapturedFrameForComparison(
864 const VideoFrame& video_frame) {
865 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100866 if (captured_frames_ < frames_to_process_) {
867 ++captured_frames_;
868 frames_.push_back(video_frame);
869 }
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200870}
871
872void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
873 const VideoFrame& render,
874 bool dropped,
875 int64_t render_time_ms) {
876 int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
877 int64_t send_time_ms = send_times_[reference_timestamp];
878 send_times_.erase(reference_timestamp);
879 int64_t recv_time_ms = recv_times_[reference_timestamp];
880 recv_times_.erase(reference_timestamp);
881
882 // TODO(ivica): Make this work for > 2 streams.
883 auto it = encoded_frame_sizes_.find(reference_timestamp);
884 if (it == encoded_frame_sizes_.end())
885 it = encoded_frame_sizes_.find(reference_timestamp - 1);
886 size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
887 if (it != encoded_frame_sizes_.end())
888 encoded_frame_sizes_.erase(it);
889
890 rtc::CritScope crit(&comparison_lock_);
891 if (comparisons_.size() < kMaxComparisons) {
892 comparisons_.push_back(FrameComparison(
893 reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
894 recv_time_ms, render_time_ms, encoded_size));
895 } else {
896 comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
897 send_time_ms, recv_time_ms,
898 render_time_ms, encoded_size));
899 }
900 comparison_available_event_.Set();
901}
902
903VideoAnalyzer::FrameComparison::FrameComparison()
904 : dropped(false),
905 input_time_ms(0),
906 send_time_ms(0),
907 recv_time_ms(0),
908 render_time_ms(0),
909 encoded_frame_size(0) {}
910
911VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
912 const VideoFrame& render,
913 bool dropped,
914 int64_t input_time_ms,
915 int64_t send_time_ms,
916 int64_t recv_time_ms,
917 int64_t render_time_ms,
918 size_t encoded_frame_size)
919 : reference(reference),
920 render(render),
921 dropped(dropped),
922 input_time_ms(input_time_ms),
923 send_time_ms(send_time_ms),
924 recv_time_ms(recv_time_ms),
925 render_time_ms(render_time_ms),
926 encoded_frame_size(encoded_frame_size) {}
927
928VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
929 int64_t input_time_ms,
930 int64_t send_time_ms,
931 int64_t recv_time_ms,
932 int64_t render_time_ms,
933 size_t encoded_frame_size)
934 : dropped(dropped),
935 input_time_ms(input_time_ms),
936 send_time_ms(send_time_ms),
937 recv_time_ms(recv_time_ms),
938 render_time_ms(render_time_ms),
939 encoded_frame_size(encoded_frame_size) {}
940
941VideoAnalyzer::Sample::Sample(int dropped,
942 int64_t input_time_ms,
943 int64_t send_time_ms,
944 int64_t recv_time_ms,
945 int64_t render_time_ms,
946 size_t encoded_frame_size,
947 double psnr,
948 double ssim)
949 : dropped(dropped),
950 input_time_ms(input_time_ms),
951 send_time_ms(send_time_ms),
952 recv_time_ms(recv_time_ms),
953 render_time_ms(render_time_ms),
954 encoded_frame_size(encoded_frame_size),
955 psnr(psnr),
956 ssim(ssim) {}
957
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200958VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
959 VideoAnalyzer* analyzer,
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100960 Clock* clock,
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100961 int frames_to_process)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200962 : analyzer_(analyzer),
963 send_stream_input_(nullptr),
Niels Möller1c931c42018-12-18 16:08:11 +0100964 video_source_(nullptr),
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100965 clock_(clock),
966 captured_frames_(0),
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100967 frames_to_process_(frames_to_process) {}
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200968
969void VideoAnalyzer::CapturedFrameForwarder::SetSource(
Niels Möller1c931c42018-12-18 16:08:11 +0100970 VideoSourceInterface<VideoFrame>* video_source) {
971 video_source_ = video_source;
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200972}
973
974void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
975 const VideoFrame& video_frame) {
976 VideoFrame copy = video_frame;
977 // Frames from the capturer does not have a rtp timestamp.
978 // Create one so it can be used for comparison.
979 RTC_DCHECK_EQ(0, video_frame.timestamp());
980 if (video_frame.ntp_time_ms() == 0)
981 copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
982 copy.set_timestamp(copy.ntp_time_ms() * 90);
983 analyzer_->AddCapturedFrameForComparison(copy);
984 rtc::CritScope lock(&crit_);
Ilya Nikolaevskiy6957abe2019-01-29 16:33:04 +0100985 ++captured_frames_;
Ilya Nikolaevskiy85fc3252019-02-11 10:41:50 +0100986 if (send_stream_input_ && captured_frames_ <= frames_to_process_)
Sebastian Janssond4c5d632018-07-10 12:57:37 +0200987 send_stream_input_->OnFrame(copy);
988}
989
990void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
991 rtc::VideoSinkInterface<VideoFrame>* sink,
992 const rtc::VideoSinkWants& wants) {
993 {
994 rtc::CritScope lock(&crit_);
995 RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
996 send_stream_input_ = sink;
997 }
Niels Möller1c931c42018-12-18 16:08:11 +0100998 if (video_source_) {
999 video_source_->AddOrUpdateSink(this, wants);
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001000 }
1001}
1002
1003void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
1004 rtc::VideoSinkInterface<VideoFrame>* sink) {
1005 rtc::CritScope lock(&crit_);
1006 RTC_DCHECK(sink == send_stream_input_);
1007 send_stream_input_ = nullptr;
Sebastian Janssond4c5d632018-07-10 12:57:37 +02001008}
1009
1010} // namespace webrtc