You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1037 lines
38 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  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. #include <algorithm>
  12. #include <utility>
  13. #include "absl/algorithm/container.h"
  14. #include "absl/flags/flag.h"
  15. #include "absl/flags/parse.h"
  16. #include "common_video/libyuv/include/webrtc_libyuv.h"
  17. #include "modules/rtp_rtcp/source/rtp_format.h"
  18. #include "modules/rtp_rtcp/source/rtp_utility.h"
  19. #include "rtc_base/cpu_time.h"
  20. #include "rtc_base/format_macros.h"
  21. #include "rtc_base/memory_usage.h"
  22. #include "rtc_base/task_queue_for_test.h"
  23. #include "rtc_base/task_utils/repeating_task.h"
  24. #include "system_wrappers/include/cpu_info.h"
  25. #include "test/call_test.h"
  26. #include "test/testsupport/file_utils.h"
  27. #include "test/testsupport/frame_writer.h"
  28. #include "test/testsupport/perf_test.h"
  29. #include "test/testsupport/test_artifacts.h"
  30. ABSL_FLAG(bool,
  31. save_worst_frame,
  32. false,
  33. "Enable saving a frame with the lowest PSNR to a jpeg file in the "
  34. "test_artifacts_dir");
  35. namespace webrtc {
  36. namespace {
  37. constexpr TimeDelta kSendStatsPollingInterval = TimeDelta::Seconds<1>();
  38. constexpr size_t kMaxComparisons = 10;
  39. // How often is keep alive message printed.
  40. constexpr int kKeepAliveIntervalSeconds = 30;
  41. // Interval between checking that the test is over.
  42. constexpr int kProbingIntervalMs = 500;
  43. constexpr int kKeepAliveIntervalIterations =
  44. kKeepAliveIntervalSeconds * 1000 / kProbingIntervalMs;
  45. bool IsFlexfec(int payload_type) {
  46. return payload_type == test::CallTest::kFlexfecPayloadType;
  47. }
  48. } // namespace
  49. VideoAnalyzer::VideoAnalyzer(test::LayerFilteringTransport* transport,
  50. const std::string& test_label,
  51. double avg_psnr_threshold,
  52. double avg_ssim_threshold,
  53. int duration_frames,
  54. FILE* graph_data_output_file,
  55. const std::string& graph_title,
  56. uint32_t ssrc_to_analyze,
  57. uint32_t rtx_ssrc_to_analyze,
  58. size_t selected_stream,
  59. int selected_sl,
  60. int selected_tl,
  61. bool is_quick_test_enabled,
  62. Clock* clock,
  63. std::string rtp_dump_name,
  64. TaskQueueBase* task_queue)
  65. : transport_(transport),
  66. receiver_(nullptr),
  67. call_(nullptr),
  68. send_stream_(nullptr),
  69. receive_stream_(nullptr),
  70. audio_receive_stream_(nullptr),
  71. captured_frame_forwarder_(this, clock, duration_frames),
  72. test_label_(test_label),
  73. graph_data_output_file_(graph_data_output_file),
  74. graph_title_(graph_title),
  75. ssrc_to_analyze_(ssrc_to_analyze),
  76. rtx_ssrc_to_analyze_(rtx_ssrc_to_analyze),
  77. selected_stream_(selected_stream),
  78. selected_sl_(selected_sl),
  79. selected_tl_(selected_tl),
  80. mean_decode_time_ms_(0.0),
  81. freeze_count_(0),
  82. total_freezes_duration_ms_(0),
  83. total_frames_duration_ms_(0),
  84. sum_squared_frame_durations_(0),
  85. decode_frame_rate_(0),
  86. render_frame_rate_(0),
  87. last_fec_bytes_(0),
  88. frames_to_process_(duration_frames),
  89. frames_recorded_(0),
  90. frames_processed_(0),
  91. captured_frames_(0),
  92. dropped_frames_(0),
  93. dropped_frames_before_first_encode_(0),
  94. dropped_frames_before_rendering_(0),
  95. last_render_time_(0),
  96. last_render_delta_ms_(0),
  97. last_unfreeze_time_ms_(0),
  98. rtp_timestamp_delta_(0),
  99. cpu_time_(0),
  100. wallclock_time_(0),
  101. avg_psnr_threshold_(avg_psnr_threshold),
  102. avg_ssim_threshold_(avg_ssim_threshold),
  103. is_quick_test_enabled_(is_quick_test_enabled),
  104. quit_(false),
  105. done_(true, false),
  106. clock_(clock),
  107. start_ms_(clock->TimeInMilliseconds()),
  108. task_queue_(task_queue) {
  109. // Create thread pool for CPU-expensive PSNR/SSIM calculations.
  110. // Try to use about as many threads as cores, but leave kMinCoresLeft alone,
  111. // so that we don't accidentally starve "real" worker threads (codec etc).
  112. // Also, don't allocate more than kMaxComparisonThreads, even if there are
  113. // spare cores.
  114. uint32_t num_cores = CpuInfo::DetectNumberOfCores();
  115. RTC_DCHECK_GE(num_cores, 1);
  116. static const uint32_t kMinCoresLeft = 4;
  117. static const uint32_t kMaxComparisonThreads = 8;
  118. if (num_cores <= kMinCoresLeft) {
  119. num_cores = 1;
  120. } else {
  121. num_cores -= kMinCoresLeft;
  122. num_cores = std::min(num_cores, kMaxComparisonThreads);
  123. }
  124. for (uint32_t i = 0; i < num_cores; ++i) {
  125. rtc::PlatformThread* thread =
  126. new rtc::PlatformThread(&FrameComparisonThread, this, "Analyzer");
  127. thread->Start();
  128. comparison_thread_pool_.push_back(thread);
  129. }
  130. if (!rtp_dump_name.empty()) {
  131. fprintf(stdout, "Writing rtp dump to %s\n", rtp_dump_name.c_str());
  132. rtp_file_writer_.reset(test::RtpFileWriter::Create(
  133. test::RtpFileWriter::kRtpDump, rtp_dump_name));
  134. }
  135. }
  136. VideoAnalyzer::~VideoAnalyzer() {
  137. {
  138. rtc::CritScope crit(&comparison_lock_);
  139. quit_ = true;
  140. }
  141. for (rtc::PlatformThread* thread : comparison_thread_pool_) {
  142. thread->Stop();
  143. delete thread;
  144. }
  145. }
  146. void VideoAnalyzer::SetReceiver(PacketReceiver* receiver) {
  147. receiver_ = receiver;
  148. }
  149. void VideoAnalyzer::SetSource(
  150. rtc::VideoSourceInterface<VideoFrame>* video_source,
  151. bool respect_sink_wants) {
  152. if (respect_sink_wants)
  153. captured_frame_forwarder_.SetSource(video_source);
  154. rtc::VideoSinkWants wants;
  155. video_source->AddOrUpdateSink(InputInterface(), wants);
  156. }
  157. void VideoAnalyzer::SetCall(Call* call) {
  158. rtc::CritScope lock(&crit_);
  159. RTC_DCHECK(!call_);
  160. call_ = call;
  161. }
  162. void VideoAnalyzer::SetSendStream(VideoSendStream* stream) {
  163. rtc::CritScope lock(&crit_);
  164. RTC_DCHECK(!send_stream_);
  165. send_stream_ = stream;
  166. }
  167. void VideoAnalyzer::SetReceiveStream(VideoReceiveStream* stream) {
  168. rtc::CritScope lock(&crit_);
  169. RTC_DCHECK(!receive_stream_);
  170. receive_stream_ = stream;
  171. }
  172. void VideoAnalyzer::SetAudioReceiveStream(AudioReceiveStream* recv_stream) {
  173. rtc::CritScope lock(&crit_);
  174. RTC_CHECK(!audio_receive_stream_);
  175. audio_receive_stream_ = recv_stream;
  176. }
  177. rtc::VideoSinkInterface<VideoFrame>* VideoAnalyzer::InputInterface() {
  178. return &captured_frame_forwarder_;
  179. }
  180. rtc::VideoSourceInterface<VideoFrame>* VideoAnalyzer::OutputInterface() {
  181. return &captured_frame_forwarder_;
  182. }
  183. PacketReceiver::DeliveryStatus VideoAnalyzer::DeliverPacket(
  184. MediaType media_type,
  185. rtc::CopyOnWriteBuffer packet,
  186. int64_t packet_time_us) {
  187. // Ignore timestamps of RTCP packets. They're not synchronized with
  188. // RTP packet timestamps and so they would confuse wrap_handler_.
  189. if (RtpHeaderParser::IsRtcp(packet.cdata(), packet.size())) {
  190. return receiver_->DeliverPacket(media_type, std::move(packet),
  191. packet_time_us);
  192. }
  193. if (rtp_file_writer_) {
  194. test::RtpPacket p;
  195. memcpy(p.data, packet.cdata(), packet.size());
  196. p.length = packet.size();
  197. p.original_length = packet.size();
  198. p.time_ms = clock_->TimeInMilliseconds() - start_ms_;
  199. rtp_file_writer_->WritePacket(&p);
  200. }
  201. RtpUtility::RtpHeaderParser parser(packet.cdata(), packet.size());
  202. RTPHeader header;
  203. parser.Parse(&header);
  204. if (!IsFlexfec(header.payloadType) && (header.ssrc == ssrc_to_analyze_ ||
  205. header.ssrc == rtx_ssrc_to_analyze_)) {
  206. // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
  207. // (FlexFEC and media are sent on different SSRCs, which have different
  208. // timestamps spaces.)
  209. // Also ignore packets from wrong SSRC, but include retransmits.
  210. rtc::CritScope lock(&crit_);
  211. int64_t timestamp =
  212. wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
  213. recv_times_[timestamp] = clock_->CurrentNtpInMilliseconds();
  214. }
  215. return receiver_->DeliverPacket(media_type, std::move(packet),
  216. packet_time_us);
  217. }
  218. void VideoAnalyzer::PreEncodeOnFrame(const VideoFrame& video_frame) {
  219. rtc::CritScope lock(&crit_);
  220. if (!first_encoded_timestamp_) {
  221. while (frames_.front().timestamp() != video_frame.timestamp()) {
  222. ++dropped_frames_before_first_encode_;
  223. frames_.pop_front();
  224. RTC_CHECK(!frames_.empty());
  225. }
  226. first_encoded_timestamp_ = video_frame.timestamp();
  227. }
  228. }
  229. void VideoAnalyzer::PostEncodeOnFrame(size_t stream_id, uint32_t timestamp) {
  230. rtc::CritScope lock(&crit_);
  231. if (!first_sent_timestamp_ && stream_id == selected_stream_) {
  232. first_sent_timestamp_ = timestamp;
  233. }
  234. }
  235. bool VideoAnalyzer::SendRtp(const uint8_t* packet,
  236. size_t length,
  237. const PacketOptions& options) {
  238. RtpUtility::RtpHeaderParser parser(packet, length);
  239. RTPHeader header;
  240. parser.Parse(&header);
  241. int64_t current_time = clock_->CurrentNtpInMilliseconds();
  242. bool result = transport_->SendRtp(packet, length, options);
  243. {
  244. rtc::CritScope lock(&crit_);
  245. if (rtp_timestamp_delta_ == 0 && header.ssrc == ssrc_to_analyze_) {
  246. RTC_CHECK(static_cast<bool>(first_sent_timestamp_));
  247. rtp_timestamp_delta_ = header.timestamp - *first_sent_timestamp_;
  248. }
  249. if (!IsFlexfec(header.payloadType) && header.ssrc == ssrc_to_analyze_) {
  250. // Ignore FlexFEC timestamps, to avoid collisions with media timestamps.
  251. // (FlexFEC and media are sent on different SSRCs, which have different
  252. // timestamps spaces.)
  253. // Also ignore packets from wrong SSRC and retransmits.
  254. int64_t timestamp =
  255. wrap_handler_.Unwrap(header.timestamp - rtp_timestamp_delta_);
  256. send_times_[timestamp] = current_time;
  257. if (IsInSelectedSpatialAndTemporalLayer(packet, length, header)) {
  258. encoded_frame_sizes_[timestamp] +=
  259. length - (header.headerLength + header.paddingLength);
  260. }
  261. }
  262. }
  263. return result;
  264. }
  265. bool VideoAnalyzer::SendRtcp(const uint8_t* packet, size_t length) {
  266. return transport_->SendRtcp(packet, length);
  267. }
  268. void VideoAnalyzer::OnFrame(const VideoFrame& video_frame) {
  269. int64_t render_time_ms = clock_->CurrentNtpInMilliseconds();
  270. rtc::CritScope lock(&crit_);
  271. StartExcludingCpuThreadTime();
  272. int64_t send_timestamp =
  273. wrap_handler_.Unwrap(video_frame.timestamp() - rtp_timestamp_delta_);
  274. while (wrap_handler_.Unwrap(frames_.front().timestamp()) < send_timestamp) {
  275. if (!last_rendered_frame_) {
  276. // No previous frame rendered, this one was dropped after sending but
  277. // before rendering.
  278. ++dropped_frames_before_rendering_;
  279. } else {
  280. AddFrameComparison(frames_.front(), *last_rendered_frame_, true,
  281. render_time_ms);
  282. }
  283. frames_.pop_front();
  284. RTC_DCHECK(!frames_.empty());
  285. }
  286. VideoFrame reference_frame = frames_.front();
  287. frames_.pop_front();
  288. int64_t reference_timestamp =
  289. wrap_handler_.Unwrap(reference_frame.timestamp());
  290. if (send_timestamp == reference_timestamp - 1) {
  291. // TODO(ivica): Make this work for > 2 streams.
  292. // Look at RTPSender::BuildRTPHeader.
  293. ++send_timestamp;
  294. }
  295. ASSERT_EQ(reference_timestamp, send_timestamp);
  296. AddFrameComparison(reference_frame, video_frame, false, render_time_ms);
  297. last_rendered_frame_ = video_frame;
  298. StopExcludingCpuThreadTime();
  299. }
  300. void VideoAnalyzer::Wait() {
  301. // Frame comparisons can be very expensive. Wait for test to be done, but
  302. // at time-out check if frames_processed is going up. If so, give it more
  303. // time, otherwise fail. Hopefully this will reduce test flakiness.
  304. RepeatingTaskHandle stats_polling_task = RepeatingTaskHandle::DelayedStart(
  305. task_queue_, kSendStatsPollingInterval, [this] {
  306. PollStats();
  307. return kSendStatsPollingInterval;
  308. });
  309. int last_frames_processed = -1;
  310. int last_frames_captured = -1;
  311. int iteration = 0;
  312. while (!done_.Wait(kProbingIntervalMs)) {
  313. int frames_processed;
  314. int frames_captured;
  315. {
  316. rtc::CritScope crit(&comparison_lock_);
  317. frames_processed = frames_processed_;
  318. frames_captured = captured_frames_;
  319. }
  320. // Print some output so test infrastructure won't think we've crashed.
  321. const char* kKeepAliveMessages[3] = {
  322. "Uh, I'm-I'm not quite dead, sir.",
  323. "Uh, I-I think uh, I could pull through, sir.",
  324. "Actually, I think I'm all right to come with you--"};
  325. if (++iteration % kKeepAliveIntervalIterations == 0) {
  326. printf("- %s\n", kKeepAliveMessages[iteration % 3]);
  327. }
  328. if (last_frames_processed == -1) {
  329. last_frames_processed = frames_processed;
  330. last_frames_captured = frames_captured;
  331. continue;
  332. }
  333. if (frames_processed == last_frames_processed &&
  334. last_frames_captured == frames_captured) {
  335. if (frames_captured < frames_to_process_) {
  336. EXPECT_GT(frames_processed, last_frames_processed)
  337. << "Analyzer stalled while waiting for test to finish.";
  338. }
  339. done_.Set();
  340. break;
  341. }
  342. last_frames_processed = frames_processed;
  343. last_frames_captured = frames_captured;
  344. }
  345. if (iteration > 0)
  346. printf("- Farewell, sweet Concorde!\n");
  347. SendTask(RTC_FROM_HERE, task_queue_, [&] { stats_polling_task.Stop(); });
  348. PrintResults();
  349. if (graph_data_output_file_)
  350. PrintSamplesToFile();
  351. }
  352. void VideoAnalyzer::StartMeasuringCpuProcessTime() {
  353. rtc::CritScope lock(&cpu_measurement_lock_);
  354. cpu_time_ -= rtc::GetProcessCpuTimeNanos();
  355. wallclock_time_ -= rtc::SystemTimeNanos();
  356. }
  357. void VideoAnalyzer::StopMeasuringCpuProcessTime() {
  358. rtc::CritScope lock(&cpu_measurement_lock_);
  359. cpu_time_ += rtc::GetProcessCpuTimeNanos();
  360. wallclock_time_ += rtc::SystemTimeNanos();
  361. }
  362. void VideoAnalyzer::StartExcludingCpuThreadTime() {
  363. rtc::CritScope lock(&cpu_measurement_lock_);
  364. cpu_time_ += rtc::GetThreadCpuTimeNanos();
  365. }
  366. void VideoAnalyzer::StopExcludingCpuThreadTime() {
  367. rtc::CritScope lock(&cpu_measurement_lock_);
  368. cpu_time_ -= rtc::GetThreadCpuTimeNanos();
  369. }
  370. double VideoAnalyzer::GetCpuUsagePercent() {
  371. rtc::CritScope lock(&cpu_measurement_lock_);
  372. return static_cast<double>(cpu_time_) / wallclock_time_ * 100.0;
  373. }
  374. bool VideoAnalyzer::IsInSelectedSpatialAndTemporalLayer(
  375. const uint8_t* packet,
  376. size_t length,
  377. const RTPHeader& header) {
  378. if (header.payloadType != test::CallTest::kPayloadTypeVP9 &&
  379. header.payloadType != test::CallTest::kPayloadTypeVP8) {
  380. return true;
  381. } else {
  382. // Get VP8 and VP9 specific header to check layers indexes.
  383. const uint8_t* payload = packet + header.headerLength;
  384. const size_t payload_length = length - header.headerLength;
  385. const size_t payload_data_length = payload_length - header.paddingLength;
  386. const bool is_vp8 = header.payloadType == test::CallTest::kPayloadTypeVP8;
  387. std::unique_ptr<RtpDepacketizer> depacketizer(
  388. RtpDepacketizer::Create(is_vp8 ? kVideoCodecVP8 : kVideoCodecVP9));
  389. RtpDepacketizer::ParsedPayload parsed_payload;
  390. bool result =
  391. depacketizer->Parse(&parsed_payload, payload, payload_data_length);
  392. RTC_DCHECK(result);
  393. int temporal_idx;
  394. int spatial_idx;
  395. if (is_vp8) {
  396. temporal_idx = absl::get<RTPVideoHeaderVP8>(
  397. parsed_payload.video_header().video_type_header)
  398. .temporalIdx;
  399. spatial_idx = kNoTemporalIdx;
  400. } else {
  401. const auto& vp9_header = absl::get<RTPVideoHeaderVP9>(
  402. parsed_payload.video_header().video_type_header);
  403. temporal_idx = vp9_header.temporal_idx;
  404. spatial_idx = vp9_header.spatial_idx;
  405. }
  406. return (selected_tl_ < 0 || temporal_idx == kNoTemporalIdx ||
  407. temporal_idx <= selected_tl_) &&
  408. (selected_sl_ < 0 || spatial_idx == kNoSpatialIdx ||
  409. spatial_idx <= selected_sl_);
  410. }
  411. }
  412. void VideoAnalyzer::PollStats() {
  413. rtc::CritScope crit(&comparison_lock_);
  414. Call::Stats call_stats = call_->GetStats();
  415. send_bandwidth_bps_.AddSample(call_stats.send_bandwidth_bps);
  416. VideoSendStream::Stats send_stats = send_stream_->GetStats();
  417. // It's not certain that we yet have estimates for any of these stats.
  418. // Check that they are positive before mixing them in.
  419. if (send_stats.encode_frame_rate > 0)
  420. encode_frame_rate_.AddSample(send_stats.encode_frame_rate);
  421. if (send_stats.avg_encode_time_ms > 0)
  422. encode_time_ms_.AddSample(send_stats.avg_encode_time_ms);
  423. if (send_stats.encode_usage_percent > 0)
  424. encode_usage_percent_.AddSample(send_stats.encode_usage_percent);
  425. if (send_stats.media_bitrate_bps > 0)
  426. media_bitrate_bps_.AddSample(send_stats.media_bitrate_bps);
  427. size_t fec_bytes = 0;
  428. for (const auto& kv : send_stats.substreams) {
  429. fec_bytes += kv.second.rtp_stats.fec.payload_bytes +
  430. kv.second.rtp_stats.fec.padding_bytes;
  431. }
  432. fec_bitrate_bps_.AddSample((fec_bytes - last_fec_bytes_) * 8);
  433. last_fec_bytes_ = fec_bytes;
  434. if (receive_stream_ != nullptr) {
  435. VideoReceiveStream::Stats receive_stats = receive_stream_->GetStats();
  436. // |total_decode_time_ms| gives a good estimate of the mean decode time,
  437. // |decode_ms| is used to keep track of the standard deviation.
  438. if (receive_stats.frames_decoded > 0)
  439. mean_decode_time_ms_ =
  440. static_cast<double>(receive_stats.total_decode_time_ms) /
  441. receive_stats.frames_decoded;
  442. if (receive_stats.decode_ms > 0)
  443. decode_time_ms_.AddSample(receive_stats.decode_ms);
  444. if (receive_stats.max_decode_ms > 0)
  445. decode_time_max_ms_.AddSample(receive_stats.max_decode_ms);
  446. if (receive_stats.width > 0 && receive_stats.height > 0) {
  447. pixels_.AddSample(receive_stats.width * receive_stats.height);
  448. }
  449. // |frames_decoded| and |frames_rendered| are used because they are more
  450. // accurate than |decode_frame_rate| and |render_frame_rate|.
  451. // The latter two are calculated on a momentary basis.
  452. const double total_frames_duration_sec_double =
  453. static_cast<double>(receive_stats.total_frames_duration_ms) / 1000.0;
  454. if (total_frames_duration_sec_double > 0) {
  455. decode_frame_rate_ = static_cast<double>(receive_stats.frames_decoded) /
  456. total_frames_duration_sec_double;
  457. render_frame_rate_ = static_cast<double>(receive_stats.frames_rendered) /
  458. total_frames_duration_sec_double;
  459. }
  460. // Freeze metrics.
  461. freeze_count_ = receive_stats.freeze_count;
  462. total_freezes_duration_ms_ = receive_stats.total_freezes_duration_ms;
  463. total_frames_duration_ms_ = receive_stats.total_frames_duration_ms;
  464. sum_squared_frame_durations_ = receive_stats.sum_squared_frame_durations;
  465. }
  466. if (audio_receive_stream_ != nullptr) {
  467. AudioReceiveStream::Stats receive_stats = audio_receive_stream_->GetStats();
  468. audio_expand_rate_.AddSample(receive_stats.expand_rate);
  469. audio_accelerate_rate_.AddSample(receive_stats.accelerate_rate);
  470. audio_jitter_buffer_ms_.AddSample(receive_stats.jitter_buffer_ms);
  471. }
  472. memory_usage_.AddSample(rtc::GetProcessResidentSizeBytes());
  473. }
  474. void VideoAnalyzer::FrameComparisonThread(void* obj) {
  475. VideoAnalyzer* analyzer = static_cast<VideoAnalyzer*>(obj);
  476. while (analyzer->CompareFrames()) {
  477. }
  478. }
  479. bool VideoAnalyzer::CompareFrames() {
  480. if (AllFramesRecorded())
  481. return false;
  482. FrameComparison comparison;
  483. if (!PopComparison(&comparison)) {
  484. // Wait until new comparison task is available, or test is done.
  485. // If done, wake up remaining threads waiting.
  486. comparison_available_event_.Wait(1000);
  487. if (AllFramesRecorded()) {
  488. comparison_available_event_.Set();
  489. return false;
  490. }
  491. return true; // Try again.
  492. }
  493. StartExcludingCpuThreadTime();
  494. PerformFrameComparison(comparison);
  495. StopExcludingCpuThreadTime();
  496. if (FrameProcessed()) {
  497. done_.Set();
  498. comparison_available_event_.Set();
  499. return false;
  500. }
  501. return true;
  502. }
  503. bool VideoAnalyzer::PopComparison(VideoAnalyzer::FrameComparison* comparison) {
  504. rtc::CritScope crit(&comparison_lock_);
  505. // If AllFramesRecorded() is true, it means we have already popped
  506. // frames_to_process_ frames from comparisons_, so there is no more work
  507. // for this thread to be done. frames_processed_ might still be lower if
  508. // all comparisons are not done, but those frames are currently being
  509. // worked on by other threads.
  510. if (comparisons_.empty() || AllFramesRecorded())
  511. return false;
  512. *comparison = comparisons_.front();
  513. comparisons_.pop_front();
  514. FrameRecorded();
  515. return true;
  516. }
  517. void VideoAnalyzer::FrameRecorded() {
  518. rtc::CritScope crit(&comparison_lock_);
  519. ++frames_recorded_;
  520. }
  521. bool VideoAnalyzer::AllFramesRecorded() {
  522. rtc::CritScope crit(&comparison_lock_);
  523. RTC_DCHECK(frames_recorded_ <= frames_to_process_);
  524. return frames_recorded_ == frames_to_process_ || quit_;
  525. }
  526. bool VideoAnalyzer::FrameProcessed() {
  527. rtc::CritScope crit(&comparison_lock_);
  528. ++frames_processed_;
  529. assert(frames_processed_ <= frames_to_process_);
  530. return frames_processed_ == frames_to_process_;
  531. }
  532. void VideoAnalyzer::PrintResults() {
  533. using ::webrtc::test::ImproveDirection;
  534. StopMeasuringCpuProcessTime();
  535. int dropped_frames_diff;
  536. {
  537. rtc::CritScope crit(&crit_);
  538. dropped_frames_diff = dropped_frames_before_first_encode_ +
  539. dropped_frames_before_rendering_ + frames_.size();
  540. }
  541. rtc::CritScope crit(&comparison_lock_);
  542. PrintResult("psnr", psnr_, "dB", ImproveDirection::kBiggerIsBetter);
  543. PrintResult("ssim", ssim_, "unitless", ImproveDirection::kBiggerIsBetter);
  544. PrintResult("sender_time", sender_time_, "ms",
  545. ImproveDirection::kSmallerIsBetter);
  546. PrintResult("receiver_time", receiver_time_, "ms",
  547. ImproveDirection::kSmallerIsBetter);
  548. PrintResult("network_time", network_time_, "ms",
  549. ImproveDirection::kSmallerIsBetter);
  550. PrintResult("total_delay_incl_network", end_to_end_, "ms",
  551. ImproveDirection::kSmallerIsBetter);
  552. PrintResult("time_between_rendered_frames", rendered_delta_, "ms",
  553. ImproveDirection::kSmallerIsBetter);
  554. PrintResult("encode_frame_rate", encode_frame_rate_, "fps",
  555. ImproveDirection::kBiggerIsBetter);
  556. PrintResult("encode_time", encode_time_ms_, "ms",
  557. ImproveDirection::kSmallerIsBetter);
  558. PrintResult("media_bitrate", media_bitrate_bps_, "bps",
  559. ImproveDirection::kNone);
  560. PrintResult("fec_bitrate", fec_bitrate_bps_, "bps", ImproveDirection::kNone);
  561. PrintResult("send_bandwidth", send_bandwidth_bps_, "bps",
  562. ImproveDirection::kNone);
  563. PrintResult("pixels_per_frame", pixels_, "count",
  564. ImproveDirection::kBiggerIsBetter);
  565. test::PrintResult("decode_frame_rate", "", test_label_.c_str(),
  566. decode_frame_rate_, "fps", false,
  567. ImproveDirection::kBiggerIsBetter);
  568. test::PrintResult("render_frame_rate", "", test_label_.c_str(),
  569. render_frame_rate_, "fps", false,
  570. ImproveDirection::kBiggerIsBetter);
  571. // Record the time from the last freeze until the last rendered frame to
  572. // ensure we cover the full timespan of the session. Otherwise the metric
  573. // would penalize an early freeze followed by no freezes until the end.
  574. time_between_freezes_.AddSample(last_render_time_ - last_unfreeze_time_ms_);
  575. // Freeze metrics.
  576. PrintResult("time_between_freezes", time_between_freezes_, "ms",
  577. ImproveDirection::kBiggerIsBetter);
  578. const double freeze_count_double = static_cast<double>(freeze_count_);
  579. const double total_freezes_duration_ms_double =
  580. static_cast<double>(total_freezes_duration_ms_);
  581. const double total_frames_duration_ms_double =
  582. static_cast<double>(total_frames_duration_ms_);
  583. if (total_frames_duration_ms_double > 0) {
  584. test::PrintResult(
  585. "freeze_duration_ratio", "", test_label_.c_str(),
  586. total_freezes_duration_ms_double / total_frames_duration_ms_double,
  587. "unitless", false, ImproveDirection::kSmallerIsBetter);
  588. RTC_DCHECK_LE(total_freezes_duration_ms_double,
  589. total_frames_duration_ms_double);
  590. constexpr double ms_per_minute = 60 * 1000;
  591. const double total_frames_duration_min =
  592. total_frames_duration_ms_double / ms_per_minute;
  593. if (total_frames_duration_min > 0) {
  594. test::PrintResult("freeze_count_per_minute", "", test_label_.c_str(),
  595. freeze_count_double / total_frames_duration_min,
  596. "unitless", false, ImproveDirection::kSmallerIsBetter);
  597. }
  598. }
  599. test::PrintResult("freeze_duration_average", "", test_label_.c_str(),
  600. freeze_count_double > 0
  601. ? total_freezes_duration_ms_double / freeze_count_double
  602. : 0,
  603. "ms", false, ImproveDirection::kSmallerIsBetter);
  604. if (1000 * sum_squared_frame_durations_ > 0) {
  605. test::PrintResult(
  606. "harmonic_frame_rate", "", test_label_.c_str(),
  607. total_frames_duration_ms_double / (1000 * sum_squared_frame_durations_),
  608. "fps", false, ImproveDirection::kBiggerIsBetter);
  609. }
  610. if (worst_frame_) {
  611. test::PrintResult("min_psnr", "", test_label_.c_str(), worst_frame_->psnr,
  612. "dB", false, ImproveDirection::kBiggerIsBetter);
  613. }
  614. if (receive_stream_ != nullptr) {
  615. PrintResultWithExternalMean("decode_time", mean_decode_time_ms_,
  616. decode_time_ms_, "ms",
  617. ImproveDirection::kSmallerIsBetter);
  618. }
  619. dropped_frames_ += dropped_frames_diff;
  620. test::PrintResult("dropped_frames", "", test_label_.c_str(), dropped_frames_,
  621. "count", false, ImproveDirection::kSmallerIsBetter);
  622. test::PrintResult("cpu_usage", "", test_label_.c_str(), GetCpuUsagePercent(),
  623. "%", false, ImproveDirection::kSmallerIsBetter);
  624. #if defined(WEBRTC_WIN)
  625. // On Linux and Mac in Resident Set some unused pages may be counted.
  626. // Therefore this metric will depend on order in which tests are run and
  627. // will be flaky.
  628. PrintResult("memory_usage", memory_usage_, "sizeInBytes",
  629. ImproveDirection::kSmallerIsBetter);
  630. #endif
  631. // Saving only the worst frame for manual analysis. Intention here is to
  632. // only detect video corruptions and not to track picture quality. Thus,
  633. // jpeg is used here.
  634. if (absl::GetFlag(FLAGS_save_worst_frame) && worst_frame_) {
  635. std::string output_dir;
  636. test::GetTestArtifactsDir(&output_dir);
  637. std::string output_path =
  638. test::JoinFilename(output_dir, test_label_ + ".jpg");
  639. RTC_LOG(LS_INFO) << "Saving worst frame to " << output_path;
  640. test::JpegFrameWriter frame_writer(output_path);
  641. RTC_CHECK(
  642. frame_writer.WriteFrame(worst_frame_->frame, 100 /*best quality*/));
  643. }
  644. if (audio_receive_stream_ != nullptr) {
  645. PrintResult("audio_expand_rate", audio_expand_rate_, "unitless",
  646. ImproveDirection::kSmallerIsBetter);
  647. PrintResult("audio_accelerate_rate", audio_accelerate_rate_, "unitless",
  648. ImproveDirection::kSmallerIsBetter);
  649. PrintResult("audio_jitter_buffer", audio_jitter_buffer_ms_, "ms",
  650. ImproveDirection::kNone);
  651. }
  652. // Disable quality check for quick test, as quality checks may fail
  653. // because too few samples were collected.
  654. if (!is_quick_test_enabled_) {
  655. EXPECT_GT(*psnr_.GetMean(), avg_psnr_threshold_);
  656. EXPECT_GT(*ssim_.GetMean(), avg_ssim_threshold_);
  657. }
  658. }
  659. void VideoAnalyzer::PerformFrameComparison(
  660. const VideoAnalyzer::FrameComparison& comparison) {
  661. // Perform expensive psnr and ssim calculations while not holding lock.
  662. double psnr = -1.0;
  663. double ssim = -1.0;
  664. if (comparison.reference && !comparison.dropped) {
  665. psnr = I420PSNR(&*comparison.reference, &*comparison.render);
  666. ssim = I420SSIM(&*comparison.reference, &*comparison.render);
  667. }
  668. rtc::CritScope crit(&comparison_lock_);
  669. if (psnr >= 0.0 && (!worst_frame_ || worst_frame_->psnr > psnr)) {
  670. worst_frame_.emplace(FrameWithPsnr{psnr, *comparison.render});
  671. }
  672. if (graph_data_output_file_) {
  673. samples_.push_back(Sample(comparison.dropped, comparison.input_time_ms,
  674. comparison.send_time_ms, comparison.recv_time_ms,
  675. comparison.render_time_ms,
  676. comparison.encoded_frame_size, psnr, ssim));
  677. }
  678. if (psnr >= 0.0)
  679. psnr_.AddSample(psnr);
  680. if (ssim >= 0.0)
  681. ssim_.AddSample(ssim);
  682. if (comparison.dropped) {
  683. ++dropped_frames_;
  684. return;
  685. }
  686. if (last_unfreeze_time_ms_ == 0)
  687. last_unfreeze_time_ms_ = comparison.render_time_ms;
  688. if (last_render_time_ != 0) {
  689. const int64_t render_delta_ms =
  690. comparison.render_time_ms - last_render_time_;
  691. rendered_delta_.AddSample(render_delta_ms);
  692. if (last_render_delta_ms_ != 0 &&
  693. render_delta_ms - last_render_delta_ms_ > 150) {
  694. time_between_freezes_.AddSample(last_render_time_ -
  695. last_unfreeze_time_ms_);
  696. last_unfreeze_time_ms_ = comparison.render_time_ms;
  697. }
  698. last_render_delta_ms_ = render_delta_ms;
  699. }
  700. last_render_time_ = comparison.render_time_ms;
  701. sender_time_.AddSample(comparison.send_time_ms - comparison.input_time_ms);
  702. if (comparison.recv_time_ms > 0) {
  703. // If recv_time_ms == 0, this frame consisted of a packets which were all
  704. // lost in the transport. Since we were able to render the frame, however,
  705. // the dropped packets were recovered by FlexFEC. The FlexFEC recovery
  706. // happens internally in Call, and we can therefore here not know which
  707. // FEC packets that protected the lost media packets. Consequently, we
  708. // were not able to record a meaningful recv_time_ms. We therefore skip
  709. // this sample.
  710. //
  711. // The reasoning above does not hold for ULPFEC and RTX, as for those
  712. // strategies the timestamp of the received packets is set to the
  713. // timestamp of the protected/retransmitted media packet. I.e., then
  714. // recv_time_ms != 0, even though the media packets were lost.
  715. receiver_time_.AddSample(comparison.render_time_ms -
  716. comparison.recv_time_ms);
  717. network_time_.AddSample(comparison.recv_time_ms - comparison.send_time_ms);
  718. }
  719. end_to_end_.AddSample(comparison.render_time_ms - comparison.input_time_ms);
  720. encoded_frame_size_.AddSample(comparison.encoded_frame_size);
  721. }
  722. void VideoAnalyzer::PrintResult(
  723. const char* result_type,
  724. Statistics stats,
  725. const char* unit,
  726. webrtc::test::ImproveDirection improve_direction) {
  727. test::PrintResultMeanAndError(
  728. result_type, "", test_label_.c_str(), stats.GetMean().value_or(0),
  729. stats.GetStandardDeviation().value_or(0), unit, false, improve_direction);
  730. }
  731. void VideoAnalyzer::PrintResultWithExternalMean(
  732. const char* result_type,
  733. double mean,
  734. Statistics stats,
  735. const char* unit,
  736. webrtc::test::ImproveDirection improve_direction) {
  737. // If the true mean is different than the sample mean, the sample variance is
  738. // too low. The sample variance given a known mean is obtained by adding the
  739. // squared error between the true mean and the sample mean.
  740. double compensated_variance =
  741. stats.Size() > 0
  742. ? *stats.GetVariance() + pow(mean - *stats.GetMean(), 2.0)
  743. : 0.0;
  744. test::PrintResultMeanAndError(result_type, "", test_label_.c_str(), mean,
  745. std::sqrt(compensated_variance), unit, false,
  746. improve_direction);
  747. }
  748. void VideoAnalyzer::PrintSamplesToFile() {
  749. FILE* out = graph_data_output_file_;
  750. rtc::CritScope crit(&comparison_lock_);
  751. absl::c_sort(samples_, [](const Sample& A, const Sample& B) -> bool {
  752. return A.input_time_ms < B.input_time_ms;
  753. });
  754. fprintf(out, "%s\n", graph_title_.c_str());
  755. fprintf(out, "%" RTC_PRIuS "\n", samples_.size());
  756. fprintf(out,
  757. "dropped "
  758. "input_time_ms "
  759. "send_time_ms "
  760. "recv_time_ms "
  761. "render_time_ms "
  762. "encoded_frame_size "
  763. "psnr "
  764. "ssim "
  765. "encode_time_ms\n");
  766. for (const Sample& sample : samples_) {
  767. fprintf(out,
  768. "%d %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" RTC_PRIuS
  769. " %lf %lf\n",
  770. sample.dropped, sample.input_time_ms, sample.send_time_ms,
  771. sample.recv_time_ms, sample.render_time_ms,
  772. sample.encoded_frame_size, sample.psnr, sample.ssim);
  773. }
  774. }
  775. void VideoAnalyzer::AddCapturedFrameForComparison(
  776. const VideoFrame& video_frame) {
  777. bool must_capture = false;
  778. {
  779. rtc::CritScope lock(&comparison_lock_);
  780. must_capture = captured_frames_ < frames_to_process_;
  781. if (must_capture) {
  782. ++captured_frames_;
  783. }
  784. }
  785. if (must_capture) {
  786. rtc::CritScope lock(&crit_);
  787. frames_.push_back(video_frame);
  788. }
  789. }
  790. void VideoAnalyzer::AddFrameComparison(const VideoFrame& reference,
  791. const VideoFrame& render,
  792. bool dropped,
  793. int64_t render_time_ms) {
  794. int64_t reference_timestamp = wrap_handler_.Unwrap(reference.timestamp());
  795. int64_t send_time_ms = send_times_[reference_timestamp];
  796. send_times_.erase(reference_timestamp);
  797. int64_t recv_time_ms = recv_times_[reference_timestamp];
  798. recv_times_.erase(reference_timestamp);
  799. // TODO(ivica): Make this work for > 2 streams.
  800. auto it = encoded_frame_sizes_.find(reference_timestamp);
  801. if (it == encoded_frame_sizes_.end())
  802. it = encoded_frame_sizes_.find(reference_timestamp - 1);
  803. size_t encoded_size = it == encoded_frame_sizes_.end() ? 0 : it->second;
  804. if (it != encoded_frame_sizes_.end())
  805. encoded_frame_sizes_.erase(it);
  806. rtc::CritScope crit(&comparison_lock_);
  807. if (comparisons_.size() < kMaxComparisons) {
  808. comparisons_.push_back(FrameComparison(
  809. reference, render, dropped, reference.ntp_time_ms(), send_time_ms,
  810. recv_time_ms, render_time_ms, encoded_size));
  811. } else {
  812. comparisons_.push_back(FrameComparison(dropped, reference.ntp_time_ms(),
  813. send_time_ms, recv_time_ms,
  814. render_time_ms, encoded_size));
  815. }
  816. comparison_available_event_.Set();
  817. }
  818. VideoAnalyzer::FrameComparison::FrameComparison()
  819. : dropped(false),
  820. input_time_ms(0),
  821. send_time_ms(0),
  822. recv_time_ms(0),
  823. render_time_ms(0),
  824. encoded_frame_size(0) {}
  825. VideoAnalyzer::FrameComparison::FrameComparison(const VideoFrame& reference,
  826. const VideoFrame& render,
  827. bool dropped,
  828. int64_t input_time_ms,
  829. int64_t send_time_ms,
  830. int64_t recv_time_ms,
  831. int64_t render_time_ms,
  832. size_t encoded_frame_size)
  833. : reference(reference),
  834. render(render),
  835. dropped(dropped),
  836. input_time_ms(input_time_ms),
  837. send_time_ms(send_time_ms),
  838. recv_time_ms(recv_time_ms),
  839. render_time_ms(render_time_ms),
  840. encoded_frame_size(encoded_frame_size) {}
  841. VideoAnalyzer::FrameComparison::FrameComparison(bool dropped,
  842. int64_t input_time_ms,
  843. int64_t send_time_ms,
  844. int64_t recv_time_ms,
  845. int64_t render_time_ms,
  846. size_t encoded_frame_size)
  847. : dropped(dropped),
  848. input_time_ms(input_time_ms),
  849. send_time_ms(send_time_ms),
  850. recv_time_ms(recv_time_ms),
  851. render_time_ms(render_time_ms),
  852. encoded_frame_size(encoded_frame_size) {}
  853. VideoAnalyzer::Sample::Sample(int dropped,
  854. int64_t input_time_ms,
  855. int64_t send_time_ms,
  856. int64_t recv_time_ms,
  857. int64_t render_time_ms,
  858. size_t encoded_frame_size,
  859. double psnr,
  860. double ssim)
  861. : dropped(dropped),
  862. input_time_ms(input_time_ms),
  863. send_time_ms(send_time_ms),
  864. recv_time_ms(recv_time_ms),
  865. render_time_ms(render_time_ms),
  866. encoded_frame_size(encoded_frame_size),
  867. psnr(psnr),
  868. ssim(ssim) {}
  869. VideoAnalyzer::CapturedFrameForwarder::CapturedFrameForwarder(
  870. VideoAnalyzer* analyzer,
  871. Clock* clock,
  872. int frames_to_process)
  873. : analyzer_(analyzer),
  874. send_stream_input_(nullptr),
  875. video_source_(nullptr),
  876. clock_(clock),
  877. captured_frames_(0),
  878. frames_to_process_(frames_to_process) {}
  879. void VideoAnalyzer::CapturedFrameForwarder::SetSource(
  880. VideoSourceInterface<VideoFrame>* video_source) {
  881. video_source_ = video_source;
  882. }
  883. void VideoAnalyzer::CapturedFrameForwarder::OnFrame(
  884. const VideoFrame& video_frame) {
  885. VideoFrame copy = video_frame;
  886. // Frames from the capturer does not have a rtp timestamp.
  887. // Create one so it can be used for comparison.
  888. RTC_DCHECK_EQ(0, video_frame.timestamp());
  889. if (video_frame.ntp_time_ms() == 0)
  890. copy.set_ntp_time_ms(clock_->CurrentNtpInMilliseconds());
  891. copy.set_timestamp(copy.ntp_time_ms() * 90);
  892. analyzer_->AddCapturedFrameForComparison(copy);
  893. rtc::CritScope lock(&crit_);
  894. ++captured_frames_;
  895. if (send_stream_input_ && captured_frames_ <= frames_to_process_)
  896. send_stream_input_->OnFrame(copy);
  897. }
  898. void VideoAnalyzer::CapturedFrameForwarder::AddOrUpdateSink(
  899. rtc::VideoSinkInterface<VideoFrame>* sink,
  900. const rtc::VideoSinkWants& wants) {
  901. {
  902. rtc::CritScope lock(&crit_);
  903. RTC_DCHECK(!send_stream_input_ || send_stream_input_ == sink);
  904. send_stream_input_ = sink;
  905. }
  906. if (video_source_) {
  907. video_source_->AddOrUpdateSink(this, wants);
  908. }
  909. }
  910. void VideoAnalyzer::CapturedFrameForwarder::RemoveSink(
  911. rtc::VideoSinkInterface<VideoFrame>* sink) {
  912. rtc::CritScope lock(&crit_);
  913. RTC_DCHECK(sink == send_stream_input_);
  914. send_stream_input_ = nullptr;
  915. }
  916. } // namespace webrtc