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.

1371 lines
53 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2013 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/send_statistics_proxy.h"
  11. #include <algorithm>
  12. #include <array>
  13. #include <cmath>
  14. #include <limits>
  15. #include <utility>
  16. #include "absl/algorithm/container.h"
  17. #include "api/video/video_codec_constants.h"
  18. #include "api/video/video_codec_type.h"
  19. #include "api/video_codecs/video_codec.h"
  20. #include "modules/video_coding/include/video_codec_interface.h"
  21. #include "rtc_base/checks.h"
  22. #include "rtc_base/logging.h"
  23. #include "rtc_base/numerics/mod_ops.h"
  24. #include "rtc_base/strings/string_builder.h"
  25. #include "system_wrappers/include/field_trial.h"
  26. #include "system_wrappers/include/metrics.h"
  27. namespace webrtc {
  28. namespace {
  29. const float kEncodeTimeWeigthFactor = 0.5f;
  30. const size_t kMaxEncodedFrameMapSize = 150;
  31. const int64_t kMaxEncodedFrameWindowMs = 800;
  32. const uint32_t kMaxEncodedFrameTimestampDiff = 900000; // 10 sec.
  33. const int64_t kBucketSizeMs = 100;
  34. const size_t kBucketCount = 10;
  35. const char kVp8ForcedFallbackEncoderFieldTrial[] =
  36. "WebRTC-VP8-Forced-Fallback-Encoder-v2";
  37. const char kVp8SwCodecName[] = "libvpx";
  38. // Used by histograms. Values of entries should not be changed.
  39. enum HistogramCodecType {
  40. kVideoUnknown = 0,
  41. kVideoVp8 = 1,
  42. kVideoVp9 = 2,
  43. kVideoH264 = 3,
  44. kVideoMax = 64,
  45. };
  46. const char* kRealtimePrefix = "WebRTC.Video.";
  47. const char* kScreenPrefix = "WebRTC.Video.Screenshare.";
  48. const char* GetUmaPrefix(VideoEncoderConfig::ContentType content_type) {
  49. switch (content_type) {
  50. case VideoEncoderConfig::ContentType::kRealtimeVideo:
  51. return kRealtimePrefix;
  52. case VideoEncoderConfig::ContentType::kScreen:
  53. return kScreenPrefix;
  54. }
  55. RTC_NOTREACHED();
  56. return nullptr;
  57. }
  58. HistogramCodecType PayloadNameToHistogramCodecType(
  59. const std::string& payload_name) {
  60. VideoCodecType codecType = PayloadStringToCodecType(payload_name);
  61. switch (codecType) {
  62. case kVideoCodecVP8:
  63. return kVideoVp8;
  64. case kVideoCodecVP9:
  65. return kVideoVp9;
  66. case kVideoCodecH264:
  67. return kVideoH264;
  68. default:
  69. return kVideoUnknown;
  70. }
  71. }
  72. void UpdateCodecTypeHistogram(const std::string& payload_name) {
  73. RTC_HISTOGRAM_ENUMERATION("WebRTC.Video.Encoder.CodecType",
  74. PayloadNameToHistogramCodecType(payload_name),
  75. kVideoMax);
  76. }
  77. bool IsForcedFallbackPossible(const CodecSpecificInfo* codec_info,
  78. int simulcast_index) {
  79. return codec_info->codecType == kVideoCodecVP8 && simulcast_index == 0 &&
  80. (codec_info->codecSpecific.VP8.temporalIdx == 0 ||
  81. codec_info->codecSpecific.VP8.temporalIdx == kNoTemporalIdx);
  82. }
  83. absl::optional<int> GetFallbackMaxPixels(const std::string& group) {
  84. if (group.empty())
  85. return absl::nullopt;
  86. int min_pixels;
  87. int max_pixels;
  88. int min_bps;
  89. if (sscanf(group.c_str(), "-%d,%d,%d", &min_pixels, &max_pixels, &min_bps) !=
  90. 3) {
  91. return absl::optional<int>();
  92. }
  93. if (min_pixels <= 0 || max_pixels <= 0 || max_pixels < min_pixels)
  94. return absl::optional<int>();
  95. return absl::optional<int>(max_pixels);
  96. }
  97. absl::optional<int> GetFallbackMaxPixelsIfFieldTrialEnabled() {
  98. std::string group =
  99. webrtc::field_trial::FindFullName(kVp8ForcedFallbackEncoderFieldTrial);
  100. return (group.find("Enabled") == 0) ? GetFallbackMaxPixels(group.substr(7))
  101. : absl::optional<int>();
  102. }
  103. absl::optional<int> GetFallbackMaxPixelsIfFieldTrialDisabled() {
  104. std::string group =
  105. webrtc::field_trial::FindFullName(kVp8ForcedFallbackEncoderFieldTrial);
  106. return (group.find("Disabled") == 0) ? GetFallbackMaxPixels(group.substr(8))
  107. : absl::optional<int>();
  108. }
  109. } // namespace
  110. const int SendStatisticsProxy::kStatsTimeoutMs = 5000;
  111. SendStatisticsProxy::SendStatisticsProxy(
  112. Clock* clock,
  113. const VideoSendStream::Config& config,
  114. VideoEncoderConfig::ContentType content_type)
  115. : clock_(clock),
  116. payload_name_(config.rtp.payload_name),
  117. rtp_config_(config.rtp),
  118. fallback_max_pixels_(GetFallbackMaxPixelsIfFieldTrialEnabled()),
  119. fallback_max_pixels_disabled_(GetFallbackMaxPixelsIfFieldTrialDisabled()),
  120. content_type_(content_type),
  121. start_ms_(clock->TimeInMilliseconds()),
  122. encode_time_(kEncodeTimeWeigthFactor),
  123. quality_downscales_(-1),
  124. cpu_downscales_(-1),
  125. quality_limitation_reason_tracker_(clock_),
  126. media_byte_rate_tracker_(kBucketSizeMs, kBucketCount),
  127. encoded_frame_rate_tracker_(kBucketSizeMs, kBucketCount),
  128. last_num_spatial_layers_(0),
  129. last_num_simulcast_streams_(0),
  130. last_spatial_layer_use_{},
  131. bw_limited_layers_(false),
  132. uma_container_(
  133. new UmaSamplesContainer(GetUmaPrefix(content_type_), stats_, clock)) {
  134. }
  135. SendStatisticsProxy::~SendStatisticsProxy() {
  136. rtc::CritScope lock(&crit_);
  137. uma_container_->UpdateHistograms(rtp_config_, stats_);
  138. int64_t elapsed_sec = (clock_->TimeInMilliseconds() - start_ms_) / 1000;
  139. RTC_HISTOGRAM_COUNTS_100000("WebRTC.Video.SendStreamLifetimeInSeconds",
  140. elapsed_sec);
  141. if (elapsed_sec >= metrics::kMinRunTimeInSeconds)
  142. UpdateCodecTypeHistogram(payload_name_);
  143. }
  144. SendStatisticsProxy::FallbackEncoderInfo::FallbackEncoderInfo() = default;
  145. SendStatisticsProxy::UmaSamplesContainer::UmaSamplesContainer(
  146. const char* prefix,
  147. const VideoSendStream::Stats& stats,
  148. Clock* const clock)
  149. : uma_prefix_(prefix),
  150. clock_(clock),
  151. input_frame_rate_tracker_(100, 10u),
  152. input_fps_counter_(clock, nullptr, true),
  153. sent_fps_counter_(clock, nullptr, true),
  154. total_byte_counter_(clock, nullptr, true),
  155. media_byte_counter_(clock, nullptr, true),
  156. rtx_byte_counter_(clock, nullptr, true),
  157. padding_byte_counter_(clock, nullptr, true),
  158. retransmit_byte_counter_(clock, nullptr, true),
  159. fec_byte_counter_(clock, nullptr, true),
  160. first_rtcp_stats_time_ms_(-1),
  161. first_rtp_stats_time_ms_(-1),
  162. start_stats_(stats),
  163. num_streams_(0),
  164. num_pixels_highest_stream_(0) {
  165. InitializeBitrateCounters(stats);
  166. static_assert(
  167. kMaxEncodedFrameTimestampDiff < std::numeric_limits<uint32_t>::max() / 2,
  168. "has to be smaller than half range");
  169. }
  170. SendStatisticsProxy::UmaSamplesContainer::~UmaSamplesContainer() {}
  171. void SendStatisticsProxy::UmaSamplesContainer::InitializeBitrateCounters(
  172. const VideoSendStream::Stats& stats) {
  173. for (const auto& it : stats.substreams) {
  174. uint32_t ssrc = it.first;
  175. total_byte_counter_.SetLast(it.second.rtp_stats.transmitted.TotalBytes(),
  176. ssrc);
  177. padding_byte_counter_.SetLast(it.second.rtp_stats.transmitted.padding_bytes,
  178. ssrc);
  179. retransmit_byte_counter_.SetLast(
  180. it.second.rtp_stats.retransmitted.TotalBytes(), ssrc);
  181. fec_byte_counter_.SetLast(it.second.rtp_stats.fec.TotalBytes(), ssrc);
  182. if (it.second.is_rtx) {
  183. rtx_byte_counter_.SetLast(it.second.rtp_stats.transmitted.TotalBytes(),
  184. ssrc);
  185. } else {
  186. media_byte_counter_.SetLast(it.second.rtp_stats.MediaPayloadBytes(),
  187. ssrc);
  188. }
  189. }
  190. }
  191. void SendStatisticsProxy::UmaSamplesContainer::RemoveOld(
  192. int64_t now_ms,
  193. bool* is_limited_in_resolution) {
  194. while (!encoded_frames_.empty()) {
  195. auto it = encoded_frames_.begin();
  196. if (now_ms - it->second.send_ms < kMaxEncodedFrameWindowMs)
  197. break;
  198. // Use max per timestamp.
  199. sent_width_counter_.Add(it->second.max_width);
  200. sent_height_counter_.Add(it->second.max_height);
  201. // Check number of encoded streams per timestamp.
  202. if (num_streams_ > static_cast<size_t>(it->second.max_simulcast_idx)) {
  203. *is_limited_in_resolution = false;
  204. if (num_streams_ > 1) {
  205. int disabled_streams =
  206. static_cast<int>(num_streams_ - 1 - it->second.max_simulcast_idx);
  207. // Can be limited in resolution or framerate.
  208. uint32_t pixels = it->second.max_width * it->second.max_height;
  209. bool bw_limited_resolution =
  210. disabled_streams > 0 && pixels < num_pixels_highest_stream_;
  211. bw_limited_frame_counter_.Add(bw_limited_resolution);
  212. if (bw_limited_resolution) {
  213. bw_resolutions_disabled_counter_.Add(disabled_streams);
  214. *is_limited_in_resolution = true;
  215. }
  216. }
  217. }
  218. encoded_frames_.erase(it);
  219. }
  220. }
  221. bool SendStatisticsProxy::UmaSamplesContainer::InsertEncodedFrame(
  222. const EncodedImage& encoded_frame,
  223. int simulcast_idx,
  224. bool* is_limited_in_resolution) {
  225. int64_t now_ms = clock_->TimeInMilliseconds();
  226. RemoveOld(now_ms, is_limited_in_resolution);
  227. if (encoded_frames_.size() > kMaxEncodedFrameMapSize) {
  228. encoded_frames_.clear();
  229. }
  230. // Check for jump in timestamp.
  231. if (!encoded_frames_.empty()) {
  232. uint32_t oldest_timestamp = encoded_frames_.begin()->first;
  233. if (ForwardDiff(oldest_timestamp, encoded_frame.Timestamp()) >
  234. kMaxEncodedFrameTimestampDiff) {
  235. // Gap detected, clear frames to have a sequence where newest timestamp
  236. // is not too far away from oldest in order to distinguish old and new.
  237. encoded_frames_.clear();
  238. }
  239. }
  240. auto it = encoded_frames_.find(encoded_frame.Timestamp());
  241. if (it == encoded_frames_.end()) {
  242. // First frame with this timestamp.
  243. encoded_frames_.insert(
  244. std::make_pair(encoded_frame.Timestamp(),
  245. Frame(now_ms, encoded_frame._encodedWidth,
  246. encoded_frame._encodedHeight, simulcast_idx)));
  247. sent_fps_counter_.Add(1);
  248. return true;
  249. }
  250. it->second.max_width =
  251. std::max(it->second.max_width, encoded_frame._encodedWidth);
  252. it->second.max_height =
  253. std::max(it->second.max_height, encoded_frame._encodedHeight);
  254. it->second.max_simulcast_idx =
  255. std::max(it->second.max_simulcast_idx, simulcast_idx);
  256. return false;
  257. }
  258. void SendStatisticsProxy::UmaSamplesContainer::UpdateHistograms(
  259. const RtpConfig& rtp_config,
  260. const VideoSendStream::Stats& current_stats) {
  261. RTC_DCHECK(uma_prefix_ == kRealtimePrefix || uma_prefix_ == kScreenPrefix);
  262. const int kIndex = uma_prefix_ == kScreenPrefix ? 1 : 0;
  263. const int kMinRequiredPeriodicSamples = 6;
  264. char log_stream_buf[8 * 1024];
  265. rtc::SimpleStringBuilder log_stream(log_stream_buf);
  266. int in_width = input_width_counter_.Avg(kMinRequiredMetricsSamples);
  267. int in_height = input_height_counter_.Avg(kMinRequiredMetricsSamples);
  268. if (in_width != -1) {
  269. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "InputWidthInPixels",
  270. in_width);
  271. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "InputHeightInPixels",
  272. in_height);
  273. log_stream << uma_prefix_ << "InputWidthInPixels " << in_width << "\n"
  274. << uma_prefix_ << "InputHeightInPixels " << in_height << "\n";
  275. }
  276. AggregatedStats in_fps = input_fps_counter_.GetStats();
  277. if (in_fps.num_samples >= kMinRequiredPeriodicSamples) {
  278. RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "InputFramesPerSecond",
  279. in_fps.average);
  280. log_stream << uma_prefix_ << "InputFramesPerSecond " << in_fps.ToString()
  281. << "\n";
  282. }
  283. int sent_width = sent_width_counter_.Avg(kMinRequiredMetricsSamples);
  284. int sent_height = sent_height_counter_.Avg(kMinRequiredMetricsSamples);
  285. if (sent_width != -1) {
  286. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "SentWidthInPixels",
  287. sent_width);
  288. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "SentHeightInPixels",
  289. sent_height);
  290. log_stream << uma_prefix_ << "SentWidthInPixels " << sent_width << "\n"
  291. << uma_prefix_ << "SentHeightInPixels " << sent_height << "\n";
  292. }
  293. AggregatedStats sent_fps = sent_fps_counter_.GetStats();
  294. if (sent_fps.num_samples >= kMinRequiredPeriodicSamples) {
  295. RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "SentFramesPerSecond",
  296. sent_fps.average);
  297. log_stream << uma_prefix_ << "SentFramesPerSecond " << sent_fps.ToString()
  298. << "\n";
  299. }
  300. if (in_fps.num_samples > kMinRequiredPeriodicSamples &&
  301. sent_fps.num_samples >= kMinRequiredPeriodicSamples) {
  302. int in_fps_avg = in_fps.average;
  303. if (in_fps_avg > 0) {
  304. int sent_fps_avg = sent_fps.average;
  305. int sent_to_in_fps_ratio_percent =
  306. (100 * sent_fps_avg + in_fps_avg / 2) / in_fps_avg;
  307. // If reported period is small, it may happen that sent_fps is larger than
  308. // input_fps briefly on average. This should be treated as 100% sent to
  309. // input ratio.
  310. if (sent_to_in_fps_ratio_percent > 100)
  311. sent_to_in_fps_ratio_percent = 100;
  312. RTC_HISTOGRAMS_PERCENTAGE(kIndex,
  313. uma_prefix_ + "SentToInputFpsRatioPercent",
  314. sent_to_in_fps_ratio_percent);
  315. log_stream << uma_prefix_ << "SentToInputFpsRatioPercent "
  316. << sent_to_in_fps_ratio_percent << "\n";
  317. }
  318. }
  319. int encode_ms = encode_time_counter_.Avg(kMinRequiredMetricsSamples);
  320. if (encode_ms != -1) {
  321. RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "EncodeTimeInMs",
  322. encode_ms);
  323. log_stream << uma_prefix_ << "EncodeTimeInMs " << encode_ms << "\n";
  324. }
  325. int key_frames_permille =
  326. key_frame_counter_.Permille(kMinRequiredMetricsSamples);
  327. if (key_frames_permille != -1) {
  328. RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "KeyFramesSentInPermille",
  329. key_frames_permille);
  330. log_stream << uma_prefix_ << "KeyFramesSentInPermille "
  331. << key_frames_permille << "\n";
  332. }
  333. int quality_limited =
  334. quality_limited_frame_counter_.Percent(kMinRequiredMetricsSamples);
  335. if (quality_limited != -1) {
  336. RTC_HISTOGRAMS_PERCENTAGE(kIndex,
  337. uma_prefix_ + "QualityLimitedResolutionInPercent",
  338. quality_limited);
  339. log_stream << uma_prefix_ << "QualityLimitedResolutionInPercent "
  340. << quality_limited << "\n";
  341. }
  342. int downscales = quality_downscales_counter_.Avg(kMinRequiredMetricsSamples);
  343. if (downscales != -1) {
  344. RTC_HISTOGRAMS_ENUMERATION(
  345. kIndex, uma_prefix_ + "QualityLimitedResolutionDownscales", downscales,
  346. 20);
  347. }
  348. int cpu_limited =
  349. cpu_limited_frame_counter_.Percent(kMinRequiredMetricsSamples);
  350. if (cpu_limited != -1) {
  351. RTC_HISTOGRAMS_PERCENTAGE(
  352. kIndex, uma_prefix_ + "CpuLimitedResolutionInPercent", cpu_limited);
  353. }
  354. int bw_limited =
  355. bw_limited_frame_counter_.Percent(kMinRequiredMetricsSamples);
  356. if (bw_limited != -1) {
  357. RTC_HISTOGRAMS_PERCENTAGE(
  358. kIndex, uma_prefix_ + "BandwidthLimitedResolutionInPercent",
  359. bw_limited);
  360. }
  361. int num_disabled =
  362. bw_resolutions_disabled_counter_.Avg(kMinRequiredMetricsSamples);
  363. if (num_disabled != -1) {
  364. RTC_HISTOGRAMS_ENUMERATION(
  365. kIndex, uma_prefix_ + "BandwidthLimitedResolutionsDisabled",
  366. num_disabled, 10);
  367. }
  368. int delay_ms = delay_counter_.Avg(kMinRequiredMetricsSamples);
  369. if (delay_ms != -1)
  370. RTC_HISTOGRAMS_COUNTS_100000(kIndex, uma_prefix_ + "SendSideDelayInMs",
  371. delay_ms);
  372. int max_delay_ms = max_delay_counter_.Avg(kMinRequiredMetricsSamples);
  373. if (max_delay_ms != -1) {
  374. RTC_HISTOGRAMS_COUNTS_100000(kIndex, uma_prefix_ + "SendSideDelayMaxInMs",
  375. max_delay_ms);
  376. }
  377. for (const auto& it : qp_counters_) {
  378. int qp_vp8 = it.second.vp8.Avg(kMinRequiredMetricsSamples);
  379. if (qp_vp8 != -1) {
  380. int spatial_idx = it.first;
  381. if (spatial_idx == -1) {
  382. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8",
  383. qp_vp8);
  384. } else if (spatial_idx == 0) {
  385. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8.S0",
  386. qp_vp8);
  387. } else if (spatial_idx == 1) {
  388. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8.S1",
  389. qp_vp8);
  390. } else if (spatial_idx == 2) {
  391. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.Vp8.S2",
  392. qp_vp8);
  393. } else {
  394. RTC_LOG(LS_WARNING)
  395. << "QP stats not recorded for VP8 spatial idx " << spatial_idx;
  396. }
  397. }
  398. int qp_vp9 = it.second.vp9.Avg(kMinRequiredMetricsSamples);
  399. if (qp_vp9 != -1) {
  400. int spatial_idx = it.first;
  401. if (spatial_idx == -1) {
  402. RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9",
  403. qp_vp9);
  404. } else if (spatial_idx == 0) {
  405. RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9.S0",
  406. qp_vp9);
  407. } else if (spatial_idx == 1) {
  408. RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9.S1",
  409. qp_vp9);
  410. } else if (spatial_idx == 2) {
  411. RTC_HISTOGRAMS_COUNTS_500(kIndex, uma_prefix_ + "Encoded.Qp.Vp9.S2",
  412. qp_vp9);
  413. } else {
  414. RTC_LOG(LS_WARNING)
  415. << "QP stats not recorded for VP9 spatial layer " << spatial_idx;
  416. }
  417. }
  418. int qp_h264 = it.second.h264.Avg(kMinRequiredMetricsSamples);
  419. if (qp_h264 != -1) {
  420. int spatial_idx = it.first;
  421. if (spatial_idx == -1) {
  422. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264",
  423. qp_h264);
  424. } else if (spatial_idx == 0) {
  425. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264.S0",
  426. qp_h264);
  427. } else if (spatial_idx == 1) {
  428. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264.S1",
  429. qp_h264);
  430. } else if (spatial_idx == 2) {
  431. RTC_HISTOGRAMS_COUNTS_200(kIndex, uma_prefix_ + "Encoded.Qp.H264.S2",
  432. qp_h264);
  433. } else {
  434. RTC_LOG(LS_WARNING)
  435. << "QP stats not recorded for H264 spatial idx " << spatial_idx;
  436. }
  437. }
  438. }
  439. if (first_rtp_stats_time_ms_ != -1) {
  440. quality_adapt_timer_.Stop(clock_->TimeInMilliseconds());
  441. int64_t elapsed_sec = quality_adapt_timer_.total_ms / 1000;
  442. if (elapsed_sec >= metrics::kMinRunTimeInSeconds) {
  443. int quality_changes = current_stats.number_of_quality_adapt_changes -
  444. start_stats_.number_of_quality_adapt_changes;
  445. // Only base stats on changes during a call, discard initial changes.
  446. int initial_changes =
  447. initial_quality_changes_.down + initial_quality_changes_.up;
  448. if (initial_changes <= quality_changes)
  449. quality_changes -= initial_changes;
  450. RTC_HISTOGRAMS_COUNTS_100(kIndex,
  451. uma_prefix_ + "AdaptChangesPerMinute.Quality",
  452. quality_changes * 60 / elapsed_sec);
  453. }
  454. cpu_adapt_timer_.Stop(clock_->TimeInMilliseconds());
  455. elapsed_sec = cpu_adapt_timer_.total_ms / 1000;
  456. if (elapsed_sec >= metrics::kMinRunTimeInSeconds) {
  457. int cpu_changes = current_stats.number_of_cpu_adapt_changes -
  458. start_stats_.number_of_cpu_adapt_changes;
  459. RTC_HISTOGRAMS_COUNTS_100(kIndex,
  460. uma_prefix_ + "AdaptChangesPerMinute.Cpu",
  461. cpu_changes * 60 / elapsed_sec);
  462. }
  463. }
  464. if (first_rtcp_stats_time_ms_ != -1) {
  465. int64_t elapsed_sec =
  466. (clock_->TimeInMilliseconds() - first_rtcp_stats_time_ms_) / 1000;
  467. if (elapsed_sec >= metrics::kMinRunTimeInSeconds) {
  468. int fraction_lost = report_block_stats_.FractionLostInPercent();
  469. if (fraction_lost != -1) {
  470. RTC_HISTOGRAMS_PERCENTAGE(
  471. kIndex, uma_prefix_ + "SentPacketsLostInPercent", fraction_lost);
  472. log_stream << uma_prefix_ << "SentPacketsLostInPercent "
  473. << fraction_lost << "\n";
  474. }
  475. // The RTCP packet type counters, delivered via the
  476. // RtcpPacketTypeCounterObserver interface, are aggregates over the entire
  477. // life of the send stream and are not reset when switching content type.
  478. // For the purpose of these statistics though, we want new counts when
  479. // switching since we switch histogram name. On every reset of the
  480. // UmaSamplesContainer, we save the initial state of the counters, so that
  481. // we can calculate the delta here and aggregate over all ssrcs.
  482. RtcpPacketTypeCounter counters;
  483. for (uint32_t ssrc : rtp_config.ssrcs) {
  484. auto kv = current_stats.substreams.find(ssrc);
  485. if (kv == current_stats.substreams.end())
  486. continue;
  487. RtcpPacketTypeCounter stream_counters =
  488. kv->second.rtcp_packet_type_counts;
  489. kv = start_stats_.substreams.find(ssrc);
  490. if (kv != start_stats_.substreams.end())
  491. stream_counters.Subtract(kv->second.rtcp_packet_type_counts);
  492. counters.Add(stream_counters);
  493. }
  494. RTC_HISTOGRAMS_COUNTS_10000(kIndex,
  495. uma_prefix_ + "NackPacketsReceivedPerMinute",
  496. counters.nack_packets * 60 / elapsed_sec);
  497. RTC_HISTOGRAMS_COUNTS_10000(kIndex,
  498. uma_prefix_ + "FirPacketsReceivedPerMinute",
  499. counters.fir_packets * 60 / elapsed_sec);
  500. RTC_HISTOGRAMS_COUNTS_10000(kIndex,
  501. uma_prefix_ + "PliPacketsReceivedPerMinute",
  502. counters.pli_packets * 60 / elapsed_sec);
  503. if (counters.nack_requests > 0) {
  504. RTC_HISTOGRAMS_PERCENTAGE(
  505. kIndex, uma_prefix_ + "UniqueNackRequestsReceivedInPercent",
  506. counters.UniqueNackRequestsInPercent());
  507. }
  508. }
  509. }
  510. if (first_rtp_stats_time_ms_ != -1) {
  511. int64_t elapsed_sec =
  512. (clock_->TimeInMilliseconds() - first_rtp_stats_time_ms_) / 1000;
  513. if (elapsed_sec >= metrics::kMinRunTimeInSeconds) {
  514. RTC_HISTOGRAMS_COUNTS_100(kIndex, uma_prefix_ + "NumberOfPauseEvents",
  515. target_rate_updates_.pause_resume_events);
  516. log_stream << uma_prefix_ << "NumberOfPauseEvents "
  517. << target_rate_updates_.pause_resume_events << "\n";
  518. int paused_time_percent =
  519. paused_time_counter_.Percent(metrics::kMinRunTimeInSeconds * 1000);
  520. if (paused_time_percent != -1) {
  521. RTC_HISTOGRAMS_PERCENTAGE(kIndex, uma_prefix_ + "PausedTimeInPercent",
  522. paused_time_percent);
  523. log_stream << uma_prefix_ << "PausedTimeInPercent "
  524. << paused_time_percent << "\n";
  525. }
  526. }
  527. }
  528. if (fallback_info_.is_possible) {
  529. // Double interval since there is some time before fallback may occur.
  530. const int kMinRunTimeMs = 2 * metrics::kMinRunTimeInSeconds * 1000;
  531. int64_t elapsed_ms = fallback_info_.elapsed_ms;
  532. int fallback_time_percent = fallback_active_counter_.Percent(kMinRunTimeMs);
  533. if (fallback_time_percent != -1 && elapsed_ms >= kMinRunTimeMs) {
  534. RTC_HISTOGRAMS_PERCENTAGE(
  535. kIndex, uma_prefix_ + "Encoder.ForcedSwFallbackTimeInPercent.Vp8",
  536. fallback_time_percent);
  537. RTC_HISTOGRAMS_COUNTS_100(
  538. kIndex, uma_prefix_ + "Encoder.ForcedSwFallbackChangesPerMinute.Vp8",
  539. fallback_info_.on_off_events * 60 / (elapsed_ms / 1000));
  540. }
  541. }
  542. AggregatedStats total_bytes_per_sec = total_byte_counter_.GetStats();
  543. if (total_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  544. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "BitrateSentInKbps",
  545. total_bytes_per_sec.average * 8 / 1000);
  546. log_stream << uma_prefix_ << "BitrateSentInBps "
  547. << total_bytes_per_sec.ToStringWithMultiplier(8) << "\n";
  548. }
  549. AggregatedStats media_bytes_per_sec = media_byte_counter_.GetStats();
  550. if (media_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  551. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "MediaBitrateSentInKbps",
  552. media_bytes_per_sec.average * 8 / 1000);
  553. log_stream << uma_prefix_ << "MediaBitrateSentInBps "
  554. << media_bytes_per_sec.ToStringWithMultiplier(8) << "\n";
  555. }
  556. AggregatedStats padding_bytes_per_sec = padding_byte_counter_.GetStats();
  557. if (padding_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  558. RTC_HISTOGRAMS_COUNTS_10000(kIndex,
  559. uma_prefix_ + "PaddingBitrateSentInKbps",
  560. padding_bytes_per_sec.average * 8 / 1000);
  561. log_stream << uma_prefix_ << "PaddingBitrateSentInBps "
  562. << padding_bytes_per_sec.ToStringWithMultiplier(8) << "\n";
  563. }
  564. AggregatedStats retransmit_bytes_per_sec =
  565. retransmit_byte_counter_.GetStats();
  566. if (retransmit_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  567. RTC_HISTOGRAMS_COUNTS_10000(kIndex,
  568. uma_prefix_ + "RetransmittedBitrateSentInKbps",
  569. retransmit_bytes_per_sec.average * 8 / 1000);
  570. log_stream << uma_prefix_ << "RetransmittedBitrateSentInBps "
  571. << retransmit_bytes_per_sec.ToStringWithMultiplier(8) << "\n";
  572. }
  573. if (!rtp_config.rtx.ssrcs.empty()) {
  574. AggregatedStats rtx_bytes_per_sec = rtx_byte_counter_.GetStats();
  575. int rtx_bytes_per_sec_avg = -1;
  576. if (rtx_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  577. rtx_bytes_per_sec_avg = rtx_bytes_per_sec.average;
  578. log_stream << uma_prefix_ << "RtxBitrateSentInBps "
  579. << rtx_bytes_per_sec.ToStringWithMultiplier(8) << "\n";
  580. } else if (total_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  581. rtx_bytes_per_sec_avg = 0; // RTX enabled but no RTX data sent, record 0.
  582. }
  583. if (rtx_bytes_per_sec_avg != -1) {
  584. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "RtxBitrateSentInKbps",
  585. rtx_bytes_per_sec_avg * 8 / 1000);
  586. }
  587. }
  588. if (rtp_config.flexfec.payload_type != -1 ||
  589. rtp_config.ulpfec.red_payload_type != -1) {
  590. AggregatedStats fec_bytes_per_sec = fec_byte_counter_.GetStats();
  591. if (fec_bytes_per_sec.num_samples > kMinRequiredPeriodicSamples) {
  592. RTC_HISTOGRAMS_COUNTS_10000(kIndex, uma_prefix_ + "FecBitrateSentInKbps",
  593. fec_bytes_per_sec.average * 8 / 1000);
  594. log_stream << uma_prefix_ << "FecBitrateSentInBps "
  595. << fec_bytes_per_sec.ToStringWithMultiplier(8) << "\n";
  596. }
  597. }
  598. log_stream << "Frames encoded " << current_stats.frames_encoded << "\n"
  599. << uma_prefix_ << "DroppedFrames.Capturer "
  600. << current_stats.frames_dropped_by_capturer << "\n";
  601. RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.Capturer",
  602. current_stats.frames_dropped_by_capturer);
  603. log_stream << uma_prefix_ << "DroppedFrames.EncoderQueue "
  604. << current_stats.frames_dropped_by_encoder_queue << "\n";
  605. RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.EncoderQueue",
  606. current_stats.frames_dropped_by_encoder_queue);
  607. log_stream << uma_prefix_ << "DroppedFrames.Encoder "
  608. << current_stats.frames_dropped_by_encoder << "\n";
  609. RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.Encoder",
  610. current_stats.frames_dropped_by_encoder);
  611. log_stream << uma_prefix_ << "DroppedFrames.Ratelimiter "
  612. << current_stats.frames_dropped_by_rate_limiter;
  613. RTC_HISTOGRAMS_COUNTS_1000(kIndex, uma_prefix_ + "DroppedFrames.Ratelimiter",
  614. current_stats.frames_dropped_by_rate_limiter);
  615. RTC_LOG(LS_INFO) << log_stream.str();
  616. }
  617. void SendStatisticsProxy::OnEncoderReconfigured(
  618. const VideoEncoderConfig& config,
  619. const std::vector<VideoStream>& streams) {
  620. rtc::CritScope lock(&crit_);
  621. if (content_type_ != config.content_type) {
  622. uma_container_->UpdateHistograms(rtp_config_, stats_);
  623. uma_container_.reset(new UmaSamplesContainer(
  624. GetUmaPrefix(config.content_type), stats_, clock_));
  625. content_type_ = config.content_type;
  626. }
  627. uma_container_->encoded_frames_.clear();
  628. uma_container_->num_streams_ = streams.size();
  629. uma_container_->num_pixels_highest_stream_ =
  630. streams.empty() ? 0 : (streams.back().width * streams.back().height);
  631. }
  632. void SendStatisticsProxy::OnEncodedFrameTimeMeasured(int encode_time_ms,
  633. int encode_usage_percent) {
  634. RTC_DCHECK_GE(encode_time_ms, 0);
  635. rtc::CritScope lock(&crit_);
  636. uma_container_->encode_time_counter_.Add(encode_time_ms);
  637. encode_time_.Apply(1.0f, encode_time_ms);
  638. stats_.avg_encode_time_ms = std::round(encode_time_.filtered());
  639. stats_.total_encode_time_ms += encode_time_ms;
  640. stats_.encode_usage_percent = encode_usage_percent;
  641. }
  642. void SendStatisticsProxy::OnSuspendChange(bool is_suspended) {
  643. int64_t now_ms = clock_->TimeInMilliseconds();
  644. rtc::CritScope lock(&crit_);
  645. stats_.suspended = is_suspended;
  646. if (is_suspended) {
  647. // Pause framerate (add min pause time since there may be frames/packets
  648. // that are not yet sent).
  649. const int64_t kMinMs = 500;
  650. uma_container_->input_fps_counter_.ProcessAndPauseForDuration(kMinMs);
  651. uma_container_->sent_fps_counter_.ProcessAndPauseForDuration(kMinMs);
  652. // Pause bitrate stats.
  653. uma_container_->total_byte_counter_.ProcessAndPauseForDuration(kMinMs);
  654. uma_container_->media_byte_counter_.ProcessAndPauseForDuration(kMinMs);
  655. uma_container_->rtx_byte_counter_.ProcessAndPauseForDuration(kMinMs);
  656. uma_container_->padding_byte_counter_.ProcessAndPauseForDuration(kMinMs);
  657. uma_container_->retransmit_byte_counter_.ProcessAndPauseForDuration(kMinMs);
  658. uma_container_->fec_byte_counter_.ProcessAndPauseForDuration(kMinMs);
  659. // Stop adaptation stats.
  660. uma_container_->cpu_adapt_timer_.Stop(now_ms);
  661. uma_container_->quality_adapt_timer_.Stop(now_ms);
  662. } else {
  663. // Start adaptation stats if scaling is enabled.
  664. if (cpu_downscales_ >= 0)
  665. uma_container_->cpu_adapt_timer_.Start(now_ms);
  666. if (quality_downscales_ >= 0)
  667. uma_container_->quality_adapt_timer_.Start(now_ms);
  668. // Stop pause explicitly for stats that may be zero/not updated for some
  669. // time.
  670. uma_container_->rtx_byte_counter_.ProcessAndStopPause();
  671. uma_container_->padding_byte_counter_.ProcessAndStopPause();
  672. uma_container_->retransmit_byte_counter_.ProcessAndStopPause();
  673. uma_container_->fec_byte_counter_.ProcessAndStopPause();
  674. }
  675. }
  676. VideoSendStream::Stats SendStatisticsProxy::GetStats() {
  677. rtc::CritScope lock(&crit_);
  678. PurgeOldStats();
  679. stats_.input_frame_rate =
  680. round(uma_container_->input_frame_rate_tracker_.ComputeRate());
  681. stats_.content_type =
  682. content_type_ == VideoEncoderConfig::ContentType::kRealtimeVideo
  683. ? VideoContentType::UNSPECIFIED
  684. : VideoContentType::SCREENSHARE;
  685. stats_.encode_frame_rate = round(encoded_frame_rate_tracker_.ComputeRate());
  686. stats_.media_bitrate_bps = media_byte_rate_tracker_.ComputeRate() * 8;
  687. stats_.quality_limitation_durations_ms =
  688. quality_limitation_reason_tracker_.DurationsMs();
  689. return stats_;
  690. }
  691. void SendStatisticsProxy::PurgeOldStats() {
  692. int64_t old_stats_ms = clock_->TimeInMilliseconds() - kStatsTimeoutMs;
  693. for (std::map<uint32_t, VideoSendStream::StreamStats>::iterator it =
  694. stats_.substreams.begin();
  695. it != stats_.substreams.end(); ++it) {
  696. uint32_t ssrc = it->first;
  697. if (update_times_[ssrc].resolution_update_ms <= old_stats_ms) {
  698. it->second.width = 0;
  699. it->second.height = 0;
  700. }
  701. }
  702. }
  703. VideoSendStream::StreamStats* SendStatisticsProxy::GetStatsEntry(
  704. uint32_t ssrc) {
  705. std::map<uint32_t, VideoSendStream::StreamStats>::iterator it =
  706. stats_.substreams.find(ssrc);
  707. if (it != stats_.substreams.end())
  708. return &it->second;
  709. bool is_media = absl::c_linear_search(rtp_config_.ssrcs, ssrc);
  710. bool is_flexfec = rtp_config_.flexfec.payload_type != -1 &&
  711. ssrc == rtp_config_.flexfec.ssrc;
  712. bool is_rtx = absl::c_linear_search(rtp_config_.rtx.ssrcs, ssrc);
  713. if (!is_media && !is_flexfec && !is_rtx)
  714. return nullptr;
  715. // Insert new entry and return ptr.
  716. VideoSendStream::StreamStats* entry = &stats_.substreams[ssrc];
  717. entry->is_rtx = is_rtx;
  718. entry->is_flexfec = is_flexfec;
  719. return entry;
  720. }
  721. void SendStatisticsProxy::OnInactiveSsrc(uint32_t ssrc) {
  722. rtc::CritScope lock(&crit_);
  723. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  724. if (!stats)
  725. return;
  726. stats->total_bitrate_bps = 0;
  727. stats->retransmit_bitrate_bps = 0;
  728. stats->height = 0;
  729. stats->width = 0;
  730. }
  731. void SendStatisticsProxy::OnSetEncoderTargetRate(uint32_t bitrate_bps) {
  732. rtc::CritScope lock(&crit_);
  733. if (uma_container_->target_rate_updates_.last_ms == -1 && bitrate_bps == 0)
  734. return; // Start on first non-zero bitrate, may initially be zero.
  735. int64_t now = clock_->TimeInMilliseconds();
  736. if (uma_container_->target_rate_updates_.last_ms != -1) {
  737. bool was_paused = stats_.target_media_bitrate_bps == 0;
  738. int64_t diff_ms = now - uma_container_->target_rate_updates_.last_ms;
  739. uma_container_->paused_time_counter_.Add(was_paused, diff_ms);
  740. // Use last to not include update when stream is stopped and video disabled.
  741. if (uma_container_->target_rate_updates_.last_paused_or_resumed)
  742. ++uma_container_->target_rate_updates_.pause_resume_events;
  743. // Check if video is paused/resumed.
  744. uma_container_->target_rate_updates_.last_paused_or_resumed =
  745. (bitrate_bps == 0) != was_paused;
  746. }
  747. uma_container_->target_rate_updates_.last_ms = now;
  748. stats_.target_media_bitrate_bps = bitrate_bps;
  749. }
  750. void SendStatisticsProxy::UpdateEncoderFallbackStats(
  751. const CodecSpecificInfo* codec_info,
  752. int pixels,
  753. int simulcast_index) {
  754. UpdateFallbackDisabledStats(codec_info, pixels, simulcast_index);
  755. if (!fallback_max_pixels_ || !uma_container_->fallback_info_.is_possible) {
  756. return;
  757. }
  758. if (!IsForcedFallbackPossible(codec_info, simulcast_index)) {
  759. uma_container_->fallback_info_.is_possible = false;
  760. return;
  761. }
  762. FallbackEncoderInfo* fallback_info = &uma_container_->fallback_info_;
  763. const int64_t now_ms = clock_->TimeInMilliseconds();
  764. bool is_active = fallback_info->is_active;
  765. if (encoder_changed_) {
  766. // Implementation changed.
  767. const bool last_was_vp8_software =
  768. encoder_changed_->previous_encoder_implementation == kVp8SwCodecName;
  769. is_active = encoder_changed_->new_encoder_implementation == kVp8SwCodecName;
  770. encoder_changed_.reset();
  771. if (!is_active && !last_was_vp8_software) {
  772. // First or not a VP8 SW change, update stats on next call.
  773. return;
  774. }
  775. if (is_active && (pixels > *fallback_max_pixels_)) {
  776. // Pixels should not be above |fallback_max_pixels_|. If above skip to
  777. // avoid fallbacks due to failure.
  778. fallback_info->is_possible = false;
  779. return;
  780. }
  781. stats_.has_entered_low_resolution = true;
  782. ++fallback_info->on_off_events;
  783. }
  784. if (fallback_info->last_update_ms) {
  785. int64_t diff_ms = now_ms - *(fallback_info->last_update_ms);
  786. // If the time diff since last update is greater than |max_frame_diff_ms|,
  787. // video is considered paused/muted and the change is not included.
  788. if (diff_ms < fallback_info->max_frame_diff_ms) {
  789. uma_container_->fallback_active_counter_.Add(fallback_info->is_active,
  790. diff_ms);
  791. fallback_info->elapsed_ms += diff_ms;
  792. }
  793. }
  794. fallback_info->is_active = is_active;
  795. fallback_info->last_update_ms.emplace(now_ms);
  796. }
  797. void SendStatisticsProxy::UpdateFallbackDisabledStats(
  798. const CodecSpecificInfo* codec_info,
  799. int pixels,
  800. int simulcast_index) {
  801. if (!fallback_max_pixels_disabled_ ||
  802. !uma_container_->fallback_info_disabled_.is_possible ||
  803. stats_.has_entered_low_resolution) {
  804. return;
  805. }
  806. if (!IsForcedFallbackPossible(codec_info, simulcast_index) ||
  807. stats_.encoder_implementation_name == kVp8SwCodecName) {
  808. uma_container_->fallback_info_disabled_.is_possible = false;
  809. return;
  810. }
  811. if (pixels <= *fallback_max_pixels_disabled_ ||
  812. uma_container_->fallback_info_disabled_.min_pixel_limit_reached) {
  813. stats_.has_entered_low_resolution = true;
  814. }
  815. }
  816. void SendStatisticsProxy::OnMinPixelLimitReached() {
  817. rtc::CritScope lock(&crit_);
  818. uma_container_->fallback_info_disabled_.min_pixel_limit_reached = true;
  819. }
  820. void SendStatisticsProxy::OnSendEncodedImage(
  821. const EncodedImage& encoded_image,
  822. const CodecSpecificInfo* codec_info) {
  823. // Simulcast is used for VP8, H264 and Generic.
  824. int simulcast_idx =
  825. (codec_info && (codec_info->codecType == kVideoCodecVP8 ||
  826. codec_info->codecType == kVideoCodecH264 ||
  827. codec_info->codecType == kVideoCodecGeneric))
  828. ? encoded_image.SpatialIndex().value_or(0)
  829. : 0;
  830. rtc::CritScope lock(&crit_);
  831. ++stats_.frames_encoded;
  832. // The current encode frame rate is based on previously encoded frames.
  833. double encode_frame_rate = encoded_frame_rate_tracker_.ComputeRate();
  834. // We assume that less than 1 FPS is not a trustworthy estimate - perhaps we
  835. // just started encoding for the first time or after a pause. Assuming frame
  836. // rate is at least 1 FPS is conservative to avoid too large increments.
  837. if (encode_frame_rate < 1.0)
  838. encode_frame_rate = 1.0;
  839. double target_frame_size_bytes =
  840. stats_.target_media_bitrate_bps / (8.0 * encode_frame_rate);
  841. // |stats_.target_media_bitrate_bps| is set in
  842. // SendStatisticsProxy::OnSetEncoderTargetRate.
  843. stats_.total_encoded_bytes_target += round(target_frame_size_bytes);
  844. if (codec_info) {
  845. UpdateEncoderFallbackStats(
  846. codec_info, encoded_image._encodedWidth * encoded_image._encodedHeight,
  847. simulcast_idx);
  848. }
  849. if (static_cast<size_t>(simulcast_idx) >= rtp_config_.ssrcs.size()) {
  850. RTC_LOG(LS_ERROR) << "Encoded image outside simulcast range ("
  851. << simulcast_idx << " >= " << rtp_config_.ssrcs.size()
  852. << ").";
  853. return;
  854. }
  855. uint32_t ssrc = rtp_config_.ssrcs[simulcast_idx];
  856. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  857. if (!stats)
  858. return;
  859. // Report resolution of top spatial layer in case of VP9 SVC.
  860. bool is_svc_low_spatial_layer =
  861. (codec_info && codec_info->codecType == kVideoCodecVP9)
  862. ? !codec_info->codecSpecific.VP9.end_of_picture
  863. : false;
  864. if (!stats->width || !stats->height || !is_svc_low_spatial_layer) {
  865. stats->width = encoded_image._encodedWidth;
  866. stats->height = encoded_image._encodedHeight;
  867. update_times_[ssrc].resolution_update_ms = clock_->TimeInMilliseconds();
  868. }
  869. uma_container_->key_frame_counter_.Add(encoded_image._frameType ==
  870. VideoFrameType::kVideoFrameKey);
  871. if (encoded_image.qp_ != -1) {
  872. if (!stats_.qp_sum)
  873. stats_.qp_sum = 0;
  874. *stats_.qp_sum += encoded_image.qp_;
  875. if (codec_info) {
  876. if (codec_info->codecType == kVideoCodecVP8) {
  877. int spatial_idx = (rtp_config_.ssrcs.size() == 1) ? -1 : simulcast_idx;
  878. uma_container_->qp_counters_[spatial_idx].vp8.Add(encoded_image.qp_);
  879. } else if (codec_info->codecType == kVideoCodecVP9) {
  880. int spatial_idx = encoded_image.SpatialIndex().value_or(-1);
  881. uma_container_->qp_counters_[spatial_idx].vp9.Add(encoded_image.qp_);
  882. } else if (codec_info->codecType == kVideoCodecH264) {
  883. int spatial_idx = (rtp_config_.ssrcs.size() == 1) ? -1 : simulcast_idx;
  884. uma_container_->qp_counters_[spatial_idx].h264.Add(encoded_image.qp_);
  885. }
  886. }
  887. }
  888. // If any of the simulcast streams have a huge frame, it should be counted
  889. // as a single difficult input frame.
  890. // https://w3c.github.io/webrtc-stats/#dom-rtcvideosenderstats-hugeframessent
  891. if (encoded_image.timing_.flags & VideoSendTiming::kTriggeredBySize) {
  892. if (!last_outlier_timestamp_ ||
  893. *last_outlier_timestamp_ < encoded_image.capture_time_ms_) {
  894. last_outlier_timestamp_.emplace(encoded_image.capture_time_ms_);
  895. ++stats_.huge_frames_sent;
  896. }
  897. }
  898. media_byte_rate_tracker_.AddSamples(encoded_image.size());
  899. // Initialize to current since |is_limited_in_resolution| is only updated
  900. // when an encoded frame is removed from the EncodedFrameMap.
  901. bool is_limited_in_resolution = stats_.bw_limited_resolution;
  902. if (uma_container_->InsertEncodedFrame(encoded_image, simulcast_idx,
  903. &is_limited_in_resolution)) {
  904. encoded_frame_rate_tracker_.AddSamples(1);
  905. }
  906. stats_.bw_limited_resolution =
  907. is_limited_in_resolution || quality_downscales_ > 0;
  908. if (quality_downscales_ != -1) {
  909. uma_container_->quality_limited_frame_counter_.Add(quality_downscales_ > 0);
  910. if (quality_downscales_ > 0)
  911. uma_container_->quality_downscales_counter_.Add(quality_downscales_);
  912. }
  913. }
  914. void SendStatisticsProxy::OnEncoderImplementationChanged(
  915. const std::string& implementation_name) {
  916. rtc::CritScope lock(&crit_);
  917. encoder_changed_ = EncoderChangeEvent{stats_.encoder_implementation_name,
  918. implementation_name};
  919. stats_.encoder_implementation_name = implementation_name;
  920. }
  921. int SendStatisticsProxy::GetInputFrameRate() const {
  922. rtc::CritScope lock(&crit_);
  923. return round(uma_container_->input_frame_rate_tracker_.ComputeRate());
  924. }
  925. int SendStatisticsProxy::GetSendFrameRate() const {
  926. rtc::CritScope lock(&crit_);
  927. return round(encoded_frame_rate_tracker_.ComputeRate());
  928. }
  929. void SendStatisticsProxy::OnIncomingFrame(int width, int height) {
  930. rtc::CritScope lock(&crit_);
  931. uma_container_->input_frame_rate_tracker_.AddSamples(1);
  932. uma_container_->input_fps_counter_.Add(1);
  933. uma_container_->input_width_counter_.Add(width);
  934. uma_container_->input_height_counter_.Add(height);
  935. if (cpu_downscales_ >= 0) {
  936. uma_container_->cpu_limited_frame_counter_.Add(
  937. stats_.cpu_limited_resolution);
  938. }
  939. if (encoded_frame_rate_tracker_.TotalSampleCount() == 0) {
  940. // Set start time now instead of when first key frame is encoded to avoid a
  941. // too high initial estimate.
  942. encoded_frame_rate_tracker_.AddSamples(0);
  943. }
  944. }
  945. void SendStatisticsProxy::OnFrameDropped(DropReason reason) {
  946. rtc::CritScope lock(&crit_);
  947. switch (reason) {
  948. case DropReason::kSource:
  949. ++stats_.frames_dropped_by_capturer;
  950. break;
  951. case DropReason::kEncoderQueue:
  952. ++stats_.frames_dropped_by_encoder_queue;
  953. break;
  954. case DropReason::kEncoder:
  955. ++stats_.frames_dropped_by_encoder;
  956. break;
  957. case DropReason::kMediaOptimization:
  958. ++stats_.frames_dropped_by_rate_limiter;
  959. break;
  960. }
  961. }
  962. void SendStatisticsProxy::OnAdaptationChanged(
  963. AdaptationReason reason,
  964. const AdaptationSteps& cpu_counts,
  965. const AdaptationSteps& quality_counts) {
  966. rtc::CritScope lock(&crit_);
  967. switch (reason) {
  968. case AdaptationReason::kNone:
  969. SetAdaptTimer(cpu_counts, &uma_container_->cpu_adapt_timer_);
  970. SetAdaptTimer(quality_counts, &uma_container_->quality_adapt_timer_);
  971. break;
  972. case AdaptationReason::kCpu:
  973. ++stats_.number_of_cpu_adapt_changes;
  974. break;
  975. case AdaptationReason::kQuality:
  976. TryUpdateInitialQualityResolutionAdaptUp(quality_counts);
  977. ++stats_.number_of_quality_adapt_changes;
  978. break;
  979. }
  980. cpu_downscales_ = cpu_counts.num_resolution_reductions.value_or(-1);
  981. quality_downscales_ = quality_counts.num_resolution_reductions.value_or(-1);
  982. cpu_counts_ = cpu_counts;
  983. quality_counts_ = quality_counts;
  984. UpdateAdaptationStats();
  985. }
  986. void SendStatisticsProxy::UpdateAdaptationStats() {
  987. bool is_cpu_limited = cpu_counts_.num_resolution_reductions > 0 ||
  988. cpu_counts_.num_framerate_reductions > 0;
  989. bool is_bandwidth_limited = quality_counts_.num_resolution_reductions > 0 ||
  990. quality_counts_.num_framerate_reductions > 0 ||
  991. bw_limited_layers_;
  992. if (is_bandwidth_limited) {
  993. // We may be both CPU limited and bandwidth limited at the same time but
  994. // there is no way to express this in standardized stats. Heuristically,
  995. // bandwidth is more likely to be a limiting factor than CPU, and more
  996. // likely to vary over time, so only when we aren't bandwidth limited do we
  997. // want to know about our CPU being the bottleneck.
  998. quality_limitation_reason_tracker_.SetReason(
  999. QualityLimitationReason::kBandwidth);
  1000. } else if (is_cpu_limited) {
  1001. quality_limitation_reason_tracker_.SetReason(QualityLimitationReason::kCpu);
  1002. } else {
  1003. quality_limitation_reason_tracker_.SetReason(
  1004. QualityLimitationReason::kNone);
  1005. }
  1006. stats_.cpu_limited_resolution = cpu_counts_.num_resolution_reductions > 0;
  1007. stats_.cpu_limited_framerate = cpu_counts_.num_framerate_reductions > 0;
  1008. stats_.bw_limited_resolution = quality_counts_.num_resolution_reductions > 0;
  1009. stats_.bw_limited_framerate = quality_counts_.num_framerate_reductions > 0;
  1010. // If bitrate allocator has disabled some layers frame-rate or resolution are
  1011. // limited depending on the encoder configuration.
  1012. if (bw_limited_layers_) {
  1013. switch (content_type_) {
  1014. case VideoEncoderConfig::ContentType::kRealtimeVideo: {
  1015. stats_.bw_limited_resolution = true;
  1016. break;
  1017. }
  1018. case VideoEncoderConfig::ContentType::kScreen: {
  1019. stats_.bw_limited_framerate = true;
  1020. break;
  1021. }
  1022. }
  1023. }
  1024. stats_.quality_limitation_reason =
  1025. quality_limitation_reason_tracker_.current_reason();
  1026. // |stats_.quality_limitation_durations_ms| depends on the current time
  1027. // when it is polled; it is updated in SendStatisticsProxy::GetStats().
  1028. }
  1029. void SendStatisticsProxy::OnBitrateAllocationUpdated(
  1030. const VideoCodec& codec,
  1031. const VideoBitrateAllocation& allocation) {
  1032. int num_spatial_layers = 0;
  1033. for (int i = 0; i < kMaxSpatialLayers; i++) {
  1034. if (codec.spatialLayers[i].active) {
  1035. num_spatial_layers++;
  1036. }
  1037. }
  1038. int num_simulcast_streams = 0;
  1039. for (int i = 0; i < kMaxSimulcastStreams; i++) {
  1040. if (codec.simulcastStream[i].active) {
  1041. num_simulcast_streams++;
  1042. }
  1043. }
  1044. std::array<bool, kMaxSpatialLayers> spatial_layers;
  1045. for (int i = 0; i < kMaxSpatialLayers; i++) {
  1046. spatial_layers[i] = (allocation.GetSpatialLayerSum(i) > 0);
  1047. }
  1048. rtc::CritScope lock(&crit_);
  1049. bw_limited_layers_ = allocation.is_bw_limited();
  1050. UpdateAdaptationStats();
  1051. if (spatial_layers != last_spatial_layer_use_) {
  1052. // If the number of spatial layers has changed, the resolution change is
  1053. // not due to quality limitations, it is because the configuration
  1054. // changed.
  1055. if (last_num_spatial_layers_ == num_spatial_layers &&
  1056. last_num_simulcast_streams_ == num_simulcast_streams) {
  1057. ++stats_.quality_limitation_resolution_changes;
  1058. }
  1059. last_spatial_layer_use_ = spatial_layers;
  1060. }
  1061. last_num_spatial_layers_ = num_spatial_layers;
  1062. last_num_simulcast_streams_ = num_simulcast_streams;
  1063. }
  1064. // TODO(asapersson): Include fps changes.
  1065. void SendStatisticsProxy::OnInitialQualityResolutionAdaptDown() {
  1066. rtc::CritScope lock(&crit_);
  1067. ++uma_container_->initial_quality_changes_.down;
  1068. }
  1069. void SendStatisticsProxy::TryUpdateInitialQualityResolutionAdaptUp(
  1070. const AdaptationSteps& quality_counts) {
  1071. if (uma_container_->initial_quality_changes_.down == 0)
  1072. return;
  1073. if (quality_downscales_ > 0 &&
  1074. quality_counts.num_resolution_reductions.value_or(-1) <
  1075. quality_downscales_) {
  1076. // Adapting up in quality.
  1077. if (uma_container_->initial_quality_changes_.down >
  1078. uma_container_->initial_quality_changes_.up) {
  1079. ++uma_container_->initial_quality_changes_.up;
  1080. }
  1081. }
  1082. }
  1083. void SendStatisticsProxy::SetAdaptTimer(const AdaptationSteps& counts,
  1084. StatsTimer* timer) {
  1085. if (counts.num_resolution_reductions || counts.num_framerate_reductions) {
  1086. // Adaptation enabled.
  1087. if (!stats_.suspended)
  1088. timer->Start(clock_->TimeInMilliseconds());
  1089. return;
  1090. }
  1091. timer->Stop(clock_->TimeInMilliseconds());
  1092. }
  1093. void SendStatisticsProxy::RtcpPacketTypesCounterUpdated(
  1094. uint32_t ssrc,
  1095. const RtcpPacketTypeCounter& packet_counter) {
  1096. rtc::CritScope lock(&crit_);
  1097. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  1098. if (!stats)
  1099. return;
  1100. stats->rtcp_packet_type_counts = packet_counter;
  1101. if (uma_container_->first_rtcp_stats_time_ms_ == -1)
  1102. uma_container_->first_rtcp_stats_time_ms_ = clock_->TimeInMilliseconds();
  1103. }
  1104. void SendStatisticsProxy::StatisticsUpdated(const RtcpStatistics& statistics,
  1105. uint32_t ssrc) {
  1106. rtc::CritScope lock(&crit_);
  1107. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  1108. if (!stats)
  1109. return;
  1110. stats->rtcp_stats = statistics;
  1111. uma_container_->report_block_stats_.Store(ssrc, statistics);
  1112. }
  1113. void SendStatisticsProxy::OnReportBlockDataUpdated(
  1114. ReportBlockData report_block_data) {
  1115. rtc::CritScope lock(&crit_);
  1116. VideoSendStream::StreamStats* stats =
  1117. GetStatsEntry(report_block_data.report_block().source_ssrc);
  1118. if (!stats)
  1119. return;
  1120. stats->report_block_data = std::move(report_block_data);
  1121. }
  1122. void SendStatisticsProxy::DataCountersUpdated(
  1123. const StreamDataCounters& counters,
  1124. uint32_t ssrc) {
  1125. rtc::CritScope lock(&crit_);
  1126. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  1127. RTC_DCHECK(stats) << "DataCountersUpdated reported for unknown ssrc " << ssrc;
  1128. if (stats->is_flexfec) {
  1129. // The same counters are reported for both the media ssrc and flexfec ssrc.
  1130. // Bitrate stats are summed for all SSRCs. Use fec stats from media update.
  1131. return;
  1132. }
  1133. stats->rtp_stats = counters;
  1134. if (uma_container_->first_rtp_stats_time_ms_ == -1) {
  1135. int64_t now_ms = clock_->TimeInMilliseconds();
  1136. uma_container_->first_rtp_stats_time_ms_ = now_ms;
  1137. uma_container_->cpu_adapt_timer_.Restart(now_ms);
  1138. uma_container_->quality_adapt_timer_.Restart(now_ms);
  1139. }
  1140. uma_container_->total_byte_counter_.Set(counters.transmitted.TotalBytes(),
  1141. ssrc);
  1142. uma_container_->padding_byte_counter_.Set(counters.transmitted.padding_bytes,
  1143. ssrc);
  1144. uma_container_->retransmit_byte_counter_.Set(
  1145. counters.retransmitted.TotalBytes(), ssrc);
  1146. uma_container_->fec_byte_counter_.Set(counters.fec.TotalBytes(), ssrc);
  1147. if (stats->is_rtx) {
  1148. uma_container_->rtx_byte_counter_.Set(counters.transmitted.TotalBytes(),
  1149. ssrc);
  1150. } else {
  1151. uma_container_->media_byte_counter_.Set(counters.MediaPayloadBytes(), ssrc);
  1152. }
  1153. }
  1154. void SendStatisticsProxy::Notify(uint32_t total_bitrate_bps,
  1155. uint32_t retransmit_bitrate_bps,
  1156. uint32_t ssrc) {
  1157. rtc::CritScope lock(&crit_);
  1158. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  1159. if (!stats)
  1160. return;
  1161. stats->total_bitrate_bps = total_bitrate_bps;
  1162. stats->retransmit_bitrate_bps = retransmit_bitrate_bps;
  1163. }
  1164. void SendStatisticsProxy::FrameCountUpdated(const FrameCounts& frame_counts,
  1165. uint32_t ssrc) {
  1166. rtc::CritScope lock(&crit_);
  1167. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  1168. if (!stats)
  1169. return;
  1170. stats->frame_counts = frame_counts;
  1171. }
  1172. void SendStatisticsProxy::SendSideDelayUpdated(int avg_delay_ms,
  1173. int max_delay_ms,
  1174. uint64_t total_delay_ms,
  1175. uint32_t ssrc) {
  1176. rtc::CritScope lock(&crit_);
  1177. VideoSendStream::StreamStats* stats = GetStatsEntry(ssrc);
  1178. if (!stats)
  1179. return;
  1180. stats->avg_delay_ms = avg_delay_ms;
  1181. stats->max_delay_ms = max_delay_ms;
  1182. stats->total_packet_send_delay_ms = total_delay_ms;
  1183. uma_container_->delay_counter_.Add(avg_delay_ms);
  1184. uma_container_->max_delay_counter_.Add(max_delay_ms);
  1185. }
  1186. void SendStatisticsProxy::StatsTimer::Start(int64_t now_ms) {
  1187. if (start_ms == -1)
  1188. start_ms = now_ms;
  1189. }
  1190. void SendStatisticsProxy::StatsTimer::Stop(int64_t now_ms) {
  1191. if (start_ms != -1) {
  1192. total_ms += now_ms - start_ms;
  1193. start_ms = -1;
  1194. }
  1195. }
  1196. void SendStatisticsProxy::StatsTimer::Restart(int64_t now_ms) {
  1197. total_ms = 0;
  1198. if (start_ms != -1)
  1199. start_ms = now_ms;
  1200. }
  1201. void SendStatisticsProxy::SampleCounter::Add(int sample) {
  1202. sum += sample;
  1203. ++num_samples;
  1204. }
  1205. int SendStatisticsProxy::SampleCounter::Avg(
  1206. int64_t min_required_samples) const {
  1207. if (num_samples < min_required_samples || num_samples == 0)
  1208. return -1;
  1209. return static_cast<int>((sum + (num_samples / 2)) / num_samples);
  1210. }
  1211. void SendStatisticsProxy::BoolSampleCounter::Add(bool sample) {
  1212. if (sample)
  1213. ++sum;
  1214. ++num_samples;
  1215. }
  1216. void SendStatisticsProxy::BoolSampleCounter::Add(bool sample, int64_t count) {
  1217. if (sample)
  1218. sum += count;
  1219. num_samples += count;
  1220. }
  1221. int SendStatisticsProxy::BoolSampleCounter::Percent(
  1222. int64_t min_required_samples) const {
  1223. return Fraction(min_required_samples, 100.0f);
  1224. }
  1225. int SendStatisticsProxy::BoolSampleCounter::Permille(
  1226. int64_t min_required_samples) const {
  1227. return Fraction(min_required_samples, 1000.0f);
  1228. }
  1229. int SendStatisticsProxy::BoolSampleCounter::Fraction(
  1230. int64_t min_required_samples,
  1231. float multiplier) const {
  1232. if (num_samples < min_required_samples || num_samples == 0)
  1233. return -1;
  1234. return static_cast<int>((sum * multiplier / num_samples) + 0.5f);
  1235. }
  1236. } // namespace webrtc