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