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