| 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/video_stream_encoder.h" |
| 12 |
| 13 | #include <algorithm> |
| 14 | #include <array> |
| 15 | #include <limits> |
| 16 | #include <memory> |
| 17 | #include <numeric> |
| 18 | #include <utility> |
| 19 |
| 20 | #include "absl/algorithm/container.h" |
| 21 | #include "absl/cleanup/cleanup.h" |
| 22 | #include "absl/types/optional.h" |
| 23 | #include "api/field_trials_view.h" |
| 24 | #include "api/sequence_checker.h" |
| 25 | #include "api/task_queue/task_queue_base.h" |
| 26 | #include "api/video/encoded_image.h" |
| 27 | #include "api/video/i420_buffer.h" |
| 28 | #include "api/video/render_resolution.h" |
| 29 | #include "api/video/video_adaptation_reason.h" |
| 30 | #include "api/video/video_bitrate_allocator_factory.h" |
| 31 | #include "api/video/video_codec_constants.h" |
| 32 | #include "api/video/video_layers_allocation.h" |
| 33 | #include "api/video_codecs/sdp_video_format.h" |
| 34 | #include "api/video_codecs/video_encoder.h" |
| 35 | #include "call/adaptation/resource_adaptation_processor.h" |
| 36 | #include "call/adaptation/video_source_restrictions.h" |
| 37 | #include "call/adaptation/video_stream_adapter.h" |
| 38 | #include "media/base/media_channel.h" |
| 39 | #include "modules/video_coding/include/video_codec_initializer.h" |
| 40 | #include "modules/video_coding/svc/scalability_mode_util.h" |
| 41 | #include "modules/video_coding/svc/svc_rate_allocator.h" |
| 42 | #include "modules/video_coding/utility/vp8_constants.h" |
| 43 | #include "rtc_base/arraysize.h" |
| 44 | #include "rtc_base/checks.h" |
| 45 | #include "rtc_base/event.h" |
| 46 | #include "rtc_base/experiments/encoder_info_settings.h" |
| 47 | #include "rtc_base/experiments/rate_control_settings.h" |
| 48 | #include "rtc_base/logging.h" |
| 49 | #include "rtc_base/strings/string_builder.h" |
| 50 | #include "rtc_base/system/no_unique_address.h" |
| 51 | #include "rtc_base/thread_annotations.h" |
| 52 | #include "rtc_base/trace_event.h" |
| 53 | #include "system_wrappers/include/metrics.h" |
| 54 | #include "video/adaptation/video_stream_encoder_resource_manager.h" |
| 55 | #include "video/alignment_adjuster.h" |
| 56 | #include "video/config/encoder_stream_factory.h" |
| 57 | #include "video/frame_cadence_adapter.h" |
| 58 | #include "video/frame_dumping_encoder.h" |
| 59 | #include "tgnet/FileLog.h" |
| 60 |
| 61 | namespace webrtc { |
| 62 |
| 63 | namespace { |
| 64 |
| 65 | // Time interval for logging frame counts. |
| 66 | const int64_t kFrameLogIntervalMs = 60000; |
| 67 |
| 68 | // Time to keep a single cached pending frame in paused state. |
| 69 | const int64_t kPendingFrameTimeoutMs = 1000; |
| 70 |
| 71 | constexpr char kFrameDropperFieldTrial[] = "WebRTC-FrameDropper"; |
| 72 |
| 73 | // TODO(bugs.webrtc.org/13572): Remove this kill switch after deploying the |
| 74 | // feature. |
| 75 | constexpr char kSwitchEncoderOnInitializationFailuresFieldTrial[] = |
| 76 | "WebRTC-SwitchEncoderOnInitializationFailures"; |
| 77 |
| 78 | const size_t kDefaultPayloadSize = 1440; |
| 79 |
| 80 | const int64_t kParameterUpdateIntervalMs = 1000; |
| 81 |
| 82 | // Animation is capped to 720p. |
| 83 | constexpr int kMaxAnimationPixels = 1280 * 720; |
| 84 |
| 85 | constexpr int kDefaultMinScreenSharebps = 1200000; |
| 86 |
| 87 | int GetNumSpatialLayers(const VideoCodec& codec) { |
| 88 | if (codec.codecType == kVideoCodecVP9) { |
| 89 | return codec.VP9().numberOfSpatialLayers; |
| 90 | } else if (codec.codecType == kVideoCodecAV1 && |
| 91 | codec.GetScalabilityMode().has_value()) { |
| 92 | return ScalabilityModeToNumSpatialLayers(*(codec.GetScalabilityMode())); |
| 93 | } else { |
| 94 | return 0; |
| 95 | } |
| 96 | } |
| 97 |
| 98 | absl::optional<EncodedImageCallback::DropReason> MaybeConvertDropReason( |
| 99 | VideoStreamEncoderObserver::DropReason reason) { |
| 100 | switch (reason) { |
| 101 | case VideoStreamEncoderObserver::DropReason::kMediaOptimization: |
| 102 | return EncodedImageCallback::DropReason::kDroppedByMediaOptimizations; |
| 103 | case VideoStreamEncoderObserver::DropReason::kEncoder: |
| 104 | return EncodedImageCallback::DropReason::kDroppedByEncoder; |
| 105 | default: |
| 106 | return absl::nullopt; |
| 107 | } |
| 108 | } |
| 109 |
| 110 | bool RequiresEncoderReset(const VideoCodec& prev_send_codec, |
| 111 | const VideoCodec& new_send_codec, |
| 112 | bool was_encode_called_since_last_initialization) { |
| 113 | // Does not check max/minBitrate or maxFramerate. |
| 114 | if (new_send_codec.codecType != prev_send_codec.codecType || |
| 115 | new_send_codec.width != prev_send_codec.width || |
| 116 | new_send_codec.height != prev_send_codec.height || |
| 117 | new_send_codec.qpMax != prev_send_codec.qpMax || |
| 118 | new_send_codec.numberOfSimulcastStreams != |
| 119 | prev_send_codec.numberOfSimulcastStreams || |
| 120 | new_send_codec.mode != prev_send_codec.mode || |
| 121 | new_send_codec.GetFrameDropEnabled() != |
| 122 | prev_send_codec.GetFrameDropEnabled()) { |
| 123 | return true; |
| 124 | } |
| 125 |
| 126 | if (!was_encode_called_since_last_initialization && |
| 127 | (new_send_codec.startBitrate != prev_send_codec.startBitrate)) { |
| 128 | // If start bitrate has changed reconfigure encoder only if encoding had not |
| 129 | // yet started. |
| 130 | return true; |
| 131 | } |
| 132 |
| 133 | switch (new_send_codec.codecType) { |
| 134 | case kVideoCodecVP8: |
| 135 | if (new_send_codec.VP8() != prev_send_codec.VP8()) { |
| 136 | return true; |
| 137 | } |
| 138 | break; |
| 139 |
| 140 | case kVideoCodecVP9: |
| 141 | if (new_send_codec.VP9() != prev_send_codec.VP9()) { |
| 142 | return true; |
| 143 | } |
| 144 | break; |
| 145 |
| 146 | case kVideoCodecH264: |
| 147 | if (new_send_codec.H264() != prev_send_codec.H264()) { |
| 148 | return true; |
| 149 | } |
| 150 | break; |
| 151 | case kVideoCodecH265: |
| 152 | // TODO(bugs.webrtc.org/13485): Implement new send codec H265 |
| 153 | [[fallthrough]]; |
| 154 | default: |
| 155 | break; |
| 156 | } |
| 157 |
| 158 | for (unsigned char i = 0; i < new_send_codec.numberOfSimulcastStreams; ++i) { |
| 159 | if (!new_send_codec.simulcastStream[i].active) { |
| 160 | // No need to reset when stream is inactive. |
| 161 | continue; |
| 162 | } |
| 163 |
| 164 | if (!prev_send_codec.simulcastStream[i].active || |
| 165 | new_send_codec.simulcastStream[i].width != |
| 166 | prev_send_codec.simulcastStream[i].width || |
| 167 | new_send_codec.simulcastStream[i].height != |
| 168 | prev_send_codec.simulcastStream[i].height || |
| 169 | new_send_codec.simulcastStream[i].numberOfTemporalLayers != |
| 170 | prev_send_codec.simulcastStream[i].numberOfTemporalLayers || |
| 171 | new_send_codec.simulcastStream[i].qpMax != |
| 172 | prev_send_codec.simulcastStream[i].qpMax) { |
| 173 | return true; |
| 174 | } |
| 175 | } |
| 176 |
| 177 | if (new_send_codec.codecType == kVideoCodecVP9) { |
| 178 | size_t num_spatial_layers = new_send_codec.VP9().numberOfSpatialLayers; |
| 179 | for (unsigned char i = 0; i < num_spatial_layers; ++i) { |
| 180 | if (!new_send_codec.spatialLayers[i].active) { |
| 181 | // No need to reset when layer is inactive. |
| 182 | continue; |
| 183 | } |
| 184 | if (new_send_codec.spatialLayers[i].width != |
| 185 | prev_send_codec.spatialLayers[i].width || |
| 186 | new_send_codec.spatialLayers[i].height != |
| 187 | prev_send_codec.spatialLayers[i].height || |
| 188 | new_send_codec.spatialLayers[i].numberOfTemporalLayers != |
| 189 | prev_send_codec.spatialLayers[i].numberOfTemporalLayers || |
| 190 | new_send_codec.spatialLayers[i].qpMax != |
| 191 | prev_send_codec.spatialLayers[i].qpMax || |
| 192 | !prev_send_codec.spatialLayers[i].active) { |
| 193 | return true; |
| 194 | } |
| 195 | } |
| 196 | } |
| 197 |
| 198 | if (new_send_codec.GetScalabilityMode() != |
| 199 | prev_send_codec.GetScalabilityMode()) { |
| 200 | return true; |
| 201 | } |
| 202 |
| 203 | return false; |
| 204 | } |
| 205 |
| 206 | // Limit allocation across TLs in bitrate allocation according to number of TLs |
| 207 | // in EncoderInfo. |
| 208 | VideoBitrateAllocation UpdateAllocationFromEncoderInfo( |
| 209 | const VideoBitrateAllocation& allocation, |
| 210 | const VideoEncoder::EncoderInfo& encoder_info) { |
| 211 | if (allocation.get_sum_bps() == 0) { |
| 212 | return allocation; |
| 213 | } |
| 214 | VideoBitrateAllocation new_allocation; |
| 215 | for (int si = 0; si < kMaxSpatialLayers; ++si) { |
| 216 | if (encoder_info.fps_allocation[si].size() == 1 && |
| 217 | allocation.IsSpatialLayerUsed(si)) { |
| 218 | // One TL is signalled to be used by the encoder. Do not distribute |
| 219 | // bitrate allocation across TLs (use sum at ti:0). |
| 220 | new_allocation.SetBitrate(si, 0, allocation.GetSpatialLayerSum(si)); |
| 221 | } else { |
| 222 | for (int ti = 0; ti < kMaxTemporalStreams; ++ti) { |
| 223 | if (allocation.HasBitrate(si, ti)) |
| 224 | new_allocation.SetBitrate(si, ti, allocation.GetBitrate(si, ti)); |
| 225 | } |
| 226 | } |
| 227 | } |
| 228 | new_allocation.set_bw_limited(allocation.is_bw_limited()); |
| 229 | return new_allocation; |
| 230 | } |
| 231 |
| 232 | // Converts a VideoBitrateAllocation that contains allocated bitrate per layer, |
| 233 | // and an EncoderInfo that contains information about the actual encoder |
| 234 | // structure used by a codec. Stream structures can be Ksvc, Full SVC, Simulcast |
| 235 | // etc. |
| 236 | VideoLayersAllocation CreateVideoLayersAllocation( |
| 237 | const VideoCodec& encoder_config, |
| 238 | const VideoEncoder::RateControlParameters& current_rate, |
| 239 | const VideoEncoder::EncoderInfo& encoder_info) { |
| 240 | const VideoBitrateAllocation& target_bitrate = current_rate.target_bitrate; |
| 241 | VideoLayersAllocation layers_allocation; |
| 242 | if (target_bitrate.get_sum_bps() == 0) { |
| 243 | return layers_allocation; |
| 244 | } |
| 245 |
| 246 | if (encoder_config.numberOfSimulcastStreams > 1) { |
| 247 | layers_allocation.resolution_and_frame_rate_is_valid = true; |
| 248 | for (int si = 0; si < encoder_config.numberOfSimulcastStreams; ++si) { |
| 249 | if (!target_bitrate.IsSpatialLayerUsed(si) || |
| 250 | target_bitrate.GetSpatialLayerSum(si) == 0) { |
| 251 | continue; |
| 252 | } |
| 253 | layers_allocation.active_spatial_layers.emplace_back(); |
| 254 | VideoLayersAllocation::SpatialLayer& spatial_layer = |
| 255 | layers_allocation.active_spatial_layers.back(); |
| 256 | spatial_layer.width = encoder_config.simulcastStream[si].width; |
| 257 | spatial_layer.height = encoder_config.simulcastStream[si].height; |
| 258 | spatial_layer.rtp_stream_index = si; |
| 259 | spatial_layer.spatial_id = 0; |
| 260 | auto frame_rate_fraction = |
| 261 | VideoEncoder::EncoderInfo::kMaxFramerateFraction; |
| 262 | if (encoder_info.fps_allocation[si].size() == 1) { |
| 263 | // One TL is signalled to be used by the encoder. Do not distribute |
| 264 | // bitrate allocation across TLs (use sum at tl:0). |
| 265 | spatial_layer.target_bitrate_per_temporal_layer.push_back( |
| 266 | DataRate::BitsPerSec(target_bitrate.GetSpatialLayerSum(si))); |
| 267 | frame_rate_fraction = encoder_info.fps_allocation[si][0]; |
| 268 | } else { // Temporal layers are supported. |
| 269 | uint32_t temporal_layer_bitrate_bps = 0; |
| 270 | for (size_t ti = 0; |
| 271 | ti < encoder_config.simulcastStream[si].numberOfTemporalLayers; |
| 272 | ++ti) { |
| 273 | if (!target_bitrate.HasBitrate(si, ti)) { |
| 274 | break; |
| 275 | } |
| 276 | if (ti < encoder_info.fps_allocation[si].size()) { |
| 277 | // Use frame rate of the top used temporal layer. |
| 278 | frame_rate_fraction = encoder_info.fps_allocation[si][ti]; |
| 279 | } |
| 280 | temporal_layer_bitrate_bps += target_bitrate.GetBitrate(si, ti); |
| 281 | spatial_layer.target_bitrate_per_temporal_layer.push_back( |
| 282 | DataRate::BitsPerSec(temporal_layer_bitrate_bps)); |
| 283 | } |
| 284 | } |
| 285 | // Encoder may drop frames internally if `maxFramerate` is set. |
| 286 | spatial_layer.frame_rate_fps = std::min<uint8_t>( |
| 287 | encoder_config.simulcastStream[si].maxFramerate, |
| 288 | rtc::saturated_cast<uint8_t>( |
| 289 | (current_rate.framerate_fps * frame_rate_fraction) / |
| 290 | VideoEncoder::EncoderInfo::kMaxFramerateFraction)); |
| 291 | } |
| 292 | } else if (encoder_config.numberOfSimulcastStreams == 1) { |
| 293 | // TODO(bugs.webrtc.org/12000): Implement support for AV1 with |
| 294 | // scalability. |
| 295 | const bool higher_spatial_depend_on_lower = |
| 296 | encoder_config.codecType == kVideoCodecVP9 && |
| 297 | encoder_config.VP9().interLayerPred == InterLayerPredMode::kOn; |
| 298 | layers_allocation.resolution_and_frame_rate_is_valid = true; |
| 299 |
| 300 | std::vector<DataRate> aggregated_spatial_bitrate( |
| 301 | webrtc::kMaxTemporalStreams, DataRate::Zero()); |
| 302 | for (int si = 0; si < webrtc::kMaxSpatialLayers; ++si) { |
| 303 | layers_allocation.resolution_and_frame_rate_is_valid = true; |
| 304 | if (!target_bitrate.IsSpatialLayerUsed(si) || |
| 305 | target_bitrate.GetSpatialLayerSum(si) == 0) { |
| 306 | break; |
| 307 | } |
| 308 | layers_allocation.active_spatial_layers.emplace_back(); |
| 309 | VideoLayersAllocation::SpatialLayer& spatial_layer = |
| 310 | layers_allocation.active_spatial_layers.back(); |
| 311 | spatial_layer.width = encoder_config.spatialLayers[si].width; |
| 312 | spatial_layer.height = encoder_config.spatialLayers[si].height; |
| 313 | spatial_layer.rtp_stream_index = 0; |
| 314 | spatial_layer.spatial_id = si; |
| 315 | auto frame_rate_fraction = |
| 316 | VideoEncoder::EncoderInfo::kMaxFramerateFraction; |
| 317 | if (encoder_info.fps_allocation[si].size() == 1) { |
| 318 | // One TL is signalled to be used by the encoder. Do not distribute |
| 319 | // bitrate allocation across TLs (use sum at tl:0). |
| 320 | DataRate aggregated_temporal_bitrate = |
| 321 | DataRate::BitsPerSec(target_bitrate.GetSpatialLayerSum(si)); |
| 322 | aggregated_spatial_bitrate[0] += aggregated_temporal_bitrate; |
| 323 | if (higher_spatial_depend_on_lower) { |
| 324 | spatial_layer.target_bitrate_per_temporal_layer.push_back( |
| 325 | aggregated_spatial_bitrate[0]); |
| 326 | } else { |
| 327 | spatial_layer.target_bitrate_per_temporal_layer.push_back( |
| 328 | aggregated_temporal_bitrate); |
| 329 | } |
| 330 | frame_rate_fraction = encoder_info.fps_allocation[si][0]; |
| 331 | } else { // Temporal layers are supported. |
| 332 | DataRate aggregated_temporal_bitrate = DataRate::Zero(); |
| 333 | for (size_t ti = 0; |
| 334 | ti < encoder_config.spatialLayers[si].numberOfTemporalLayers; |
| 335 | ++ti) { |
| 336 | if (!target_bitrate.HasBitrate(si, ti)) { |
| 337 | break; |
| 338 | } |
| 339 | if (ti < encoder_info.fps_allocation[si].size()) { |
| 340 | // Use frame rate of the top used temporal layer. |
| 341 | frame_rate_fraction = encoder_info.fps_allocation[si][ti]; |
| 342 | } |
| 343 | aggregated_temporal_bitrate += |
| 344 | DataRate::BitsPerSec(target_bitrate.GetBitrate(si, ti)); |
| 345 | if (higher_spatial_depend_on_lower) { |
| 346 | spatial_layer.target_bitrate_per_temporal_layer.push_back( |
| 347 | aggregated_temporal_bitrate + aggregated_spatial_bitrate[ti]); |
| 348 | aggregated_spatial_bitrate[ti] += aggregated_temporal_bitrate; |
| 349 | } else { |
| 350 | spatial_layer.target_bitrate_per_temporal_layer.push_back( |
| 351 | aggregated_temporal_bitrate); |
| 352 | } |
| 353 | } |
| 354 | } |
| 355 | // Encoder may drop frames internally if `maxFramerate` is set. |
| 356 | spatial_layer.frame_rate_fps = std::min<uint8_t>( |
| 357 | encoder_config.spatialLayers[si].maxFramerate, |
| 358 | rtc::saturated_cast<uint8_t>( |
| 359 | (current_rate.framerate_fps * frame_rate_fraction) / |
| 360 | VideoEncoder::EncoderInfo::kMaxFramerateFraction)); |
| 361 | } |
| 362 | } |
| 363 |
| 364 | return layers_allocation; |
| 365 | } |
| 366 |
| 367 | VideoEncoder::EncoderInfo GetEncoderInfoWithBitrateLimitUpdate( |
| 368 | const VideoEncoder::EncoderInfo& info, |
| 369 | const VideoEncoderConfig& encoder_config, |
| 370 | bool default_limits_allowed) { |
| 371 | if (!default_limits_allowed || !info.resolution_bitrate_limits.empty() || |
| 372 | encoder_config.simulcast_layers.size() <= 1) { |
| 373 | return info; |
| 374 | } |
| 375 | // Bitrate limits are not configured and more than one layer is used, use |
| 376 | // the default limits (bitrate limits are not used for simulcast). |
| 377 | VideoEncoder::EncoderInfo new_info = info; |
| 378 | new_info.resolution_bitrate_limits = |
| 379 | EncoderInfoSettings::GetDefaultSinglecastBitrateLimits( |
| 380 | encoder_config.codec_type); |
| 381 | return new_info; |
| 382 | } |
| 383 |
| 384 | int NumActiveStreams(const std::vector<VideoStream>& streams) { |
| 385 | int num_active = 0; |
| 386 | for (const auto& stream : streams) { |
| 387 | if (stream.active) |
| 388 | ++num_active; |
| 389 | } |
| 390 | return num_active; |
| 391 | } |
| 392 |
| 393 | void ApplySpatialLayerBitrateLimits( |
| 394 | const VideoEncoder::EncoderInfo& encoder_info, |
| 395 | const VideoEncoderConfig& encoder_config, |
| 396 | VideoCodec* codec) { |
| 397 | if (!(GetNumSpatialLayers(*codec) > 0)) { |
| 398 | // ApplySpatialLayerBitrateLimits() supports VP9 and AV1 (the latter with |
| 399 | // scalability mode set) only. |
| 400 | return; |
| 401 | } |
| 402 | if (VideoStreamEncoderResourceManager::IsSimulcastOrMultipleSpatialLayers( |
| 403 | encoder_config, *codec) || |
| 404 | encoder_config.simulcast_layers.size() <= 1) { |
| 405 | // Resolution bitrate limits usage is restricted to singlecast. |
| 406 | return; |
| 407 | } |
| 408 |
| 409 | // Get bitrate limits for active stream. |
| 410 | absl::optional<uint32_t> pixels = |
| 411 | VideoStreamAdapter::GetSingleActiveLayerPixels(*codec); |
| 412 | if (!pixels.has_value()) { |
| 413 | return; |
| 414 | } |
| 415 | absl::optional<VideoEncoder::ResolutionBitrateLimits> bitrate_limits = |
| 416 | encoder_info.GetEncoderBitrateLimitsForResolution(*pixels); |
| 417 | if (!bitrate_limits.has_value()) { |
| 418 | return; |
| 419 | } |
| 420 | // Index for the active stream. |
| 421 | absl::optional<size_t> index; |
| 422 | for (size_t i = 0; i < encoder_config.simulcast_layers.size(); ++i) { |
| 423 | if (encoder_config.simulcast_layers[i].active) |
| 424 | index = i; |
| 425 | } |
| 426 | if (!index.has_value()) { |
| 427 | return; |
| 428 | } |
| 429 | int min_bitrate_bps; |
| 430 | if (encoder_config.simulcast_layers[*index].min_bitrate_bps <= 0) { |
| 431 | min_bitrate_bps = bitrate_limits->min_bitrate_bps; |
| 432 | } else { |
| 433 | min_bitrate_bps = |
| 434 | std::max(bitrate_limits->min_bitrate_bps, |
| 435 | encoder_config.simulcast_layers[*index].min_bitrate_bps); |
| 436 | } |
| 437 | int max_bitrate_bps; |
| 438 | if (encoder_config.simulcast_layers[*index].max_bitrate_bps <= 0) { |
| 439 | max_bitrate_bps = bitrate_limits->max_bitrate_bps; |
| 440 | } else { |
| 441 | max_bitrate_bps = |
| 442 | std::min(bitrate_limits->max_bitrate_bps, |
| 443 | encoder_config.simulcast_layers[*index].max_bitrate_bps); |
| 444 | } |
| 445 | if (min_bitrate_bps >= max_bitrate_bps) { |
| 446 | RTC_LOG(LS_WARNING) << "Bitrate limits not used, min_bitrate_bps " |
| 447 | << min_bitrate_bps << " >= max_bitrate_bps " |
| 448 | << max_bitrate_bps; |
| 449 | return; |
| 450 | } |
| 451 |
| 452 | for (int i = 0; i < GetNumSpatialLayers(*codec); ++i) { |
| 453 | if (codec->spatialLayers[i].active) { |
| 454 | codec->spatialLayers[i].minBitrate = min_bitrate_bps / 1000; |
| 455 | codec->spatialLayers[i].maxBitrate = max_bitrate_bps / 1000; |
| 456 | codec->spatialLayers[i].targetBitrate = |
| 457 | std::min(codec->spatialLayers[i].targetBitrate, |
| 458 | codec->spatialLayers[i].maxBitrate); |
| 459 | break; |
| 460 | } |
| 461 | } |
| 462 | } |
| 463 |
| 464 | void ApplyEncoderBitrateLimitsIfSingleActiveStream( |
| 465 | const VideoEncoder::EncoderInfo& encoder_info, |
| 466 | const std::vector<VideoStream>& encoder_config_layers, |
| 467 | std::vector<VideoStream>* streams) { |
| 468 | // Apply limits if simulcast with one active stream (expect lowest). |
| 469 | bool single_active_stream = |
| 470 | streams->size() > 1 && NumActiveStreams(*streams) == 1 && |
| 471 | !streams->front().active && NumActiveStreams(encoder_config_layers) == 1; |
| 472 | if (!single_active_stream) { |
| 473 | return; |
| 474 | } |
| 475 |
| 476 | // Index for the active stream. |
| 477 | size_t index = 0; |
| 478 | for (size_t i = 0; i < encoder_config_layers.size(); ++i) { |
| 479 | if (encoder_config_layers[i].active) |
| 480 | index = i; |
| 481 | } |
| 482 | if (streams->size() < (index + 1) || !(*streams)[index].active) { |
| 483 | return; |
| 484 | } |
| 485 |
| 486 | // Get bitrate limits for active stream. |
| 487 | absl::optional<VideoEncoder::ResolutionBitrateLimits> encoder_bitrate_limits = |
| 488 | encoder_info.GetEncoderBitrateLimitsForResolution( |
| 489 | (*streams)[index].width * (*streams)[index].height); |
| 490 | if (!encoder_bitrate_limits) { |
| 491 | return; |
| 492 | } |
| 493 |
| 494 | // If bitrate limits are set by RtpEncodingParameters, use intersection. |
| 495 | int min_bitrate_bps; |
| 496 | if (encoder_config_layers[index].min_bitrate_bps <= 0) { |
| 497 | min_bitrate_bps = encoder_bitrate_limits->min_bitrate_bps; |
| 498 | } else { |
| 499 | min_bitrate_bps = std::max(encoder_bitrate_limits->min_bitrate_bps, |
| 500 | (*streams)[index].min_bitrate_bps); |
| 501 | } |
| 502 | int max_bitrate_bps; |
| 503 | if (encoder_config_layers[index].max_bitrate_bps <= 0) { |
| 504 | max_bitrate_bps = encoder_bitrate_limits->max_bitrate_bps; |
| 505 | } else { |
| 506 | max_bitrate_bps = std::min(encoder_bitrate_limits->max_bitrate_bps, |
| 507 | (*streams)[index].max_bitrate_bps); |
| 508 | } |
| 509 | if (min_bitrate_bps >= max_bitrate_bps) { |
| 510 | RTC_LOG(LS_WARNING) << "Encoder bitrate limits" |
| 511 | << " (min=" << encoder_bitrate_limits->min_bitrate_bps |
| 512 | << ", max=" << encoder_bitrate_limits->max_bitrate_bps |
| 513 | << ") do not intersect with stream limits" |
| 514 | << " (min=" << (*streams)[index].min_bitrate_bps |
| 515 | << ", max=" << (*streams)[index].max_bitrate_bps |
| 516 | << "). Encoder bitrate limits not used."; |
| 517 | return; |
| 518 | } |
| 519 |
| 520 | (*streams)[index].min_bitrate_bps = min_bitrate_bps; |
| 521 | (*streams)[index].max_bitrate_bps = max_bitrate_bps; |
| 522 | (*streams)[index].target_bitrate_bps = |
| 523 | std::min((*streams)[index].target_bitrate_bps, |
| 524 | encoder_bitrate_limits->max_bitrate_bps); |
| 525 | } |
| 526 |
| 527 | absl::optional<int> ParseVp9LowTierCoreCountThreshold( |
| 528 | const FieldTrialsView& trials) { |
| 529 | FieldTrialFlag disable_low_tier("Disabled"); |
| 530 | FieldTrialParameter<int> max_core_count("max_core_count", 2); |
| 531 | ParseFieldTrial({&disable_low_tier, &max_core_count}, |
| 532 | trials.Lookup("WebRTC-VP9-LowTierOptimizations")); |
| 533 | if (disable_low_tier.Get()) { |
| 534 | return absl::nullopt; |
| 535 | } |
| 536 | return max_core_count.Get(); |
| 537 | } |
| 538 |
| 539 | absl::optional<int> ParseEncoderThreadLimit(const FieldTrialsView& trials) { |
| 540 | FieldTrialOptional<int> encoder_thread_limit("encoder_thread_limit"); |
| 541 | ParseFieldTrial({&encoder_thread_limit}, |
| 542 | trials.Lookup("WebRTC-VideoEncoderSettings")); |
| 543 | return encoder_thread_limit.GetOptional(); |
| 544 | } |
| 545 |
| 546 | absl::optional<VideoSourceRestrictions> MergeRestrictions( |
| 547 | const std::vector<absl::optional<VideoSourceRestrictions>>& list) { |
| 548 | absl::optional<VideoSourceRestrictions> return_value; |
| 549 | for (const auto& res : list) { |
| 550 | if (!res) { |
| 551 | continue; |
| 552 | } |
| 553 | if (!return_value) { |
| 554 | return_value = *res; |
| 555 | continue; |
| 556 | } |
| 557 | return_value->UpdateMin(*res); |
| 558 | } |
| 559 | return return_value; |
| 560 | } |
| 561 |
| 562 | } // namespace |
| 563 |
| 564 | VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings() |
| 565 | : rate_control(), |
| 566 | encoder_target(DataRate::Zero()), |
| 567 | stable_encoder_target(DataRate::Zero()) {} |
| 568 |
| 569 | VideoStreamEncoder::EncoderRateSettings::EncoderRateSettings( |
| 570 | const VideoBitrateAllocation& bitrate, |
| 571 | double framerate_fps, |
| 572 | DataRate bandwidth_allocation, |
| 573 | DataRate encoder_target, |
| 574 | DataRate stable_encoder_target) |
| 575 | : rate_control(bitrate, framerate_fps, bandwidth_allocation), |
| 576 | encoder_target(encoder_target), |
| 577 | stable_encoder_target(stable_encoder_target) {} |
| 578 |
| 579 | bool VideoStreamEncoder::EncoderRateSettings::operator==( |
| 580 | const EncoderRateSettings& rhs) const { |
| 581 | return rate_control == rhs.rate_control && |
| 582 | encoder_target == rhs.encoder_target && |
| 583 | stable_encoder_target == rhs.stable_encoder_target; |
| 584 | } |
| 585 |
| 586 | bool VideoStreamEncoder::EncoderRateSettings::operator!=( |
| 587 | const EncoderRateSettings& rhs) const { |
| 588 | return !(*this == rhs); |
| 589 | } |
| 590 |
| 591 | class VideoStreamEncoder::DegradationPreferenceManager |
| 592 | : public DegradationPreferenceProvider { |
| 593 | public: |
| 594 | explicit DegradationPreferenceManager( |
| 595 | VideoStreamAdapter* video_stream_adapter) |
| 596 | : degradation_preference_(DegradationPreference::DISABLED), |
| 597 | is_screenshare_(false), |
| 598 | effective_degradation_preference_(DegradationPreference::DISABLED), |
| 599 | video_stream_adapter_(video_stream_adapter) { |
| 600 | RTC_DCHECK(video_stream_adapter_); |
| 601 | sequence_checker_.Detach(); |
| 602 | } |
| 603 |
| 604 | ~DegradationPreferenceManager() override = default; |
| 605 |
| 606 | DegradationPreference degradation_preference() const override { |
| 607 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 608 | return effective_degradation_preference_; |
| 609 | } |
| 610 |
| 611 | void SetDegradationPreference(DegradationPreference degradation_preference) { |
| 612 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 613 | degradation_preference_ = degradation_preference; |
| 614 | MaybeUpdateEffectiveDegradationPreference(); |
| 615 | } |
| 616 |
| 617 | void SetIsScreenshare(bool is_screenshare) { |
| 618 | RTC_DCHECK_RUN_ON(&sequence_checker_); |
| 619 | is_screenshare_ = is_screenshare; |
| 620 | MaybeUpdateEffectiveDegradationPreference(); |
| 621 | } |
| 622 |
| 623 | private: |
| 624 | void MaybeUpdateEffectiveDegradationPreference() |
| 625 | RTC_RUN_ON(&sequence_checker_) { |
| 626 | DegradationPreference effective_degradation_preference = |
| 627 | (is_screenshare_ && |
| 628 | degradation_preference_ == DegradationPreference::BALANCED) |
| 629 | ? DegradationPreference::MAINTAIN_RESOLUTION |
| 630 | : degradation_preference_; |
| 631 |
| 632 | if (effective_degradation_preference != effective_degradation_preference_) { |
| 633 | effective_degradation_preference_ = effective_degradation_preference; |
| 634 | video_stream_adapter_->SetDegradationPreference( |
| 635 | effective_degradation_preference); |
| 636 | } |
| 637 | } |
| 638 |
| 639 | RTC_NO_UNIQUE_ADDRESS SequenceChecker sequence_checker_; |
| 640 | DegradationPreference degradation_preference_ |
| 641 | RTC_GUARDED_BY(&sequence_checker_); |
| 642 | bool is_screenshare_ RTC_GUARDED_BY(&sequence_checker_); |
| 643 | DegradationPreference effective_degradation_preference_ |
| 644 | RTC_GUARDED_BY(&sequence_checker_); |
| 645 | VideoStreamAdapter* video_stream_adapter_ RTC_GUARDED_BY(&sequence_checker_); |
| 646 | }; |
| 647 | int B= 0; |
| 648 | VideoStreamEncoder::VideoStreamEncoder( |
| 649 | Clock* clock, |
| 650 | uint32_t number_of_cores, |
| 651 | VideoStreamEncoderObserver* encoder_stats_observer, |
| 652 | const VideoStreamEncoderSettings& settings, |
| 653 | std::unique_ptr<OveruseFrameDetector> overuse_detector, |
| 654 | std::unique_ptr<FrameCadenceAdapterInterface> frame_cadence_adapter, |
| 655 | std::unique_ptr<webrtc::TaskQueueBase, webrtc::TaskQueueDeleter> |
| 656 | encoder_queue, |
| 657 | BitrateAllocationCallbackType allocation_cb_type, |
| 658 | const FieldTrialsView& field_trials, |
| 659 | webrtc::VideoEncoderFactory::EncoderSelectorInterface* encoder_selector) |
| 660 | : b(B++), field_trials_(field_trials), |
| 661 | worker_queue_(TaskQueueBase::Current()), |
| 662 | number_of_cores_(number_of_cores), |
| 663 | settings_(settings), |
| 664 | allocation_cb_type_(allocation_cb_type), |
| 665 | rate_control_settings_( |
| 666 | RateControlSettings::ParseFromKeyValueConfig(&field_trials)), |
| 667 | encoder_selector_from_constructor_(encoder_selector), |
| 668 | encoder_selector_from_factory_( |
| 669 | encoder_selector_from_constructor_ |
| 670 | ? nullptr |
| 671 | : settings.encoder_factory->GetEncoderSelector()), |
| 672 | encoder_selector_(encoder_selector_from_constructor_ |
| 673 | ? encoder_selector_from_constructor_ |
| 674 | : encoder_selector_from_factory_.get()), |
| 675 | encoder_stats_observer_(encoder_stats_observer), |
| 676 | frame_cadence_adapter_(std::move(frame_cadence_adapter)), |
| 677 | clock_(clock), |
| 678 | delta_ntp_internal_ms_(clock_->CurrentNtpInMilliseconds() - |
| 679 | clock_->TimeInMilliseconds()), |
| 680 | last_frame_log_ms_(clock_->TimeInMilliseconds()), |
| 681 | next_frame_types_(1, VideoFrameType::kVideoFrameDelta), |
| 682 | automatic_animation_detection_experiment_( |
| 683 | ParseAutomatincAnimationDetectionFieldTrial()), |
| 684 | input_state_provider_(encoder_stats_observer), |
| 685 | video_stream_adapter_( |
| 686 | std::make_unique<VideoStreamAdapter>(&input_state_provider_, |
| 687 | encoder_stats_observer, |
| 688 | field_trials)), |
| 689 | degradation_preference_manager_( |
| 690 | std::make_unique<DegradationPreferenceManager>( |
| 691 | video_stream_adapter_.get())), |
| 692 | stream_resource_manager_(&input_state_provider_, |
| 693 | encoder_stats_observer, |
| 694 | clock_, |
| 695 | settings_.experiment_cpu_load_estimator, |
| 696 | std::move(overuse_detector), |
| 697 | degradation_preference_manager_.get(), |
| 698 | field_trials), |
| 699 | video_source_sink_controller_(/*sink=*/frame_cadence_adapter_.get(), |
| 700 | /*source=*/nullptr), |
| 701 | default_limits_allowed_( |
| 702 | !field_trials.IsEnabled("WebRTC-DefaultBitrateLimitsKillSwitch")), |
| 703 | qp_parsing_allowed_( |
| 704 | !field_trials.IsEnabled("WebRTC-QpParsingKillSwitch")), |
| 705 | switch_encoder_on_init_failures_(!field_trials.IsDisabled( |
| 706 | kSwitchEncoderOnInitializationFailuresFieldTrial)), |
| 707 | vp9_low_tier_core_threshold_( |
| 708 | ParseVp9LowTierCoreCountThreshold(field_trials)), |
| 709 | experimental_encoder_thread_limit_(ParseEncoderThreadLimit(field_trials)), |
| 710 | encoder_queue_(std::move(encoder_queue)) { |
| 711 | DEBUG_D("new VideoStreamEncoder$%d!!!!!!", b); |
| 712 | TRACE_EVENT0("webrtc", "VideoStreamEncoder::VideoStreamEncoder"); |
| 713 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 714 | RTC_DCHECK(encoder_stats_observer); |
| 715 | RTC_DCHECK_GE(number_of_cores, 1); |
| 716 |
| 717 | frame_cadence_adapter_->Initialize(&cadence_callback_); |
| 718 | stream_resource_manager_.Initialize(encoder_queue_.get()); |
| 719 |
| 720 | encoder_queue_->PostTask([this] { |
| 721 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 722 |
| 723 | resource_adaptation_processor_ = |
| 724 | std::make_unique<ResourceAdaptationProcessor>( |
| 725 | video_stream_adapter_.get()); |
| 726 |
| 727 | stream_resource_manager_.SetAdaptationProcessor( |
| 728 | resource_adaptation_processor_.get(), video_stream_adapter_.get()); |
| 729 | resource_adaptation_processor_->AddResourceLimitationsListener( |
| 730 | &stream_resource_manager_); |
| 731 | video_stream_adapter_->AddRestrictionsListener(&stream_resource_manager_); |
| 732 | video_stream_adapter_->AddRestrictionsListener(this); |
| 733 | stream_resource_manager_.MaybeInitializePixelLimitResource(); |
| 734 |
| 735 | // Add the stream resource manager's resources to the processor. |
| 736 | adaptation_constraints_ = stream_resource_manager_.AdaptationConstraints(); |
| 737 | for (auto* constraint : adaptation_constraints_) { |
| 738 | video_stream_adapter_->AddAdaptationConstraint(constraint); |
| 739 | } |
| 740 | }); |
| 741 | } |
| 742 |
| 743 | VideoStreamEncoder::~VideoStreamEncoder() { |
| 744 | DEBUG_D("~VideoStreamEncoder$%d!!!!!!",b); |
| 745 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 746 | RTC_DCHECK(!video_source_sink_controller_.HasSource()) |
| 747 | << "Must call ::Stop() before destruction."; |
| 748 |
| 749 | // The queue must be destroyed before its pointer is invalidated to avoid race |
| 750 | // between destructor and running task that check if function is called on the |
| 751 | // encoder_queue_. |
| 752 | // std::unique_ptr destructor does the same two operations in reverse order as |
| 753 | // it doesn't expect member would be used after its destruction has started. |
| 754 | encoder_queue_.get_deleter()(encoder_queue_.get()); |
| 755 | encoder_queue_.release(); |
| 756 | } |
| 757 |
| 758 | void VideoStreamEncoder::Stop() { |
| 759 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 760 | video_source_sink_controller_.SetSource(nullptr); |
| 761 |
| 762 | rtc::Event shutdown_event; |
| 763 | absl::Cleanup shutdown = [&shutdown_event] { shutdown_event.Set(); }; |
| 764 | encoder_queue_->PostTask([this, shutdown = std::move(shutdown)] { |
| 765 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 766 | if (resource_adaptation_processor_) { |
| 767 | stream_resource_manager_.StopManagedResources(); |
| 768 | for (auto* constraint : adaptation_constraints_) { |
| 769 | video_stream_adapter_->RemoveAdaptationConstraint(constraint); |
| 770 | } |
| 771 | for (auto& resource : additional_resources_) { |
| 772 | stream_resource_manager_.RemoveResource(resource); |
| 773 | } |
| 774 | additional_resources_.clear(); |
| 775 | video_stream_adapter_->RemoveRestrictionsListener(this); |
| 776 | video_stream_adapter_->RemoveRestrictionsListener( |
| 777 | &stream_resource_manager_); |
| 778 | resource_adaptation_processor_->RemoveResourceLimitationsListener( |
| 779 | &stream_resource_manager_); |
| 780 | stream_resource_manager_.SetAdaptationProcessor(nullptr, nullptr); |
| 781 | resource_adaptation_processor_.reset(); |
| 782 | } |
| 783 | rate_allocator_ = nullptr; |
| 784 | ReleaseEncoder(); |
| 785 | encoder_ = nullptr; |
| 786 | frame_cadence_adapter_ = nullptr; |
| 787 | }); |
| 788 | shutdown_event.Wait(rtc::Event::kForever); |
| 789 | } |
| 790 |
| 791 | void VideoStreamEncoder::SetFecControllerOverride( |
| 792 | FecControllerOverride* fec_controller_override) { |
| 793 | encoder_queue_->PostTask([this, fec_controller_override] { |
| 794 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 795 | RTC_DCHECK(!fec_controller_override_); |
| 796 | fec_controller_override_ = fec_controller_override; |
| 797 | if (encoder_) { |
| 798 | encoder_->SetFecControllerOverride(fec_controller_override_); |
| 799 | } |
| 800 | }); |
| 801 | } |
| 802 |
| 803 | void VideoStreamEncoder::AddAdaptationResource( |
| 804 | rtc::scoped_refptr<Resource> resource) { |
| 805 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 806 | TRACE_EVENT0("webrtc", "VideoStreamEncoder::AddAdaptationResource"); |
| 807 | // Map any externally added resources as kCpu for the sake of stats reporting. |
| 808 | // TODO(hbos): Make the manager map any unknown resources to kCpu and get rid |
| 809 | // of this MapResourceToReason() call. |
| 810 | TRACE_EVENT_ASYNC_BEGIN0( |
| 811 | "webrtc", "VideoStreamEncoder::AddAdaptationResource(latency)", this); |
| 812 | encoder_queue_->PostTask([this, resource = std::move(resource)] { |
| 813 | TRACE_EVENT_ASYNC_END0( |
| 814 | "webrtc", "VideoStreamEncoder::AddAdaptationResource(latency)", this); |
| 815 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 816 | additional_resources_.push_back(resource); |
| 817 | stream_resource_manager_.AddResource(resource, VideoAdaptationReason::kCpu); |
| 818 | }); |
| 819 | } |
| 820 |
| 821 | std::vector<rtc::scoped_refptr<Resource>> |
| 822 | VideoStreamEncoder::GetAdaptationResources() { |
| 823 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 824 | // In practice, this method is only called by tests to verify operations that |
| 825 | // run on the encoder queue. So rather than force PostTask() operations to |
| 826 | // be accompanied by an event and a `Wait()`, we'll use PostTask + Wait() |
| 827 | // here. |
| 828 | rtc::Event event; |
| 829 | std::vector<rtc::scoped_refptr<Resource>> resources; |
| 830 | encoder_queue_->PostTask([&] { |
| 831 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 832 | resources = resource_adaptation_processor_->GetResources(); |
| 833 | event.Set(); |
| 834 | }); |
| 835 | event.Wait(rtc::Event::kForever); |
| 836 | return resources; |
| 837 | } |
| 838 |
| 839 | void VideoStreamEncoder::SetSource( |
| 840 | rtc::VideoSourceInterface<VideoFrame>* source, |
| 841 | const DegradationPreference& degradation_preference) { |
| 842 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 843 | video_source_sink_controller_.SetSource(source); |
| 844 | input_state_provider_.OnHasInputChanged(source); |
| 845 |
| 846 | // This may trigger reconfiguring the QualityScaler on the encoder queue. |
| 847 | encoder_queue_->PostTask([this, degradation_preference] { |
| 848 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 849 | degradation_preference_manager_->SetDegradationPreference( |
| 850 | degradation_preference); |
| 851 | stream_resource_manager_.SetDegradationPreferences(degradation_preference); |
| 852 | if (encoder_) { |
| 853 | stream_resource_manager_.ConfigureQualityScaler( |
| 854 | encoder_->GetEncoderInfo()); |
| 855 | stream_resource_manager_.ConfigureBandwidthQualityScaler( |
| 856 | encoder_->GetEncoderInfo()); |
| 857 | } |
| 858 | }); |
| 859 | } |
| 860 |
| 861 | void VideoStreamEncoder::SetSink(EncoderSink* sink, bool rotation_applied) { |
| 862 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 863 | video_source_sink_controller_.SetRotationApplied(rotation_applied); |
| 864 | video_source_sink_controller_.PushSourceSinkSettings(); |
| 865 |
| 866 | encoder_queue_->PostTask([this, sink] { |
| 867 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 868 | sink_ = sink; |
| 869 | }); |
| 870 | } |
| 871 |
| 872 | void VideoStreamEncoder::SetStartBitrate(int start_bitrate_bps) { |
| 873 | encoder_queue_->PostTask([this, start_bitrate_bps] { |
| 874 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 875 | RTC_LOG(LS_INFO) << "SetStartBitrate " << start_bitrate_bps; |
| 876 | encoder_target_bitrate_bps_ = |
| 877 | start_bitrate_bps != 0 ? absl::optional<uint32_t>(start_bitrate_bps) |
| 878 | : absl::nullopt; |
| 879 | stream_resource_manager_.SetStartBitrate( |
| 880 | DataRate::BitsPerSec(start_bitrate_bps)); |
| 881 | }); |
| 882 | } |
| 883 |
| 884 | void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config, |
| 885 | size_t max_data_payload_length) { |
| 886 | ConfigureEncoder(std::move(config), max_data_payload_length, nullptr); |
| 887 | } |
| 888 |
| 889 | void VideoStreamEncoder::ConfigureEncoder(VideoEncoderConfig config, |
| 890 | size_t max_data_payload_length, |
| 891 | SetParametersCallback callback) { |
| 892 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 893 | encoder_queue_->PostTask([this, config = std::move(config), |
| 894 | max_data_payload_length, |
| 895 | callback = std::move(callback)]() mutable { |
| 896 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 897 | RTC_DCHECK(sink_); |
| 898 | RTC_LOG(LS_INFO) << "ConfigureEncoder requested."; |
| 899 |
| 900 | // Set up the frame cadence adapter according to if we're going to do |
| 901 | // screencast. The final number of spatial layers is based on info |
| 902 | // in `send_codec_`, which is computed based on incoming frame |
| 903 | // dimensions which can only be determined later. |
| 904 | // |
| 905 | // Note: zero-hertz mode isn't enabled by this alone. Constraints also |
| 906 | // have to be set up with min_fps = 0 and max_fps > 0. |
| 907 | if (config.content_type == VideoEncoderConfig::ContentType::kScreen) { |
| 908 | frame_cadence_adapter_->SetZeroHertzModeEnabled( |
| 909 | FrameCadenceAdapterInterface::ZeroHertzModeParams{}); |
| 910 | } else { |
| 911 | frame_cadence_adapter_->SetZeroHertzModeEnabled(absl::nullopt); |
| 912 | } |
| 913 |
| 914 | pending_encoder_creation_ = |
| 915 | (!encoder_ || encoder_config_.video_format != config.video_format || |
| 916 | max_data_payload_length_ != max_data_payload_length); |
| 917 | encoder_config_ = std::move(config); |
| 918 | max_data_payload_length_ = max_data_payload_length; |
| 919 | pending_encoder_reconfiguration_ = true; |
| 920 |
| 921 | // Reconfigure the encoder now if the frame resolution is known. |
| 922 | // Otherwise, the reconfiguration is deferred until the next frame to |
| 923 | // minimize the number of reconfigurations. The codec configuration |
| 924 | // depends on incoming video frame size. |
| 925 | if (last_frame_info_) { |
| 926 | if (callback) { |
| 927 | encoder_configuration_callbacks_.push_back(std::move(callback)); |
| 928 | } |
| 929 |
| 930 | ReconfigureEncoder(); |
| 931 | } else { |
| 932 | webrtc::InvokeSetParametersCallback(callback, webrtc::RTCError::OK()); |
| 933 | } |
| 934 | }); |
| 935 | } |
| 936 |
| 937 | // We should reduce the number of 'full' ReconfigureEncoder(). If only need |
| 938 | // subset of it at runtime, consider handle it in |
| 939 | // VideoStreamEncoder::EncodeVideoFrame() when encoder_info_ != info. |
| 940 | void VideoStreamEncoder::ReconfigureEncoder() { |
| 941 | // Running on the encoder queue. |
| 942 | RTC_DCHECK(pending_encoder_reconfiguration_); |
| 943 | RTC_LOG(LS_INFO) << "[VSE] " << __func__ |
| 944 | << " [encoder_config=" << encoder_config_.ToString() << "]"; |
| 945 |
| 946 | bool encoder_reset_required = false; |
| 947 | if (pending_encoder_creation_) { |
| 948 | // Destroy existing encoder instance before creating a new one. Otherwise |
| 949 | // attempt to create another instance will fail if encoder factory |
| 950 | // supports only single instance of encoder of given type. |
| 951 | encoder_.reset(); |
| 952 |
| 953 | encoder_ = MaybeCreateFrameDumpingEncoderWrapper( |
| 954 | settings_.encoder_factory->CreateVideoEncoder( |
| 955 | encoder_config_.video_format), |
| 956 | field_trials_); |
| 957 | if (!encoder_) { |
| 958 | RTC_LOG(LS_ERROR) << "CreateVideoEncoder failed, failing encoder format: " |
| 959 | << encoder_config_.video_format.ToString(); |
| 960 | RequestEncoderSwitch(); |
| 961 | return; |
| 962 | } |
| 963 |
| 964 | if (encoder_selector_) { |
| 965 | encoder_selector_->OnCurrentEncoder(encoder_config_.video_format); |
| 966 | } |
| 967 |
| 968 | encoder_->SetFecControllerOverride(fec_controller_override_); |
| 969 |
| 970 | encoder_reset_required = true; |
| 971 | } |
| 972 |
| 973 | // TODO(webrtc:14451) : Move AlignmentAdjuster into EncoderStreamFactory |
| 974 | // Possibly adjusts scale_resolution_down_by in `encoder_config_` to limit the |
| 975 | // alignment value. |
| 976 | AlignmentAdjuster::GetAlignmentAndMaybeAdjustScaleFactors( |
| 977 | encoder_->GetEncoderInfo(), &encoder_config_, absl::nullopt); |
| 978 |
| 979 | std::vector<VideoStream> streams; |
| 980 | if (encoder_config_.video_stream_factory) { |
| 981 | // Note: only tests set their own EncoderStreamFactory... |
| 982 | streams = encoder_config_.video_stream_factory->CreateEncoderStreams( |
| 983 | last_frame_info_->width, last_frame_info_->height, encoder_config_); |
| 984 | } else { |
| 985 | rtc::scoped_refptr<VideoEncoderConfig::VideoStreamFactoryInterface> |
| 986 | factory = rtc::make_ref_counted<cricket::EncoderStreamFactory>( |
| 987 | encoder_config_.video_format.name, encoder_config_.max_qp, |
| 988 | encoder_config_.content_type == |
| 989 | webrtc::VideoEncoderConfig::ContentType::kScreen, |
| 990 | encoder_config_.legacy_conference_mode, encoder_->GetEncoderInfo(), |
| 991 | MergeRestrictions({latest_restrictions_, animate_restrictions_}), |
| 992 | &field_trials_); |
| 993 |
| 994 | streams = factory->CreateEncoderStreams( |
| 995 | last_frame_info_->width, last_frame_info_->height, encoder_config_); |
| 996 | } |
| 997 |
| 998 | // TODO(webrtc:14451) : Move AlignmentAdjuster into EncoderStreamFactory |
| 999 | // Get alignment when actual number of layers are known. |
| 1000 | int alignment = AlignmentAdjuster::GetAlignmentAndMaybeAdjustScaleFactors( |
| 1001 | encoder_->GetEncoderInfo(), &encoder_config_, streams.size()); |
| 1002 |
| 1003 | // Check that the higher layers do not try to set number of temporal layers |
| 1004 | // to less than 1. |
| 1005 | // TODO(brandtr): Get rid of the wrapping optional as it serves no purpose |
| 1006 | // at this layer. |
| 1007 | #if RTC_DCHECK_IS_ON |
| 1008 | for (const auto& stream : streams) { |
| 1009 | RTC_DCHECK_GE(stream.num_temporal_layers.value_or(1), 1); |
| 1010 | } |
| 1011 | #endif |
| 1012 |
| 1013 | // TODO(ilnik): If configured resolution is significantly less than provided, |
| 1014 | // e.g. because there are not enough SSRCs for all simulcast streams, |
| 1015 | // signal new resolutions via SinkWants to video source. |
| 1016 |
| 1017 | // Stream dimensions may be not equal to given because of a simulcast |
| 1018 | // restrictions. |
| 1019 | auto highest_stream = absl::c_max_element( |
| 1020 | streams, [](const webrtc::VideoStream& a, const webrtc::VideoStream& b) { |
| 1021 | return std::tie(a.width, a.height) < std::tie(b.width, b.height); |
| 1022 | }); |
| 1023 | int highest_stream_width = static_cast<int>(highest_stream->width); |
| 1024 | int highest_stream_height = static_cast<int>(highest_stream->height); |
| 1025 | // Dimension may be reduced to be, e.g. divisible by 4. |
| 1026 | RTC_CHECK_GE(last_frame_info_->width, highest_stream_width); |
| 1027 | RTC_CHECK_GE(last_frame_info_->height, highest_stream_height); |
| 1028 | crop_width_ = last_frame_info_->width - highest_stream_width; |
| 1029 | crop_height_ = last_frame_info_->height - highest_stream_height; |
| 1030 |
| 1031 | if (!encoder_->GetEncoderInfo().is_qp_trusted.value_or(true)) { |
| 1032 | // when qp is not trusted, we priorities to using the |
| 1033 | // |resolution_bitrate_limits| provided by the decoder. |
| 1034 | const std::vector<VideoEncoder::ResolutionBitrateLimits>& bitrate_limits = |
| 1035 | encoder_->GetEncoderInfo().resolution_bitrate_limits.empty() |
| 1036 | ? EncoderInfoSettings:: |
| 1037 | GetDefaultSinglecastBitrateLimitsWhenQpIsUntrusted() |
| 1038 | : encoder_->GetEncoderInfo().resolution_bitrate_limits; |
| 1039 |
| 1040 | // For BandwidthQualityScaler, its implement based on a certain pixel_count |
| 1041 | // correspond a certain bps interval. In fact, WebRTC default max_bps is |
| 1042 | // 2500Kbps when width * height > 960 * 540. For example, we assume: |
| 1043 | // 1.the camera support 1080p. |
| 1044 | // 2.ResolutionBitrateLimits set 720p bps interval is [1500Kbps,2000Kbps]. |
| 1045 | // 3.ResolutionBitrateLimits set 1080p bps interval is [2000Kbps,2500Kbps]. |
| 1046 | // We will never be stable at 720p due to actual encoding bps of 720p and |
| 1047 | // 1080p are both 2500Kbps. So it is necessary to do a linear interpolation |
| 1048 | // to get a certain bitrate for certain pixel_count. It also doesn't work |
| 1049 | // for 960*540 and 640*520, we will nerver be stable at 640*520 due to their |
| 1050 | // |target_bitrate_bps| are both 2000Kbps. |
| 1051 | absl::optional<VideoEncoder::ResolutionBitrateLimits> |
| 1052 | qp_untrusted_bitrate_limit = EncoderInfoSettings:: |
| 1053 | GetSinglecastBitrateLimitForResolutionWhenQpIsUntrusted( |
| 1054 | last_frame_info_->width * last_frame_info_->height, |
| 1055 | bitrate_limits); |
| 1056 |
| 1057 | if (qp_untrusted_bitrate_limit) { |
| 1058 | // bandwidth_quality_scaler is only used for singlecast. |
| 1059 | if (streams.size() == 1 && encoder_config_.simulcast_layers.size() == 1) { |
| 1060 | VideoStream& stream = streams.back(); |
| 1061 | stream.max_bitrate_bps = |
| 1062 | std::min(stream.max_bitrate_bps, |
| 1063 | qp_untrusted_bitrate_limit->max_bitrate_bps); |
| 1064 | stream.min_bitrate_bps = |
| 1065 | std::min(stream.max_bitrate_bps, |
| 1066 | qp_untrusted_bitrate_limit->min_bitrate_bps); |
| 1067 | // If it is screen share mode, the minimum value of max_bitrate should |
| 1068 | // be greater than/equal to 1200kbps. |
| 1069 | if (encoder_config_.content_type == |
| 1070 | VideoEncoderConfig::ContentType::kScreen) { |
| 1071 | stream.max_bitrate_bps = |
| 1072 | std::max(stream.max_bitrate_bps, kDefaultMinScreenSharebps); |
| 1073 | } |
| 1074 | stream.target_bitrate_bps = stream.max_bitrate_bps; |
| 1075 | } |
| 1076 | } |
| 1077 | } else { |
| 1078 | absl::optional<VideoEncoder::ResolutionBitrateLimits> |
| 1079 | encoder_bitrate_limits = |
| 1080 | encoder_->GetEncoderInfo().GetEncoderBitrateLimitsForResolution( |
| 1081 | last_frame_info_->width * last_frame_info_->height); |
| 1082 |
| 1083 | if (encoder_bitrate_limits) { |
| 1084 | if (streams.size() == 1 && encoder_config_.simulcast_layers.size() == 1) { |
| 1085 | // Bitrate limits can be set by app (in SDP or RtpEncodingParameters) |
| 1086 | // or/and can be provided by encoder. In presence of both set of |
| 1087 | // limits, the final set is derived as their intersection. |
| 1088 | int min_bitrate_bps; |
| 1089 | if (encoder_config_.simulcast_layers[0].min_bitrate_bps <= 0) { |
| 1090 | min_bitrate_bps = encoder_bitrate_limits->min_bitrate_bps; |
| 1091 | } else { |
| 1092 | min_bitrate_bps = std::max(encoder_bitrate_limits->min_bitrate_bps, |
| 1093 | streams.back().min_bitrate_bps); |
| 1094 | } |
| 1095 |
| 1096 | int max_bitrate_bps; |
| 1097 | // The API max bitrate comes from both `encoder_config_.max_bitrate_bps` |
| 1098 | // and `encoder_config_.simulcast_layers[0].max_bitrate_bps`. |
| 1099 | absl::optional<int> api_max_bitrate_bps; |
| 1100 | if (encoder_config_.simulcast_layers[0].max_bitrate_bps > 0) { |
| 1101 | api_max_bitrate_bps = |
| 1102 | encoder_config_.simulcast_layers[0].max_bitrate_bps; |
| 1103 | } |
| 1104 | if (encoder_config_.max_bitrate_bps > 0) { |
| 1105 | api_max_bitrate_bps = api_max_bitrate_bps.has_value() |
| 1106 | ? std::min(encoder_config_.max_bitrate_bps, |
| 1107 | *api_max_bitrate_bps) |
| 1108 | : encoder_config_.max_bitrate_bps; |
| 1109 | } |
| 1110 | if (!api_max_bitrate_bps.has_value()) { |
| 1111 | max_bitrate_bps = encoder_bitrate_limits->max_bitrate_bps; |
| 1112 | } else { |
| 1113 | max_bitrate_bps = std::min(encoder_bitrate_limits->max_bitrate_bps, |
| 1114 | streams.back().max_bitrate_bps); |
| 1115 | } |
| 1116 |
| 1117 | if (min_bitrate_bps < max_bitrate_bps) { |
| 1118 | streams.back().min_bitrate_bps = min_bitrate_bps; |
| 1119 | streams.back().max_bitrate_bps = max_bitrate_bps; |
| 1120 | streams.back().target_bitrate_bps = |
| 1121 | std::min(streams.back().target_bitrate_bps, |
| 1122 | encoder_bitrate_limits->max_bitrate_bps); |
| 1123 | } else { |
| 1124 | RTC_LOG(LS_WARNING) |
| 1125 | << "Bitrate limits provided by encoder" |
| 1126 | << " (min=" << encoder_bitrate_limits->min_bitrate_bps |
| 1127 | << ", max=" << encoder_bitrate_limits->max_bitrate_bps |
| 1128 | << ") do not intersect with limits set by app" |
| 1129 | << " (min=" << streams.back().min_bitrate_bps |
| 1130 | << ", max=" << api_max_bitrate_bps.value_or(-1) |
| 1131 | << "). The app bitrate limits will be used."; |
| 1132 | } |
| 1133 | } |
| 1134 | } |
| 1135 | } |
| 1136 |
| 1137 | ApplyEncoderBitrateLimitsIfSingleActiveStream( |
| 1138 | GetEncoderInfoWithBitrateLimitUpdate( |
| 1139 | encoder_->GetEncoderInfo(), encoder_config_, default_limits_allowed_), |
| 1140 | encoder_config_.simulcast_layers, &streams); |
| 1141 |
| 1142 | VideoCodec codec; |
| 1143 | if (!VideoCodecInitializer::SetupCodec(encoder_config_, streams, &codec)) { |
| 1144 | RTC_LOG(LS_ERROR) << "Failed to create encoder configuration."; |
| 1145 | } |
| 1146 |
| 1147 | if (encoder_config_.codec_type == kVideoCodecVP9 || |
| 1148 | encoder_config_.codec_type == kVideoCodecAV1) { |
| 1149 | // Spatial layers configuration might impose some parity restrictions, |
| 1150 | // thus some cropping might be needed. |
| 1151 | crop_width_ = last_frame_info_->width - codec.width; |
| 1152 | crop_height_ = last_frame_info_->height - codec.height; |
| 1153 | ApplySpatialLayerBitrateLimits( |
| 1154 | GetEncoderInfoWithBitrateLimitUpdate(encoder_->GetEncoderInfo(), |
| 1155 | encoder_config_, |
| 1156 | default_limits_allowed_), |
| 1157 | encoder_config_, &codec); |
| 1158 | } |
| 1159 |
| 1160 | char log_stream_buf[4 * 1024]; |
| 1161 | rtc::SimpleStringBuilder log_stream(log_stream_buf); |
| 1162 | log_stream << "ReconfigureEncoder: simulcast streams: "; |
| 1163 | for (size_t i = 0; i < codec.numberOfSimulcastStreams; ++i) { |
| 1164 | log_stream << "{" << i << ": " << codec.simulcastStream[i].width << "x" |
| 1165 | << codec.simulcastStream[i].height << " " |
| 1166 | << ScalabilityModeToString( |
| 1167 | codec.simulcastStream[i].GetScalabilityMode()) |
| 1168 | << ", min_kbps: " << codec.simulcastStream[i].minBitrate |
| 1169 | << ", target_kbps: " << codec.simulcastStream[i].targetBitrate |
| 1170 | << ", max_kbps: " << codec.simulcastStream[i].maxBitrate |
| 1171 | << ", max_fps: " << codec.simulcastStream[i].maxFramerate |
| 1172 | << ", max_qp: " << codec.simulcastStream[i].qpMax << ", num_tl: " |
| 1173 | << codec.simulcastStream[i].numberOfTemporalLayers |
| 1174 | << ", active: " |
| 1175 | << (codec.simulcastStream[i].active ? "true" : "false") << "}"; |
| 1176 | } |
| 1177 | if (encoder_config_.codec_type == kVideoCodecVP9 || |
| 1178 | encoder_config_.codec_type == kVideoCodecAV1) { |
| 1179 | log_stream << ", spatial layers: "; |
| 1180 | for (int i = 0; i < GetNumSpatialLayers(codec); ++i) { |
| 1181 | log_stream << "{" << i << ": " << codec.spatialLayers[i].width << "x" |
| 1182 | << codec.spatialLayers[i].height |
| 1183 | << ", min_kbps: " << codec.spatialLayers[i].minBitrate |
| 1184 | << ", target_kbps: " << codec.spatialLayers[i].targetBitrate |
| 1185 | << ", max_kbps: " << codec.spatialLayers[i].maxBitrate |
| 1186 | << ", max_fps: " << codec.spatialLayers[i].maxFramerate |
| 1187 | << ", max_qp: " << codec.spatialLayers[i].qpMax << ", num_tl: " |
| 1188 | << codec.spatialLayers[i].numberOfTemporalLayers |
| 1189 | << ", active: " |
| 1190 | << (codec.spatialLayers[i].active ? "true" : "false") << "}"; |
| 1191 | } |
| 1192 | } |
| 1193 | RTC_LOG(LS_INFO) << "[VSE] " << log_stream.str(); |
| 1194 |
| 1195 | codec.startBitrate = std::max(encoder_target_bitrate_bps_.value_or(0) / 1000, |
| 1196 | codec.minBitrate); |
| 1197 | codec.startBitrate = std::min(codec.startBitrate, codec.maxBitrate); |
| 1198 | codec.expect_encode_from_texture = last_frame_info_->is_texture; |
| 1199 | // Make sure the start bit rate is sane... |
| 1200 | RTC_DCHECK_LE(codec.startBitrate, 1000000); |
| 1201 | max_framerate_ = codec.maxFramerate; |
| 1202 |
| 1203 | // Inform source about max configured framerate, |
| 1204 | // requested_resolution and which layers are active. |
| 1205 | int max_framerate = 0; |
| 1206 | // Is any layer active. |
| 1207 | bool active = false; |
| 1208 | // The max requested_resolution. |
| 1209 | absl::optional<rtc::VideoSinkWants::FrameSize> requested_resolution; |
| 1210 | for (const auto& stream : streams) { |
| 1211 | max_framerate = std::max(stream.max_framerate, max_framerate); |
| 1212 | active |= stream.active; |
| 1213 | // Note: we propagate the highest requested_resolution regardless |
| 1214 | // if layer is active or not. |
| 1215 | if (stream.requested_resolution) { |
| 1216 | if (!requested_resolution) { |
| 1217 | requested_resolution.emplace(stream.requested_resolution->width, |
| 1218 | stream.requested_resolution->height); |
| 1219 | } else { |
| 1220 | requested_resolution.emplace( |
| 1221 | std::max(stream.requested_resolution->width, |
| 1222 | requested_resolution->width), |
| 1223 | std::max(stream.requested_resolution->height, |
| 1224 | requested_resolution->height)); |
| 1225 | } |
| 1226 | } |
| 1227 | } |
| 1228 |
| 1229 | // The resolutions that we're actually encoding with. |
| 1230 | std::vector<rtc::VideoSinkWants::FrameSize> encoder_resolutions; |
| 1231 | // TODO(hbos): For the case of SVC, also make use of `codec.spatialLayers`. |
| 1232 | // For now, SVC layers are handled by the VP9 encoder. |
| 1233 | for (const auto& simulcastStream : codec.simulcastStream) { |
| 1234 | if (!simulcastStream.active) |
| 1235 | continue; |
| 1236 | encoder_resolutions.emplace_back(simulcastStream.width, |
| 1237 | simulcastStream.height); |
| 1238 | } |
| 1239 | worker_queue_->PostTask(SafeTask( |
| 1240 | task_safety_.flag(), |
| 1241 | [this, max_framerate, alignment, |
| 1242 | encoder_resolutions = std::move(encoder_resolutions), |
| 1243 | requested_resolution = std::move(requested_resolution), active]() { |
| 1244 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 1245 | if (max_framerate != |
| 1246 | video_source_sink_controller_.frame_rate_upper_limit() || |
| 1247 | alignment != video_source_sink_controller_.resolution_alignment() || |
| 1248 | encoder_resolutions != |
| 1249 | video_source_sink_controller_.resolutions() || |
| 1250 | (video_source_sink_controller_.requested_resolution() != |
| 1251 | requested_resolution) || |
| 1252 | (video_source_sink_controller_.active() != active)) { |
| 1253 | video_source_sink_controller_.SetFrameRateUpperLimit(max_framerate); |
| 1254 | video_source_sink_controller_.SetResolutionAlignment(alignment); |
| 1255 | video_source_sink_controller_.SetResolutions( |
| 1256 | std::move(encoder_resolutions)); |
| 1257 | video_source_sink_controller_.SetRequestedResolution( |
| 1258 | requested_resolution); |
| 1259 | video_source_sink_controller_.SetActive(active); |
| 1260 | video_source_sink_controller_.PushSourceSinkSettings(); |
| 1261 | } |
| 1262 | })); |
| 1263 |
| 1264 | rate_allocator_ = |
| 1265 | settings_.bitrate_allocator_factory->CreateVideoBitrateAllocator(codec); |
| 1266 | rate_allocator_->SetLegacyConferenceMode( |
| 1267 | encoder_config_.legacy_conference_mode); |
| 1268 |
| 1269 | // Reset (release existing encoder) if one exists and anything except |
| 1270 | // start bitrate or max framerate has changed. |
| 1271 | if (!encoder_reset_required) { |
| 1272 | encoder_reset_required = RequiresEncoderReset( |
| 1273 | send_codec_, codec, was_encode_called_since_last_initialization_); |
| 1274 | } |
| 1275 |
| 1276 | if (codec.codecType == VideoCodecType::kVideoCodecVP9 && |
| 1277 | number_of_cores_ <= vp9_low_tier_core_threshold_.value_or(0)) { |
| 1278 | codec.SetVideoEncoderComplexity(VideoCodecComplexity::kComplexityLow); |
| 1279 | } |
| 1280 |
| 1281 | send_codec_ = codec; |
| 1282 |
| 1283 | // Keep the same encoder, as long as the video_format is unchanged. |
| 1284 | // Encoder creation block is split in two since EncoderInfo needed to start |
| 1285 | // CPU adaptation with the correct settings should be polled after |
| 1286 | // encoder_->InitEncode(). |
| 1287 | if (encoder_reset_required) { |
| 1288 | ReleaseEncoder(); |
| 1289 | const size_t max_data_payload_length = max_data_payload_length_ > 0 |
| 1290 | ? max_data_payload_length_ |
| 1291 | : kDefaultPayloadSize; |
| 1292 | VideoEncoder::Settings settings = VideoEncoder::Settings( |
| 1293 | settings_.capabilities, number_of_cores_, max_data_payload_length); |
| 1294 | settings.encoder_thread_limit = experimental_encoder_thread_limit_; |
| 1295 | int error = encoder_->InitEncode(&send_codec_, settings); |
| 1296 | if (error != 0) { |
| 1297 | RTC_LOG(LS_ERROR) << "Failed to initialize the encoder associated with " |
| 1298 | "codec type: " |
| 1299 | << CodecTypeToPayloadString(send_codec_.codecType) |
| 1300 | << " (" << send_codec_.codecType |
| 1301 | << "). Error: " << error; |
| 1302 | ReleaseEncoder(); |
| 1303 | } else { |
| 1304 | encoder_initialized_ = true; |
| 1305 | encoder_->RegisterEncodeCompleteCallback(this); |
| 1306 | frame_encode_metadata_writer_.OnEncoderInit(send_codec_); |
| 1307 | next_frame_types_.clear(); |
| 1308 | next_frame_types_.resize( |
| 1309 | std::max(static_cast<int>(codec.numberOfSimulcastStreams), 1), |
| 1310 | VideoFrameType::kVideoFrameKey); |
| 1311 | } |
| 1312 |
| 1313 | frame_encode_metadata_writer_.Reset(); |
| 1314 | last_encode_info_ms_ = absl::nullopt; |
| 1315 | was_encode_called_since_last_initialization_ = false; |
| 1316 | } |
| 1317 |
| 1318 | // Inform dependents of updated encoder settings. |
| 1319 | OnEncoderSettingsChanged(); |
| 1320 |
| 1321 | if (encoder_initialized_) { |
| 1322 | RTC_LOG(LS_VERBOSE) << " max bitrate " << codec.maxBitrate |
| 1323 | << " start bitrate " << codec.startBitrate |
| 1324 | << " max frame rate " << codec.maxFramerate |
| 1325 | << " max payload size " << max_data_payload_length_; |
| 1326 | } else { |
| 1327 | RTC_LOG(LS_ERROR) << "[VSE] Failed to configure encoder."; |
| 1328 | rate_allocator_ = nullptr; |
| 1329 | } |
| 1330 |
| 1331 | if (pending_encoder_creation_) { |
| 1332 | stream_resource_manager_.ConfigureEncodeUsageResource(); |
| 1333 | pending_encoder_creation_ = false; |
| 1334 | } |
| 1335 |
| 1336 | int num_layers; |
| 1337 | if (codec.codecType == kVideoCodecVP8) { |
| 1338 | num_layers = codec.VP8()->numberOfTemporalLayers; |
| 1339 | } else if (codec.codecType == kVideoCodecVP9) { |
| 1340 | num_layers = codec.VP9()->numberOfTemporalLayers; |
| 1341 | } else if (codec.codecType == kVideoCodecAV1 && |
| 1342 | codec.GetScalabilityMode().has_value()) { |
| 1343 | num_layers = |
| 1344 | ScalabilityModeToNumTemporalLayers(*(codec.GetScalabilityMode())); |
| 1345 | } else if (codec.codecType == kVideoCodecH264) { |
| 1346 | num_layers = codec.H264()->numberOfTemporalLayers; |
| 1347 | } else if (codec.codecType == kVideoCodecGeneric && |
| 1348 | codec.numberOfSimulcastStreams > 0) { |
| 1349 | // This is mainly for unit testing, disabling frame dropping. |
| 1350 | // TODO(sprang): Add a better way to disable frame dropping. |
| 1351 | num_layers = codec.simulcastStream[0].numberOfTemporalLayers; |
| 1352 | } else { |
| 1353 | // TODO(bugs.webrtc.org/13485): Implement H265 temporal layer |
| 1354 | num_layers = 1; |
| 1355 | } |
| 1356 |
| 1357 | frame_dropper_.Reset(); |
| 1358 | frame_dropper_.SetRates(codec.startBitrate, max_framerate_); |
| 1359 | // Force-disable frame dropper if either: |
| 1360 | // * We have screensharing with layers. |
| 1361 | // * "WebRTC-FrameDropper" field trial is "Disabled". |
| 1362 | force_disable_frame_dropper_ = |
| 1363 | field_trials_.IsDisabled(kFrameDropperFieldTrial) || |
| 1364 | (num_layers > 1 && codec.mode == VideoCodecMode::kScreensharing); |
| 1365 |
| 1366 | const VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo(); |
| 1367 | if (rate_control_settings_.UseEncoderBitrateAdjuster()) { |
| 1368 | bitrate_adjuster_ = |
| 1369 | std::make_unique<EncoderBitrateAdjuster>(codec, field_trials_); |
| 1370 | bitrate_adjuster_->OnEncoderInfo(info); |
| 1371 | } |
| 1372 |
| 1373 | if (rate_allocator_ && last_encoder_rate_settings_) { |
| 1374 | // We have a new rate allocator instance and already configured target |
| 1375 | // bitrate. Update the rate allocation and notify observers. |
| 1376 | // We must invalidate the last_encoder_rate_settings_ to ensure |
| 1377 | // the changes get propagated to all listeners. |
| 1378 | EncoderRateSettings rate_settings = *last_encoder_rate_settings_; |
| 1379 | last_encoder_rate_settings_.reset(); |
| 1380 | rate_settings.rate_control.framerate_fps = GetInputFramerateFps(); |
| 1381 |
| 1382 | SetEncoderRates(UpdateBitrateAllocation(rate_settings)); |
| 1383 | } |
| 1384 |
| 1385 | encoder_stats_observer_->OnEncoderReconfigured(encoder_config_, streams); |
| 1386 |
| 1387 | pending_encoder_reconfiguration_ = false; |
| 1388 |
| 1389 | bool is_svc = false; |
| 1390 | bool single_stream_or_non_first_inactive = true; |
| 1391 | for (size_t i = 1; i < encoder_config_.number_of_streams; ++i) { |
| 1392 | if (encoder_config_.simulcast_layers[i].active) { |
| 1393 | single_stream_or_non_first_inactive = false; |
| 1394 | break; |
| 1395 | } |
| 1396 | } |
| 1397 | // Set min_bitrate_bps, max_bitrate_bps, and max padding bit rate for VP9 |
| 1398 | // and AV1 and leave only one stream containing all necessary information. |
| 1399 | if ((encoder_config_.codec_type == kVideoCodecVP9 || |
| 1400 | encoder_config_.codec_type == kVideoCodecAV1) && |
| 1401 | single_stream_or_non_first_inactive) { |
| 1402 | // Lower max bitrate to the level codec actually can produce. |
| 1403 | streams[0].max_bitrate_bps = |
| 1404 | std::min(streams[0].max_bitrate_bps, |
| 1405 | SvcRateAllocator::GetMaxBitrate(codec).bps<int>()); |
| 1406 | streams[0].min_bitrate_bps = codec.spatialLayers[0].minBitrate * 1000; |
| 1407 | // target_bitrate_bps specifies the maximum padding bitrate. |
| 1408 | streams[0].target_bitrate_bps = |
| 1409 | SvcRateAllocator::GetPaddingBitrate(codec).bps<int>(); |
| 1410 | streams[0].width = streams.back().width; |
| 1411 | streams[0].height = streams.back().height; |
| 1412 | is_svc = GetNumSpatialLayers(codec) > 1; |
| 1413 | streams.resize(1); |
| 1414 | } |
| 1415 |
| 1416 | sink_->OnEncoderConfigurationChanged( |
| 1417 | std::move(streams), is_svc, encoder_config_.content_type, |
| 1418 | encoder_config_.min_transmit_bitrate_bps); |
| 1419 |
| 1420 | stream_resource_manager_.ConfigureQualityScaler(info); |
| 1421 | stream_resource_manager_.ConfigureBandwidthQualityScaler(info); |
| 1422 |
| 1423 | webrtc::RTCError encoder_configuration_result = webrtc::RTCError::OK(); |
| 1424 |
| 1425 | if (!encoder_initialized_) { |
| 1426 | RTC_LOG(LS_WARNING) << "Failed to initialize " |
| 1427 | << CodecTypeToPayloadString(codec.codecType) |
| 1428 | << " encoder." |
| 1429 | << "switch_encoder_on_init_failures: " |
| 1430 | << switch_encoder_on_init_failures_; |
| 1431 |
| 1432 | if (switch_encoder_on_init_failures_) { |
| 1433 | RequestEncoderSwitch(); |
| 1434 | } else { |
| 1435 | encoder_configuration_result = |
| 1436 | webrtc::RTCError(RTCErrorType::UNSUPPORTED_OPERATION); |
| 1437 | } |
| 1438 | } |
| 1439 |
| 1440 | if (!encoder_configuration_callbacks_.empty()) { |
| 1441 | for (auto& callback : encoder_configuration_callbacks_) { |
| 1442 | webrtc::InvokeSetParametersCallback(callback, |
| 1443 | encoder_configuration_result); |
| 1444 | } |
| 1445 | encoder_configuration_callbacks_.clear(); |
| 1446 | } |
| 1447 | } |
| 1448 |
| 1449 | void VideoStreamEncoder::RequestEncoderSwitch() { |
| 1450 | bool is_encoder_switching_supported = |
| 1451 | settings_.encoder_switch_request_callback != nullptr; |
| 1452 | bool is_encoder_selector_available = encoder_selector_ != nullptr; |
| 1453 |
| 1454 | RTC_LOG(LS_INFO) << "RequestEncoderSwitch." |
| 1455 | << " is_encoder_selector_available: " |
| 1456 | << is_encoder_selector_available |
| 1457 | << " is_encoder_switching_supported: " |
| 1458 | << is_encoder_switching_supported; |
| 1459 |
| 1460 | if (!is_encoder_switching_supported) { |
| 1461 | return; |
| 1462 | } |
| 1463 |
| 1464 | // If encoder selector is available, switch to the encoder it prefers. |
| 1465 | // Otherwise try switching to VP8 (default WebRTC codec). |
| 1466 | absl::optional<SdpVideoFormat> preferred_fallback_encoder; |
| 1467 | if (is_encoder_selector_available) { |
| 1468 | preferred_fallback_encoder = encoder_selector_->OnEncoderBroken(); |
| 1469 | } |
| 1470 |
| 1471 | if (!preferred_fallback_encoder) { |
| 1472 | preferred_fallback_encoder = |
| 1473 | SdpVideoFormat(CodecTypeToPayloadString(kVideoCodecVP8)); |
| 1474 | } |
| 1475 |
| 1476 | settings_.encoder_switch_request_callback->RequestEncoderSwitch( |
| 1477 | *preferred_fallback_encoder, /*allow_default_fallback=*/true); |
| 1478 | } |
| 1479 |
| 1480 | void VideoStreamEncoder::OnEncoderSettingsChanged() { |
| 1481 | EncoderSettings encoder_settings( |
| 1482 | GetEncoderInfoWithBitrateLimitUpdate( |
| 1483 | encoder_->GetEncoderInfo(), encoder_config_, default_limits_allowed_), |
| 1484 | encoder_config_.Copy(), send_codec_); |
| 1485 | stream_resource_manager_.SetEncoderSettings(encoder_settings); |
| 1486 | input_state_provider_.OnEncoderSettingsChanged(encoder_settings); |
| 1487 | bool is_screenshare = encoder_settings.encoder_config().content_type == |
| 1488 | VideoEncoderConfig::ContentType::kScreen; |
| 1489 | degradation_preference_manager_->SetIsScreenshare(is_screenshare); |
| 1490 | if (is_screenshare) { |
| 1491 | frame_cadence_adapter_->SetZeroHertzModeEnabled( |
| 1492 | FrameCadenceAdapterInterface::ZeroHertzModeParams{ |
| 1493 | send_codec_.numberOfSimulcastStreams}); |
| 1494 | } |
| 1495 | } |
| 1496 |
| 1497 | void VideoStreamEncoder::OnFrame(Timestamp post_time, |
| 1498 | bool queue_overload, |
| 1499 | const VideoFrame& video_frame) { |
| 1500 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 1501 | VideoFrame incoming_frame = video_frame; |
| 1502 |
| 1503 | // In some cases, e.g., when the frame from decoder is fed to encoder, |
| 1504 | // the timestamp may be set to the future. As the encoding pipeline assumes |
| 1505 | // capture time to be less than present time, we should reset the capture |
| 1506 | // timestamps here. Otherwise there may be issues with RTP send stream. |
| 1507 | if (incoming_frame.timestamp_us() > post_time.us()) |
| 1508 | incoming_frame.set_timestamp_us(post_time.us()); |
| 1509 |
| 1510 | // Capture time may come from clock with an offset and drift from clock_. |
| 1511 | int64_t capture_ntp_time_ms; |
| 1512 | if (video_frame.ntp_time_ms() > 0) { |
| 1513 | capture_ntp_time_ms = video_frame.ntp_time_ms(); |
| 1514 | } else if (video_frame.render_time_ms() != 0) { |
| 1515 | capture_ntp_time_ms = video_frame.render_time_ms() + delta_ntp_internal_ms_; |
| 1516 | } else { |
| 1517 | capture_ntp_time_ms = post_time.ms() + delta_ntp_internal_ms_; |
| 1518 | } |
| 1519 | incoming_frame.set_ntp_time_ms(capture_ntp_time_ms); |
| 1520 |
| 1521 | // Convert NTP time, in ms, to RTP timestamp. |
| 1522 | const int kMsToRtpTimestamp = 90; |
| 1523 | incoming_frame.set_timestamp( |
| 1524 | kMsToRtpTimestamp * static_cast<uint32_t>(incoming_frame.ntp_time_ms())); |
| 1525 |
| 1526 | // Identifier should remain the same for newly produced incoming frame and the |
| 1527 | // received |video_frame|. |
| 1528 | incoming_frame.set_capture_time_identifier( |
| 1529 | video_frame.capture_time_identifier()); |
| 1530 |
| 1531 | if (incoming_frame.ntp_time_ms() <= last_captured_timestamp_) { |
| 1532 | // We don't allow the same capture time for two frames, drop this one. |
| 1533 | RTC_LOG(LS_WARNING) << "Same/old NTP timestamp (" |
| 1534 | << incoming_frame.ntp_time_ms() |
| 1535 | << " <= " << last_captured_timestamp_ |
| 1536 | << ") for incoming frame. Dropping."; |
| 1537 | ProcessDroppedFrame(incoming_frame, |
| 1538 | VideoStreamEncoderObserver::DropReason::kBadTimestamp); |
| 1539 | return; |
| 1540 | } |
| 1541 |
| 1542 | bool log_stats = false; |
| 1543 | if (post_time.ms() - last_frame_log_ms_ > kFrameLogIntervalMs) { |
| 1544 | last_frame_log_ms_ = post_time.ms(); |
| 1545 | log_stats = true; |
| 1546 | } |
| 1547 |
| 1548 | last_captured_timestamp_ = incoming_frame.ntp_time_ms(); |
| 1549 |
| 1550 | encoder_stats_observer_->OnIncomingFrame(incoming_frame.width(), |
| 1551 | incoming_frame.height()); |
| 1552 | ++captured_frame_count_; |
| 1553 | CheckForAnimatedContent(incoming_frame, post_time.us()); |
| 1554 | bool cwnd_frame_drop = |
| 1555 | cwnd_frame_drop_interval_ && |
| 1556 | (cwnd_frame_counter_++ % cwnd_frame_drop_interval_.value() == 0); |
| 1557 | if (!queue_overload && !cwnd_frame_drop) { |
| 1558 | MaybeEncodeVideoFrame(incoming_frame, post_time.us()); |
| 1559 | } else { |
| 1560 | if (cwnd_frame_drop) { |
| 1561 | // Frame drop by congestion window pushback. Do not encode this |
| 1562 | // frame. |
| 1563 | ++dropped_frame_cwnd_pushback_count_; |
| 1564 | } else { |
| 1565 | // There is a newer frame in flight. Do not encode this frame. |
| 1566 | RTC_LOG(LS_VERBOSE) |
| 1567 | << "Incoming frame dropped due to that the encoder is blocked."; |
| 1568 | ++dropped_frame_encoder_block_count_; |
| 1569 | } |
| 1570 | ProcessDroppedFrame( |
| 1571 | incoming_frame, |
| 1572 | cwnd_frame_drop |
| 1573 | ? VideoStreamEncoderObserver::DropReason::kCongestionWindow |
| 1574 | : VideoStreamEncoderObserver::DropReason::kEncoderQueue); |
| 1575 | } |
| 1576 | if (log_stats) { |
| 1577 | RTC_LOG(LS_INFO) << "Number of frames: captured " << captured_frame_count_ |
| 1578 | << ", dropped (due to congestion window pushback) " |
| 1579 | << dropped_frame_cwnd_pushback_count_ |
| 1580 | << ", dropped (due to encoder blocked) " |
| 1581 | << dropped_frame_encoder_block_count_ << ", interval_ms " |
| 1582 | << kFrameLogIntervalMs; |
| 1583 | captured_frame_count_ = 0; |
| 1584 | dropped_frame_cwnd_pushback_count_ = 0; |
| 1585 | dropped_frame_encoder_block_count_ = 0; |
| 1586 | } |
| 1587 | } |
| 1588 |
| 1589 | void VideoStreamEncoder::OnDiscardedFrame() { |
| 1590 | encoder_stats_observer_->OnFrameDropped( |
| 1591 | VideoStreamEncoderObserver::DropReason::kSource); |
| 1592 | } |
| 1593 |
| 1594 | bool VideoStreamEncoder::EncoderPaused() const { |
| 1595 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 1596 | // Pause video if paused by caller or as long as the network is down or the |
| 1597 | // pacer queue has grown too large in buffered mode. |
| 1598 | // If the pacer queue has grown too large or the network is down, |
| 1599 | // `last_encoder_rate_settings_->encoder_target` will be 0. |
| 1600 | return !last_encoder_rate_settings_ || |
| 1601 | last_encoder_rate_settings_->encoder_target == DataRate::Zero(); |
| 1602 | } |
| 1603 |
| 1604 | void VideoStreamEncoder::TraceFrameDropStart() { |
| 1605 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 1606 | // Start trace event only on the first frame after encoder is paused. |
| 1607 | if (!encoder_paused_and_dropped_frame_) { |
| 1608 | TRACE_EVENT_ASYNC_BEGIN0("webrtc", "EncoderPaused", this); |
| 1609 | } |
| 1610 | encoder_paused_and_dropped_frame_ = true; |
| 1611 | } |
| 1612 |
| 1613 | void VideoStreamEncoder::TraceFrameDropEnd() { |
| 1614 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 1615 | // End trace event on first frame after encoder resumes, if frame was dropped. |
| 1616 | if (encoder_paused_and_dropped_frame_) { |
| 1617 | TRACE_EVENT_ASYNC_END0("webrtc", "EncoderPaused", this); |
| 1618 | } |
| 1619 | encoder_paused_and_dropped_frame_ = false; |
| 1620 | } |
| 1621 |
| 1622 | VideoStreamEncoder::EncoderRateSettings |
| 1623 | VideoStreamEncoder::UpdateBitrateAllocation( |
| 1624 | const EncoderRateSettings& rate_settings) { |
| 1625 | VideoBitrateAllocation new_allocation; |
| 1626 | // Only call allocators if bitrate > 0 (ie, not suspended), otherwise they |
| 1627 | // might cap the bitrate to the min bitrate configured. |
| 1628 | if (rate_allocator_ && rate_settings.encoder_target > DataRate::Zero()) { |
| 1629 | new_allocation = rate_allocator_->Allocate(VideoBitrateAllocationParameters( |
| 1630 | rate_settings.encoder_target, rate_settings.stable_encoder_target, |
| 1631 | rate_settings.rate_control.framerate_fps)); |
| 1632 | } |
| 1633 |
| 1634 | EncoderRateSettings new_rate_settings = rate_settings; |
| 1635 | new_rate_settings.rate_control.target_bitrate = new_allocation; |
| 1636 | new_rate_settings.rate_control.bitrate = new_allocation; |
| 1637 | // VideoBitrateAllocator subclasses may allocate a bitrate higher than the |
| 1638 | // target in order to sustain the min bitrate of the video codec. In this |
| 1639 | // case, make sure the bandwidth allocation is at least equal the allocation |
| 1640 | // as that is part of the document contract for that field. |
| 1641 | new_rate_settings.rate_control.bandwidth_allocation = |
| 1642 | std::max(new_rate_settings.rate_control.bandwidth_allocation, |
| 1643 | DataRate::BitsPerSec( |
| 1644 | new_rate_settings.rate_control.bitrate.get_sum_bps())); |
| 1645 |
| 1646 | if (bitrate_adjuster_) { |
| 1647 | VideoBitrateAllocation adjusted_allocation = |
| 1648 | bitrate_adjuster_->AdjustRateAllocation(new_rate_settings.rate_control); |
| 1649 | RTC_LOG(LS_VERBOSE) << "Adjusting allocation, fps = " |
| 1650 | << rate_settings.rate_control.framerate_fps << ", from " |
| 1651 | << new_allocation.ToString() << ", to " |
| 1652 | << adjusted_allocation.ToString(); |
| 1653 | new_rate_settings.rate_control.bitrate = adjusted_allocation; |
| 1654 | } |
| 1655 |
| 1656 | return new_rate_settings; |
| 1657 | } |
| 1658 |
| 1659 | uint32_t VideoStreamEncoder::GetInputFramerateFps() { |
| 1660 | const uint32_t default_fps = max_framerate_ != -1 ? max_framerate_ : 30; |
| 1661 |
| 1662 | // This method may be called after we cleared out the frame_cadence_adapter_ |
| 1663 | // reference in Stop(). In such a situation it's probably not important with a |
| 1664 | // decent estimate. |
| 1665 | absl::optional<uint32_t> input_fps = |
| 1666 | frame_cadence_adapter_ ? frame_cadence_adapter_->GetInputFrameRateFps() |
| 1667 | : absl::nullopt; |
| 1668 | if (!input_fps || *input_fps == 0) { |
| 1669 | return default_fps; |
| 1670 | } |
| 1671 | return *input_fps; |
| 1672 | } |
| 1673 |
| 1674 | void VideoStreamEncoder::SetEncoderRates( |
| 1675 | const EncoderRateSettings& rate_settings) { |
| 1676 | RTC_DCHECK_GT(rate_settings.rate_control.framerate_fps, 0.0); |
| 1677 | bool rate_control_changed = |
| 1678 | (!last_encoder_rate_settings_.has_value() || |
| 1679 | last_encoder_rate_settings_->rate_control != rate_settings.rate_control); |
| 1680 | // For layer allocation signal we care only about the target bitrate (not the |
| 1681 | // adjusted one) and the target fps. |
| 1682 | bool layer_allocation_changed = |
| 1683 | !last_encoder_rate_settings_.has_value() || |
| 1684 | last_encoder_rate_settings_->rate_control.target_bitrate != |
| 1685 | rate_settings.rate_control.target_bitrate || |
| 1686 | last_encoder_rate_settings_->rate_control.framerate_fps != |
| 1687 | rate_settings.rate_control.framerate_fps; |
| 1688 |
| 1689 | if (last_encoder_rate_settings_ != rate_settings) { |
| 1690 | last_encoder_rate_settings_ = rate_settings; |
| 1691 | } |
| 1692 |
| 1693 | if (!encoder_) |
| 1694 | return; |
| 1695 |
| 1696 | // Make the cadence adapter know if streams were disabled. |
| 1697 | for (int spatial_index = 0; |
| 1698 | spatial_index != send_codec_.numberOfSimulcastStreams; ++spatial_index) { |
| 1699 | frame_cadence_adapter_->UpdateLayerStatus( |
| 1700 | spatial_index, |
| 1701 | /*enabled=*/rate_settings.rate_control.target_bitrate |
| 1702 | .GetSpatialLayerSum(spatial_index) > 0); |
| 1703 | } |
| 1704 |
| 1705 | // `bitrate_allocation` is 0 it means that the network is down or the send |
| 1706 | // pacer is full. We currently don't pass this on to the encoder since it is |
| 1707 | // unclear how current encoder implementations behave when given a zero target |
| 1708 | // bitrate. |
| 1709 | // TODO(perkj): Make sure all known encoder implementations handle zero |
| 1710 | // target bitrate and remove this check. |
| 1711 | if (rate_settings.rate_control.bitrate.get_sum_bps() == 0) |
| 1712 | return; |
| 1713 |
| 1714 | if (rate_control_changed) { |
| 1715 | encoder_->SetRates(rate_settings.rate_control); |
| 1716 |
| 1717 | encoder_stats_observer_->OnBitrateAllocationUpdated( |
| 1718 | send_codec_, rate_settings.rate_control.bitrate); |
| 1719 | frame_encode_metadata_writer_.OnSetRates( |
| 1720 | rate_settings.rate_control.bitrate, |
| 1721 | static_cast<uint32_t>(rate_settings.rate_control.framerate_fps + 0.5)); |
| 1722 | stream_resource_manager_.SetEncoderRates(rate_settings.rate_control); |
| 1723 | if (layer_allocation_changed && |
| 1724 | allocation_cb_type_ == |
| 1725 | BitrateAllocationCallbackType::kVideoLayersAllocation) { |
| 1726 | sink_->OnVideoLayersAllocationUpdated(CreateVideoLayersAllocation( |
| 1727 | send_codec_, rate_settings.rate_control, encoder_->GetEncoderInfo())); |
| 1728 | } |
| 1729 | } |
| 1730 | if ((allocation_cb_type_ == |
| 1731 | BitrateAllocationCallbackType::kVideoBitrateAllocation) || |
| 1732 | (encoder_config_.content_type == |
| 1733 | VideoEncoderConfig::ContentType::kScreen && |
| 1734 | allocation_cb_type_ == BitrateAllocationCallbackType:: |
| 1735 | kVideoBitrateAllocationWhenScreenSharing)) { |
| 1736 | sink_->OnBitrateAllocationUpdated( |
| 1737 | // Update allocation according to info from encoder. An encoder may |
| 1738 | // choose to not use all layers due to for example HW. |
| 1739 | UpdateAllocationFromEncoderInfo( |
| 1740 | rate_settings.rate_control.target_bitrate, |
| 1741 | encoder_->GetEncoderInfo())); |
| 1742 | } |
| 1743 | } |
| 1744 |
| 1745 | void VideoStreamEncoder::MaybeEncodeVideoFrame(const VideoFrame& video_frame, |
| 1746 | int64_t time_when_posted_us) { |
| 1747 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 1748 | input_state_provider_.OnFrameSizeObserved(video_frame.size()); |
| 1749 |
| 1750 | if (!last_frame_info_ || video_frame.width() != last_frame_info_->width || |
| 1751 | video_frame.height() != last_frame_info_->height || |
| 1752 | video_frame.is_texture() != last_frame_info_->is_texture) { |
| 1753 | if ((!last_frame_info_ || video_frame.width() != last_frame_info_->width || |
| 1754 | video_frame.height() != last_frame_info_->height) && |
| 1755 | settings_.encoder_switch_request_callback && encoder_selector_) { |
| 1756 | if (auto encoder = encoder_selector_->OnResolutionChange( |
| 1757 | {video_frame.width(), video_frame.height()})) { |
| 1758 | settings_.encoder_switch_request_callback->RequestEncoderSwitch( |
| 1759 | *encoder, /*allow_default_fallback=*/false); |
| 1760 | } |
| 1761 | } |
| 1762 |
| 1763 | pending_encoder_reconfiguration_ = true; |
| 1764 | last_frame_info_ = VideoFrameInfo(video_frame.width(), video_frame.height(), |
| 1765 | video_frame.is_texture()); |
| 1766 | RTC_LOG(LS_INFO) << "Video frame parameters changed: dimensions=" |
| 1767 | << last_frame_info_->width << "x" |
| 1768 | << last_frame_info_->height |
| 1769 | << ", texture=" << last_frame_info_->is_texture << "."; |
| 1770 | // Force full frame update, since resolution has changed. |
| 1771 | accumulated_update_rect_ = |
| 1772 | VideoFrame::UpdateRect{0, 0, video_frame.width(), video_frame.height()}; |
| 1773 | } |
| 1774 |
| 1775 | // We have to create the encoder before the frame drop logic, |
| 1776 | // because the latter depends on encoder_->GetScalingSettings. |
| 1777 | // According to the testcase |
| 1778 | // InitialFrameDropOffWhenEncoderDisabledScaling, the return value |
| 1779 | // from GetScalingSettings should enable or disable the frame drop. |
| 1780 |
| 1781 | // Update input frame rate before we start using it. If we update it after |
| 1782 | // any potential frame drop we are going to artificially increase frame sizes. |
| 1783 | // Poll the rate before updating, otherwise we risk the rate being estimated |
| 1784 | // a little too high at the start of the call when then window is small. |
| 1785 | uint32_t framerate_fps = GetInputFramerateFps(); |
| 1786 | frame_cadence_adapter_->UpdateFrameRate(); |
| 1787 |
| 1788 | int64_t now_ms = clock_->TimeInMilliseconds(); |
| 1789 | if (pending_encoder_reconfiguration_) { |
| 1790 | ReconfigureEncoder(); |
| 1791 | last_parameters_update_ms_.emplace(now_ms); |
| 1792 | } else if (!last_parameters_update_ms_ || |
| 1793 | now_ms - *last_parameters_update_ms_ >= |
| 1794 | kParameterUpdateIntervalMs) { |
| 1795 | if (last_encoder_rate_settings_) { |
| 1796 | // Clone rate settings before update, so that SetEncoderRates() will |
| 1797 | // actually detect the change between the input and |
| 1798 | // `last_encoder_rate_setings_`, triggering the call to SetRate() on the |
| 1799 | // encoder. |
| 1800 | EncoderRateSettings new_rate_settings = *last_encoder_rate_settings_; |
| 1801 | new_rate_settings.rate_control.framerate_fps = |
| 1802 | static_cast<double>(framerate_fps); |
| 1803 | SetEncoderRates(UpdateBitrateAllocation(new_rate_settings)); |
| 1804 | } |
| 1805 | last_parameters_update_ms_.emplace(now_ms); |
| 1806 | } |
| 1807 |
| 1808 | // Because pending frame will be dropped in any case, we need to |
| 1809 | // remember its updated region. |
| 1810 | if (pending_frame_) { |
| 1811 | ProcessDroppedFrame(*pending_frame_, |
| 1812 | VideoStreamEncoderObserver::DropReason::kEncoderQueue); |
| 1813 | } |
| 1814 |
| 1815 | if (DropDueToSize(video_frame.size())) { |
| 1816 | RTC_LOG(LS_INFO) << "Dropping frame. Too large for target bitrate."; |
| 1817 | stream_resource_manager_.OnFrameDroppedDueToSize(); |
| 1818 | // Storing references to a native buffer risks blocking frame capture. |
| 1819 | if (video_frame.video_frame_buffer()->type() != |
| 1820 | VideoFrameBuffer::Type::kNative) { |
| 1821 | pending_frame_ = video_frame; |
| 1822 | pending_frame_post_time_us_ = time_when_posted_us; |
| 1823 | } else { |
| 1824 | // Ensure that any previously stored frame is dropped. |
| 1825 | pending_frame_.reset(); |
| 1826 | ProcessDroppedFrame( |
| 1827 | video_frame, VideoStreamEncoderObserver::DropReason::kEncoderQueue); |
| 1828 | } |
| 1829 | return; |
| 1830 | } |
| 1831 | stream_resource_manager_.OnMaybeEncodeFrame(); |
| 1832 |
| 1833 | if (EncoderPaused()) { |
| 1834 | // Storing references to a native buffer risks blocking frame capture. |
| 1835 | if (video_frame.video_frame_buffer()->type() != |
| 1836 | VideoFrameBuffer::Type::kNative) { |
| 1837 | if (pending_frame_) |
| 1838 | TraceFrameDropStart(); |
| 1839 | pending_frame_ = video_frame; |
| 1840 | pending_frame_post_time_us_ = time_when_posted_us; |
| 1841 | } else { |
| 1842 | // Ensure that any previously stored frame is dropped. |
| 1843 | pending_frame_.reset(); |
| 1844 | TraceFrameDropStart(); |
| 1845 | ProcessDroppedFrame( |
| 1846 | video_frame, VideoStreamEncoderObserver::DropReason::kEncoderQueue); |
| 1847 | } |
| 1848 | return; |
| 1849 | } |
| 1850 |
| 1851 | pending_frame_.reset(); |
| 1852 |
| 1853 | frame_dropper_.Leak(framerate_fps); |
| 1854 | // Frame dropping is enabled iff frame dropping is not force-disabled, and |
| 1855 | // rate controller is not trusted. |
| 1856 | const bool frame_dropping_enabled = |
| 1857 | !force_disable_frame_dropper_ && |
| 1858 | !encoder_info_.has_trusted_rate_controller; |
| 1859 | frame_dropper_.Enable(frame_dropping_enabled); |
| 1860 | if (frame_dropping_enabled && frame_dropper_.DropFrame()) { |
| 1861 | RTC_LOG(LS_VERBOSE) |
| 1862 | << "Drop Frame: " |
| 1863 | "target bitrate " |
| 1864 | << (last_encoder_rate_settings_ |
| 1865 | ? last_encoder_rate_settings_->encoder_target.bps() |
| 1866 | : 0) |
| 1867 | << ", input frame rate " << framerate_fps; |
| 1868 | ProcessDroppedFrame( |
| 1869 | video_frame, |
| 1870 | VideoStreamEncoderObserver::DropReason::kMediaOptimization); |
| 1871 | return; |
| 1872 | } |
| 1873 |
| 1874 | EncodeVideoFrame(video_frame, time_when_posted_us); |
| 1875 | } |
| 1876 |
| 1877 | void VideoStreamEncoder::EncodeVideoFrame(const VideoFrame& video_frame, |
| 1878 | int64_t time_when_posted_us) { |
| 1879 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 1880 | RTC_LOG(LS_VERBOSE) << __func__ << " posted " << time_when_posted_us |
| 1881 | << " ntp time " << video_frame.ntp_time_ms(); |
| 1882 |
| 1883 | // If the encoder fail we can't continue to encode frames. When this happens |
| 1884 | // the WebrtcVideoSender is notified and the whole VideoSendStream is |
| 1885 | // recreated. |
| 1886 | if (encoder_failed_ || !encoder_initialized_) |
| 1887 | return; |
| 1888 |
| 1889 | // It's possible that EncodeVideoFrame can be called after we've completed |
| 1890 | // a Stop() operation. Check if the encoder_ is set before continuing. |
| 1891 | // See: bugs.webrtc.org/12857 |
| 1892 | if (!encoder_) |
| 1893 | return; |
| 1894 |
| 1895 | TraceFrameDropEnd(); |
| 1896 |
| 1897 | // Encoder metadata needs to be updated before encode complete callback. |
| 1898 | const VideoEncoder::EncoderInfo info = encoder_->GetEncoderInfo(); |
| 1899 | if (info.implementation_name != encoder_info_.implementation_name || |
| 1900 | info.is_hardware_accelerated != encoder_info_.is_hardware_accelerated) { |
| 1901 | encoder_stats_observer_->OnEncoderImplementationChanged({ |
| 1902 | .name = info.implementation_name, |
| 1903 | .is_hardware_accelerated = info.is_hardware_accelerated, |
| 1904 | }); |
| 1905 | if (bitrate_adjuster_) { |
| 1906 | // Encoder implementation changed, reset overshoot detector states. |
| 1907 | bitrate_adjuster_->Reset(); |
| 1908 | } |
| 1909 | } |
| 1910 |
| 1911 | if (encoder_info_ != info) { |
| 1912 | OnEncoderSettingsChanged(); |
| 1913 | stream_resource_manager_.ConfigureEncodeUsageResource(); |
| 1914 | // Re-configure scalers when encoder info changed. Consider two cases: |
| 1915 | // 1. When the status of the scaler changes from enabled to disabled, if we |
| 1916 | // don't do this CL, scaler will adapt up/down to trigger an unnecessary |
| 1917 | // full ReconfigureEncoder() when the scaler should be banned. |
| 1918 | // 2. When the status of the scaler changes from disabled to enabled, if we |
| 1919 | // don't do this CL, scaler will not work until some code trigger |
| 1920 | // ReconfigureEncoder(). In extreme cases, the scaler doesn't even work for |
| 1921 | // a long time when we expect that the scaler should work. |
| 1922 | stream_resource_manager_.ConfigureQualityScaler(info); |
| 1923 | stream_resource_manager_.ConfigureBandwidthQualityScaler(info); |
| 1924 |
| 1925 | RTC_LOG(LS_INFO) << "[VSE] Encoder info changed to " << info.ToString(); |
| 1926 | } |
| 1927 |
| 1928 | if (bitrate_adjuster_) { |
| 1929 | for (size_t si = 0; si < kMaxSpatialLayers; ++si) { |
| 1930 | if (info.fps_allocation[si] != encoder_info_.fps_allocation[si]) { |
| 1931 | bitrate_adjuster_->OnEncoderInfo(info); |
| 1932 | break; |
| 1933 | } |
| 1934 | } |
| 1935 | } |
| 1936 | encoder_info_ = info; |
| 1937 | last_encode_info_ms_ = clock_->TimeInMilliseconds(); |
| 1938 |
| 1939 | VideoFrame out_frame(video_frame); |
| 1940 | // Crop or scale the frame if needed. Dimension may be reduced to fit encoder |
| 1941 | // requirements, e.g. some encoders may require them to be divisible by 4. |
| 1942 | if ((crop_width_ > 0 || crop_height_ > 0) && |
| 1943 | (out_frame.video_frame_buffer()->type() != |
| 1944 | VideoFrameBuffer::Type::kNative || |
| 1945 | !info.supports_native_handle)) { |
| 1946 | int cropped_width = video_frame.width() - crop_width_; |
| 1947 | int cropped_height = video_frame.height() - crop_height_; |
| 1948 | rtc::scoped_refptr<VideoFrameBuffer> cropped_buffer; |
| 1949 | // TODO(ilnik): Remove scaling if cropping is too big, as it should never |
| 1950 | // happen after SinkWants signaled correctly from ReconfigureEncoder. |
| 1951 | VideoFrame::UpdateRect update_rect = video_frame.update_rect(); |
| 1952 | if (crop_width_ < 4 && crop_height_ < 4) { |
| 1953 | // The difference is small, crop without scaling. |
| 1954 | cropped_buffer = video_frame.video_frame_buffer()->CropAndScale( |
| 1955 | crop_width_ / 2, crop_height_ / 2, cropped_width, cropped_height, |
| 1956 | cropped_width, cropped_height); |
| 1957 | update_rect.offset_x -= crop_width_ / 2; |
| 1958 | update_rect.offset_y -= crop_height_ / 2; |
| 1959 | update_rect.Intersect( |
| 1960 | VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height}); |
| 1961 |
| 1962 | } else { |
| 1963 | // The difference is large, scale it. |
| 1964 | cropped_buffer = video_frame.video_frame_buffer()->Scale(cropped_width, |
| 1965 | cropped_height); |
| 1966 | if (!update_rect.IsEmpty()) { |
| 1967 | // Since we can't reason about pixels after scaling, we invalidate whole |
| 1968 | // picture, if anything changed. |
| 1969 | update_rect = |
| 1970 | VideoFrame::UpdateRect{0, 0, cropped_width, cropped_height}; |
| 1971 | } |
| 1972 | } |
| 1973 | if (!cropped_buffer) { |
| 1974 | RTC_LOG(LS_ERROR) << "Cropping and scaling frame failed, dropping frame."; |
| 1975 | return; |
| 1976 | } |
| 1977 |
| 1978 | out_frame.set_video_frame_buffer(cropped_buffer); |
| 1979 | out_frame.set_update_rect(update_rect); |
| 1980 | out_frame.set_ntp_time_ms(video_frame.ntp_time_ms()); |
| 1981 | out_frame.set_capture_time_identifier( |
| 1982 | video_frame.capture_time_identifier()); |
| 1983 | // Since accumulated_update_rect_ is constructed before cropping, |
| 1984 | // we can't trust it. If any changes were pending, we invalidate whole |
| 1985 | // frame here. |
| 1986 | if (!accumulated_update_rect_.IsEmpty()) { |
| 1987 | accumulated_update_rect_ = |
| 1988 | VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()}; |
| 1989 | accumulated_update_rect_is_valid_ = false; |
| 1990 | } |
| 1991 | } |
| 1992 |
| 1993 | if (!accumulated_update_rect_is_valid_) { |
| 1994 | out_frame.clear_update_rect(); |
| 1995 | } else if (!accumulated_update_rect_.IsEmpty() && |
| 1996 | out_frame.has_update_rect()) { |
| 1997 | accumulated_update_rect_.Union(out_frame.update_rect()); |
| 1998 | accumulated_update_rect_.Intersect( |
| 1999 | VideoFrame::UpdateRect{0, 0, out_frame.width(), out_frame.height()}); |
| 2000 | out_frame.set_update_rect(accumulated_update_rect_); |
| 2001 | accumulated_update_rect_.MakeEmptyUpdate(); |
| 2002 | } |
| 2003 | accumulated_update_rect_is_valid_ = true; |
| 2004 |
| 2005 | TRACE_EVENT_ASYNC_STEP0("webrtc", "Video", video_frame.render_time_ms(), |
| 2006 | "Encode"); |
| 2007 |
| 2008 | stream_resource_manager_.OnEncodeStarted(out_frame, time_when_posted_us); |
| 2009 |
| 2010 | // The encoder should get the size that it expects. |
| 2011 | RTC_DCHECK(send_codec_.width <= out_frame.width() && |
| 2012 | send_codec_.height <= out_frame.height()) |
| 2013 | << "Encoder configured to " << send_codec_.width << "x" |
| 2014 | << send_codec_.height << " received a too small frame " |
| 2015 | << out_frame.width() << "x" << out_frame.height(); |
| 2016 |
| 2017 | TRACE_EVENT1("webrtc", "VCMGenericEncoder::Encode", "timestamp", |
| 2018 | out_frame.timestamp()); |
| 2019 |
| 2020 | frame_encode_metadata_writer_.OnEncodeStarted(out_frame); |
| 2021 |
| 2022 | const int32_t encode_status = encoder_->Encode(out_frame, &next_frame_types_); |
| 2023 | was_encode_called_since_last_initialization_ = true; |
| 2024 |
| 2025 | if (encode_status < 0) { |
| 2026 | RTC_LOG(LS_ERROR) << "Encoder failed, failing encoder format: " |
| 2027 | << encoder_config_.video_format.ToString(); |
| 2028 | RequestEncoderSwitch(); |
| 2029 | return; |
| 2030 | } |
| 2031 |
| 2032 | for (auto& it : next_frame_types_) { |
| 2033 | it = VideoFrameType::kVideoFrameDelta; |
| 2034 | } |
| 2035 | } |
| 2036 |
| 2037 | void VideoStreamEncoder::RequestRefreshFrame() { |
| 2038 | worker_queue_->PostTask(SafeTask(task_safety_.flag(), [this] { |
| 2039 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 2040 | video_source_sink_controller_.RequestRefreshFrame(); |
| 2041 | })); |
| 2042 | } |
| 2043 |
| 2044 | void VideoStreamEncoder::SendKeyFrame( |
| 2045 | const std::vector<VideoFrameType>& layers) { |
| 2046 | if (!encoder_queue_->IsCurrent()) { |
| 2047 | encoder_queue_->PostTask([this, layers] { SendKeyFrame(layers); }); |
| 2048 | return; |
| 2049 | } |
| 2050 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2051 | TRACE_EVENT0("webrtc", "OnKeyFrameRequest"); |
| 2052 | RTC_DCHECK(!next_frame_types_.empty()); |
| 2053 |
| 2054 | if (frame_cadence_adapter_) |
| 2055 | frame_cadence_adapter_->ProcessKeyFrameRequest(); |
| 2056 |
| 2057 | if (!encoder_) { |
| 2058 | RTC_DLOG(LS_INFO) << __func__ << " no encoder."; |
| 2059 | return; // Shutting down, or not configured yet. |
| 2060 | } |
| 2061 |
| 2062 | if (!layers.empty()) { |
| 2063 | RTC_DCHECK_EQ(layers.size(), next_frame_types_.size()); |
| 2064 | for (size_t i = 0; i < layers.size() && i < next_frame_types_.size(); i++) { |
| 2065 | next_frame_types_[i] = layers[i]; |
| 2066 | } |
| 2067 | } else { |
| 2068 | std::fill(next_frame_types_.begin(), next_frame_types_.end(), |
| 2069 | VideoFrameType::kVideoFrameKey); |
| 2070 | } |
| 2071 | } |
| 2072 |
| 2073 | void VideoStreamEncoder::OnLossNotification( |
| 2074 | const VideoEncoder::LossNotification& loss_notification) { |
| 2075 | if (!encoder_queue_->IsCurrent()) { |
| 2076 | encoder_queue_->PostTask( |
| 2077 | [this, loss_notification] { OnLossNotification(loss_notification); }); |
| 2078 | return; |
| 2079 | } |
| 2080 |
| 2081 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2082 | if (encoder_) { |
| 2083 | encoder_->OnLossNotification(loss_notification); |
| 2084 | } |
| 2085 | } |
| 2086 |
| 2087 | EncodedImage VideoStreamEncoder::AugmentEncodedImage( |
| 2088 | const EncodedImage& encoded_image, |
| 2089 | const CodecSpecificInfo* codec_specific_info) { |
| 2090 | EncodedImage image_copy(encoded_image); |
| 2091 | // We could either have simulcast layers or spatial layers. |
| 2092 | // TODO(https://crbug.com/webrtc/14891): If we want to support a mix of |
| 2093 | // simulcast and SVC we'll also need to consider the case where we have both |
| 2094 | // simulcast and spatial indices. |
| 2095 | int stream_idx = encoded_image.SpatialIndex().value_or( |
| 2096 | encoded_image.SimulcastIndex().value_or(0)); |
| 2097 | frame_encode_metadata_writer_.FillTimingInfo(stream_idx, &image_copy); |
| 2098 | frame_encode_metadata_writer_.UpdateBitstream(codec_specific_info, |
| 2099 | &image_copy); |
| 2100 | VideoCodecType codec_type = codec_specific_info |
| 2101 | ? codec_specific_info->codecType |
| 2102 | : VideoCodecType::kVideoCodecGeneric; |
| 2103 | if (image_copy.qp_ < 0 && qp_parsing_allowed_) { |
| 2104 | // Parse encoded frame QP if that was not provided by encoder. |
| 2105 | image_copy.qp_ = |
| 2106 | qp_parser_ |
| 2107 | .Parse(codec_type, stream_idx, image_copy.data(), image_copy.size()) |
| 2108 | .value_or(-1); |
| 2109 | } |
| 2110 | TRACE_EVENT2("webrtc", "VideoStreamEncoder::AugmentEncodedImage", |
| 2111 | "stream_idx", stream_idx, "qp", image_copy.qp_); |
| 2112 | RTC_LOG(LS_VERBOSE) << __func__ << " ntp time " << encoded_image.NtpTimeMs() |
| 2113 | << " stream_idx " << stream_idx << " qp " |
| 2114 | << image_copy.qp_; |
| 2115 | image_copy.SetAtTargetQuality(codec_type == kVideoCodecVP8 && |
| 2116 | image_copy.qp_ <= kVp8SteadyStateQpThreshold); |
| 2117 |
| 2118 | return image_copy; |
| 2119 | } |
| 2120 |
| 2121 | EncodedImageCallback::Result VideoStreamEncoder::OnEncodedImage( |
| 2122 | const EncodedImage& encoded_image, |
| 2123 | const CodecSpecificInfo* codec_specific_info) { |
| 2124 | TRACE_EVENT_INSTANT1("webrtc", "VCMEncodedFrameCallback::Encoded", |
| 2125 | "timestamp", encoded_image.RtpTimestamp()); |
| 2126 |
| 2127 | const size_t simulcast_index = encoded_image.SimulcastIndex().value_or(0); |
| 2128 | const VideoCodecType codec_type = codec_specific_info |
| 2129 | ? codec_specific_info->codecType |
| 2130 | : VideoCodecType::kVideoCodecGeneric; |
| 2131 | EncodedImage image_copy = |
| 2132 | AugmentEncodedImage(encoded_image, codec_specific_info); |
| 2133 |
| 2134 | // Post a task because `send_codec_` requires `encoder_queue_` lock and we |
| 2135 | // need to update on quality convergence. |
| 2136 | unsigned int image_width = image_copy._encodedWidth; |
| 2137 | unsigned int image_height = image_copy._encodedHeight; |
| 2138 | encoder_queue_->PostTask([this, codec_type, image_width, image_height, |
| 2139 | simulcast_index, |
| 2140 | at_target_quality = |
| 2141 | image_copy.IsAtTargetQuality()] { |
| 2142 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2143 |
| 2144 | // Let the frame cadence adapter know about quality convergence. |
| 2145 | if (frame_cadence_adapter_) |
| 2146 | frame_cadence_adapter_->UpdateLayerQualityConvergence(simulcast_index, |
| 2147 | at_target_quality); |
| 2148 |
| 2149 | // Currently, the internal quality scaler is used for VP9 instead of the |
| 2150 | // webrtc qp scaler (in the no-svc case or if only a single spatial layer is |
| 2151 | // encoded). It has to be explicitly detected and reported to adaptation |
| 2152 | // metrics. |
| 2153 | if (codec_type == VideoCodecType::kVideoCodecVP9 && |
| 2154 | send_codec_.VP9()->automaticResizeOn) { |
| 2155 | unsigned int expected_width = send_codec_.width; |
| 2156 | unsigned int expected_height = send_codec_.height; |
| 2157 | int num_active_layers = 0; |
| 2158 | for (int i = 0; i < send_codec_.VP9()->numberOfSpatialLayers; ++i) { |
| 2159 | if (send_codec_.spatialLayers[i].active) { |
| 2160 | ++num_active_layers; |
| 2161 | expected_width = send_codec_.spatialLayers[i].width; |
| 2162 | expected_height = send_codec_.spatialLayers[i].height; |
| 2163 | } |
| 2164 | } |
| 2165 | RTC_DCHECK_LE(num_active_layers, 1) |
| 2166 | << "VP9 quality scaling is enabled for " |
| 2167 | "SVC with several active layers."; |
| 2168 | encoder_stats_observer_->OnEncoderInternalScalerUpdate( |
| 2169 | image_width < expected_width || image_height < expected_height); |
| 2170 | } |
| 2171 | }); |
| 2172 |
| 2173 | // Encoded is called on whatever thread the real encoder implementation run |
| 2174 | // on. In the case of hardware encoders, there might be several encoders |
| 2175 | // running in parallel on different threads. |
| 2176 | encoder_stats_observer_->OnSendEncodedImage(image_copy, codec_specific_info); |
| 2177 |
| 2178 | EncodedImageCallback::Result result = |
| 2179 | sink_->OnEncodedImage(image_copy, codec_specific_info); |
| 2180 |
| 2181 | // We are only interested in propagating the meta-data about the image, not |
| 2182 | // encoded data itself, to the post encode function. Since we cannot be sure |
| 2183 | // the pointer will still be valid when run on the task queue, set it to null. |
| 2184 | DataSize frame_size = DataSize::Bytes(image_copy.size()); |
| 2185 | image_copy.ClearEncodedData(); |
| 2186 |
| 2187 | int temporal_index = 0; |
| 2188 | if (codec_specific_info) { |
| 2189 | if (codec_specific_info->codecType == kVideoCodecVP9) { |
| 2190 | temporal_index = codec_specific_info->codecSpecific.VP9.temporal_idx; |
| 2191 | } else if (codec_specific_info->codecType == kVideoCodecVP8) { |
| 2192 | temporal_index = codec_specific_info->codecSpecific.VP8.temporalIdx; |
| 2193 | } |
| 2194 | } |
| 2195 | if (temporal_index == kNoTemporalIdx) { |
| 2196 | temporal_index = 0; |
| 2197 | } |
| 2198 |
| 2199 | RunPostEncode(image_copy, clock_->CurrentTime().us(), temporal_index, |
| 2200 | frame_size); |
| 2201 |
| 2202 | if (result.error == Result::OK) { |
| 2203 | // In case of an internal encoder running on a separate thread, the |
| 2204 | // decision to drop a frame might be a frame late and signaled via |
| 2205 | // atomic flag. This is because we can't easily wait for the worker thread |
| 2206 | // without risking deadlocks, eg during shutdown when the worker thread |
| 2207 | // might be waiting for the internal encoder threads to stop. |
| 2208 | if (pending_frame_drops_.load() > 0) { |
| 2209 | int pending_drops = pending_frame_drops_.fetch_sub(1); |
| 2210 | RTC_DCHECK_GT(pending_drops, 0); |
| 2211 | result.drop_next_frame = true; |
| 2212 | } |
| 2213 | } |
| 2214 |
| 2215 | return result; |
| 2216 | } |
| 2217 |
| 2218 | void VideoStreamEncoder::OnDroppedFrame(DropReason reason) { |
| 2219 | sink_->OnDroppedFrame(reason); |
| 2220 | encoder_queue_->PostTask([this, reason] { |
| 2221 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2222 | stream_resource_manager_.OnFrameDropped(reason); |
| 2223 | }); |
| 2224 | } |
| 2225 |
| 2226 | DataRate VideoStreamEncoder::UpdateTargetBitrate(DataRate target_bitrate, |
| 2227 | double cwnd_reduce_ratio) { |
| 2228 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2229 | DataRate updated_target_bitrate = target_bitrate; |
| 2230 |
| 2231 | // Drop frames when congestion window pushback ratio is larger than 1 |
| 2232 | // percent and target bitrate is larger than codec min bitrate. |
| 2233 | // When target_bitrate is 0 means codec is paused, skip frame dropping. |
| 2234 | if (cwnd_reduce_ratio > 0.01 && target_bitrate.bps() > 0 && |
| 2235 | target_bitrate.bps() > send_codec_.minBitrate * 1000) { |
| 2236 | int reduce_bitrate_bps = std::min( |
| 2237 | static_cast<int>(target_bitrate.bps() * cwnd_reduce_ratio), |
| 2238 | static_cast<int>(target_bitrate.bps() - send_codec_.minBitrate * 1000)); |
| 2239 | if (reduce_bitrate_bps > 0) { |
| 2240 | // At maximum the congestion window can drop 1/2 frames. |
| 2241 | cwnd_frame_drop_interval_ = std::max( |
| 2242 | 2, static_cast<int>(target_bitrate.bps() / reduce_bitrate_bps)); |
| 2243 | // Reduce target bitrate accordingly. |
| 2244 | updated_target_bitrate = |
| 2245 | target_bitrate - (target_bitrate / cwnd_frame_drop_interval_.value()); |
| 2246 | return updated_target_bitrate; |
| 2247 | } |
| 2248 | } |
| 2249 | cwnd_frame_drop_interval_.reset(); |
| 2250 | return updated_target_bitrate; |
| 2251 | } |
| 2252 |
| 2253 | void VideoStreamEncoder::OnBitrateUpdated(DataRate target_bitrate, |
| 2254 | DataRate stable_target_bitrate, |
| 2255 | DataRate link_allocation, |
| 2256 | uint8_t fraction_lost, |
| 2257 | int64_t round_trip_time_ms, |
| 2258 | double cwnd_reduce_ratio) { |
| 2259 | RTC_DCHECK_GE(link_allocation, target_bitrate); |
| 2260 | if (!encoder_queue_->IsCurrent()) { |
| 2261 | encoder_queue_->PostTask([this, target_bitrate, stable_target_bitrate, |
| 2262 | link_allocation, fraction_lost, |
| 2263 | round_trip_time_ms, cwnd_reduce_ratio] { |
| 2264 | DataRate updated_target_bitrate = |
| 2265 | UpdateTargetBitrate(target_bitrate, cwnd_reduce_ratio); |
| 2266 | OnBitrateUpdated(updated_target_bitrate, stable_target_bitrate, |
| 2267 | link_allocation, fraction_lost, round_trip_time_ms, |
| 2268 | cwnd_reduce_ratio); |
| 2269 | }); |
| 2270 | return; |
| 2271 | } |
| 2272 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2273 |
| 2274 | const bool video_is_suspended = target_bitrate == DataRate::Zero(); |
| 2275 | const bool video_suspension_changed = video_is_suspended != EncoderPaused(); |
| 2276 |
| 2277 | if (!video_is_suspended && settings_.encoder_switch_request_callback && |
| 2278 | encoder_selector_) { |
| 2279 | if (auto encoder = encoder_selector_->OnAvailableBitrate(link_allocation)) { |
| 2280 | settings_.encoder_switch_request_callback->RequestEncoderSwitch( |
| 2281 | *encoder, /*allow_default_fallback=*/false); |
| 2282 | } |
| 2283 | } |
| 2284 |
| 2285 | RTC_DCHECK(sink_) << "sink_ must be set before the encoder is active."; |
| 2286 |
| 2287 | RTC_LOG(LS_VERBOSE) << "OnBitrateUpdated, bitrate " << target_bitrate.bps() |
| 2288 | << " stable bitrate = " << stable_target_bitrate.bps() |
| 2289 | << " link allocation bitrate = " << link_allocation.bps() |
| 2290 | << " packet loss " << static_cast<int>(fraction_lost) |
| 2291 | << " rtt " << round_trip_time_ms; |
| 2292 |
| 2293 | if (encoder_) { |
| 2294 | encoder_->OnPacketLossRateUpdate(static_cast<float>(fraction_lost) / 256.f); |
| 2295 | encoder_->OnRttUpdate(round_trip_time_ms); |
| 2296 | } |
| 2297 |
| 2298 | uint32_t framerate_fps = GetInputFramerateFps(); |
| 2299 | frame_dropper_.SetRates((target_bitrate.bps() + 500) / 1000, framerate_fps); |
| 2300 |
| 2301 | EncoderRateSettings new_rate_settings{ |
| 2302 | VideoBitrateAllocation(), static_cast<double>(framerate_fps), |
| 2303 | link_allocation, target_bitrate, stable_target_bitrate}; |
| 2304 | SetEncoderRates(UpdateBitrateAllocation(new_rate_settings)); |
| 2305 |
| 2306 | if (target_bitrate.bps() != 0) |
| 2307 | encoder_target_bitrate_bps_ = target_bitrate.bps(); |
| 2308 |
| 2309 | stream_resource_manager_.SetTargetBitrate(target_bitrate); |
| 2310 |
| 2311 | if (video_suspension_changed) { |
| 2312 | RTC_LOG(LS_INFO) << "Video suspend state changed to: " |
| 2313 | << (video_is_suspended ? "suspended" : "not suspended"); |
| 2314 | encoder_stats_observer_->OnSuspendChange(video_is_suspended); |
| 2315 |
| 2316 | if (!video_is_suspended && pending_frame_ && |
| 2317 | !DropDueToSize(pending_frame_->size())) { |
| 2318 | // A pending stored frame can be processed. |
| 2319 | int64_t pending_time_us = |
| 2320 | clock_->CurrentTime().us() - pending_frame_post_time_us_; |
| 2321 | if (pending_time_us < kPendingFrameTimeoutMs * 1000) |
| 2322 | EncodeVideoFrame(*pending_frame_, pending_frame_post_time_us_); |
| 2323 | pending_frame_.reset(); |
| 2324 | } else if (!video_is_suspended && !pending_frame_ && |
| 2325 | encoder_paused_and_dropped_frame_) { |
| 2326 | // A frame was enqueued during pause-state, but since it was a native |
| 2327 | // frame we could not store it in `pending_frame_` so request a |
| 2328 | // refresh-frame instead. |
| 2329 | RequestRefreshFrame(); |
| 2330 | } |
| 2331 | } |
| 2332 | } |
| 2333 |
| 2334 | bool VideoStreamEncoder::DropDueToSize(uint32_t source_pixel_count) const { |
| 2335 | if (!encoder_ || !stream_resource_manager_.DropInitialFrames() || |
| 2336 | !encoder_target_bitrate_bps_ || |
| 2337 | !stream_resource_manager_.SingleActiveStreamPixels()) { |
| 2338 | return false; |
| 2339 | } |
| 2340 |
| 2341 | int pixel_count = std::min( |
| 2342 | source_pixel_count, *stream_resource_manager_.SingleActiveStreamPixels()); |
| 2343 |
| 2344 | uint32_t bitrate_bps = |
| 2345 | stream_resource_manager_.UseBandwidthAllocationBps().value_or( |
| 2346 | encoder_target_bitrate_bps_.value()); |
| 2347 |
| 2348 | absl::optional<VideoEncoder::ResolutionBitrateLimits> encoder_bitrate_limits = |
| 2349 | GetEncoderInfoWithBitrateLimitUpdate( |
| 2350 | encoder_->GetEncoderInfo(), encoder_config_, default_limits_allowed_) |
| 2351 | .GetEncoderBitrateLimitsForResolution(pixel_count); |
| 2352 |
| 2353 | if (encoder_bitrate_limits.has_value()) { |
| 2354 | // Use bitrate limits provided by encoder. |
| 2355 | return bitrate_bps < |
| 2356 | static_cast<uint32_t>(encoder_bitrate_limits->min_start_bitrate_bps); |
| 2357 | } |
| 2358 |
| 2359 | if (bitrate_bps < 300000 /* qvga */) { |
| 2360 | return pixel_count > 320 * 240; |
| 2361 | } else if (bitrate_bps < 500000 /* vga */) { |
| 2362 | return pixel_count > 640 * 480; |
| 2363 | } |
| 2364 | return false; |
| 2365 | } |
| 2366 |
| 2367 | void VideoStreamEncoder::OnVideoSourceRestrictionsUpdated( |
| 2368 | VideoSourceRestrictions restrictions, |
| 2369 | const VideoAdaptationCounters& adaptation_counters, |
| 2370 | rtc::scoped_refptr<Resource> reason, |
| 2371 | const VideoSourceRestrictions& unfiltered_restrictions) { |
| 2372 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2373 | RTC_LOG(LS_INFO) << "Updating sink restrictions from " |
| 2374 | << (reason ? reason->Name() : std::string("<null>")) |
| 2375 | << " to " << restrictions.ToString(); |
| 2376 |
| 2377 | if (frame_cadence_adapter_) { |
| 2378 | frame_cadence_adapter_->UpdateVideoSourceRestrictions( |
| 2379 | restrictions.max_frame_rate()); |
| 2380 | } |
| 2381 |
| 2382 | // TODO(webrtc:14451) Split video_source_sink_controller_ |
| 2383 | // so that ownership on restrictions/wants is kept on &encoder_queue_ |
| 2384 | latest_restrictions_ = restrictions; |
| 2385 | worker_queue_->PostTask(SafeTask( |
| 2386 | task_safety_.flag(), [this, restrictions = std::move(restrictions)]() { |
| 2387 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 2388 | video_source_sink_controller_.SetRestrictions(std::move(restrictions)); |
| 2389 | video_source_sink_controller_.PushSourceSinkSettings(); |
| 2390 | })); |
| 2391 | } |
| 2392 |
| 2393 | void VideoStreamEncoder::RunPostEncode(const EncodedImage& encoded_image, |
| 2394 | int64_t time_sent_us, |
| 2395 | int temporal_index, |
| 2396 | DataSize frame_size) { |
| 2397 | if (!encoder_queue_->IsCurrent()) { |
| 2398 | encoder_queue_->PostTask([this, encoded_image, time_sent_us, temporal_index, |
| 2399 | frame_size] { |
| 2400 | RunPostEncode(encoded_image, time_sent_us, temporal_index, frame_size); |
| 2401 | }); |
| 2402 | return; |
| 2403 | } |
| 2404 |
| 2405 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2406 |
| 2407 | absl::optional<int> encode_duration_us; |
| 2408 | if (encoded_image.timing_.flags != VideoSendTiming::kInvalid) { |
| 2409 | encode_duration_us = |
| 2410 | TimeDelta::Millis(encoded_image.timing_.encode_finish_ms - |
| 2411 | encoded_image.timing_.encode_start_ms) |
| 2412 | .us(); |
| 2413 | } |
| 2414 |
| 2415 | // Run post encode tasks, such as overuse detection and frame rate/drop |
| 2416 | // stats for internal encoders. |
| 2417 | const bool keyframe = |
| 2418 | encoded_image._frameType == VideoFrameType::kVideoFrameKey; |
| 2419 |
| 2420 | if (!frame_size.IsZero()) { |
| 2421 | frame_dropper_.Fill(frame_size.bytes(), !keyframe); |
| 2422 | } |
| 2423 |
| 2424 | stream_resource_manager_.OnEncodeCompleted(encoded_image, time_sent_us, |
| 2425 | encode_duration_us, frame_size); |
| 2426 | if (bitrate_adjuster_) { |
| 2427 | // We could either have simulcast layers or spatial layers. |
| 2428 | // TODO(https://crbug.com/webrtc/14891): If we want to support a mix of |
| 2429 | // simulcast and SVC we'll also need to consider the case where we have both |
| 2430 | // simulcast and spatial indices. |
| 2431 | int stream_index = encoded_image.SpatialIndex().value_or( |
| 2432 | encoded_image.SimulcastIndex().value_or(0)); |
| 2433 | bitrate_adjuster_->OnEncodedFrame(frame_size, stream_index, temporal_index); |
| 2434 | } |
| 2435 | } |
| 2436 |
| 2437 | void VideoStreamEncoder::ReleaseEncoder() { |
| 2438 | if (!encoder_ || !encoder_initialized_) { |
| 2439 | return; |
| 2440 | } |
| 2441 | encoder_->Release(); |
| 2442 | encoder_initialized_ = false; |
| 2443 | TRACE_EVENT0("webrtc", "VCMGenericEncoder::Release"); |
| 2444 | } |
| 2445 |
| 2446 | VideoStreamEncoder::AutomaticAnimationDetectionExperiment |
| 2447 | VideoStreamEncoder::ParseAutomatincAnimationDetectionFieldTrial() const { |
| 2448 | AutomaticAnimationDetectionExperiment result; |
| 2449 |
| 2450 | result.Parser()->Parse( |
| 2451 | field_trials_.Lookup("WebRTC-AutomaticAnimationDetectionScreenshare")); |
| 2452 |
| 2453 | if (!result.enabled) { |
| 2454 | RTC_LOG(LS_INFO) << "Automatic animation detection experiment is disabled."; |
| 2455 | return result; |
| 2456 | } |
| 2457 |
| 2458 | RTC_LOG(LS_INFO) << "Automatic animation detection experiment settings:" |
| 2459 | " min_duration_ms=" |
| 2460 | << result.min_duration_ms |
| 2461 | << " min_area_ration=" << result.min_area_ratio |
| 2462 | << " min_fps=" << result.min_fps; |
| 2463 |
| 2464 | return result; |
| 2465 | } |
| 2466 |
| 2467 | void VideoStreamEncoder::CheckForAnimatedContent( |
| 2468 | const VideoFrame& frame, |
| 2469 | int64_t time_when_posted_in_us) { |
| 2470 | if (!automatic_animation_detection_experiment_.enabled || |
| 2471 | encoder_config_.content_type != |
| 2472 | VideoEncoderConfig::ContentType::kScreen || |
| 2473 | stream_resource_manager_.degradation_preference() != |
| 2474 | DegradationPreference::BALANCED) { |
| 2475 | return; |
| 2476 | } |
| 2477 |
| 2478 | if (expect_resize_state_ == ExpectResizeState::kResize && last_frame_info_ && |
| 2479 | last_frame_info_->width != frame.width() && |
| 2480 | last_frame_info_->height != frame.height()) { |
| 2481 | // On applying resolution cap there will be one frame with no/different |
| 2482 | // update, which should be skipped. |
| 2483 | // It can be delayed by several frames. |
| 2484 | expect_resize_state_ = ExpectResizeState::kFirstFrameAfterResize; |
| 2485 | return; |
| 2486 | } |
| 2487 |
| 2488 | if (expect_resize_state_ == ExpectResizeState::kFirstFrameAfterResize) { |
| 2489 | // The first frame after resize should have new, scaled update_rect. |
| 2490 | if (frame.has_update_rect()) { |
| 2491 | last_update_rect_ = frame.update_rect(); |
| 2492 | } else { |
| 2493 | last_update_rect_ = absl::nullopt; |
| 2494 | } |
| 2495 | expect_resize_state_ = ExpectResizeState::kNoResize; |
| 2496 | } |
| 2497 |
| 2498 | bool should_cap_resolution = false; |
| 2499 | if (!frame.has_update_rect()) { |
| 2500 | last_update_rect_ = absl::nullopt; |
| 2501 | animation_start_time_ = Timestamp::PlusInfinity(); |
| 2502 | } else if ((!last_update_rect_ || |
| 2503 | frame.update_rect() != *last_update_rect_)) { |
| 2504 | last_update_rect_ = frame.update_rect(); |
| 2505 | animation_start_time_ = Timestamp::Micros(time_when_posted_in_us); |
| 2506 | } else { |
| 2507 | TimeDelta animation_duration = |
| 2508 | Timestamp::Micros(time_when_posted_in_us) - animation_start_time_; |
| 2509 | float area_ratio = static_cast<float>(last_update_rect_->width * |
| 2510 | last_update_rect_->height) / |
| 2511 | (frame.width() * frame.height()); |
| 2512 | if (animation_duration.ms() >= |
| 2513 | automatic_animation_detection_experiment_.min_duration_ms && |
| 2514 | area_ratio >= |
| 2515 | automatic_animation_detection_experiment_.min_area_ratio && |
| 2516 | encoder_stats_observer_->GetInputFrameRate() >= |
| 2517 | automatic_animation_detection_experiment_.min_fps) { |
| 2518 | should_cap_resolution = true; |
| 2519 | } |
| 2520 | } |
| 2521 | if (cap_resolution_due_to_video_content_ != should_cap_resolution) { |
| 2522 | expect_resize_state_ = should_cap_resolution ? ExpectResizeState::kResize |
| 2523 | : ExpectResizeState::kNoResize; |
| 2524 | cap_resolution_due_to_video_content_ = should_cap_resolution; |
| 2525 | if (should_cap_resolution) { |
| 2526 | RTC_LOG(LS_INFO) << "Applying resolution cap due to animation detection."; |
| 2527 | } else { |
| 2528 | RTC_LOG(LS_INFO) << "Removing resolution cap due to no consistent " |
| 2529 | "animation detection."; |
| 2530 | } |
| 2531 | // TODO(webrtc:14451) Split video_source_sink_controller_ |
| 2532 | // so that ownership on restrictions/wants is kept on &encoder_queue_ |
| 2533 | if (should_cap_resolution) { |
| 2534 | animate_restrictions_ = |
| 2535 | VideoSourceRestrictions(kMaxAnimationPixels, |
| 2536 | /* target_pixels_per_frame= */ absl::nullopt, |
| 2537 | /* max_frame_rate= */ absl::nullopt); |
| 2538 | } else { |
| 2539 | animate_restrictions_.reset(); |
| 2540 | } |
| 2541 |
| 2542 | worker_queue_->PostTask( |
| 2543 | SafeTask(task_safety_.flag(), [this, should_cap_resolution]() { |
| 2544 | RTC_DCHECK_RUN_ON(worker_queue_); |
| 2545 | video_source_sink_controller_.SetPixelsPerFrameUpperLimit( |
| 2546 | should_cap_resolution |
| 2547 | ? absl::optional<size_t>(kMaxAnimationPixels) |
| 2548 | : absl::nullopt); |
| 2549 | video_source_sink_controller_.PushSourceSinkSettings(); |
| 2550 | })); |
| 2551 | } |
| 2552 | } |
| 2553 |
| 2554 | void VideoStreamEncoder::InjectAdaptationResource( |
| 2555 | rtc::scoped_refptr<Resource> resource, |
| 2556 | VideoAdaptationReason reason) { |
| 2557 | encoder_queue_->PostTask([this, resource = std::move(resource), reason] { |
| 2558 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2559 | additional_resources_.push_back(resource); |
| 2560 | stream_resource_manager_.AddResource(resource, reason); |
| 2561 | }); |
| 2562 | } |
| 2563 |
| 2564 | void VideoStreamEncoder::InjectAdaptationConstraint( |
| 2565 | AdaptationConstraint* adaptation_constraint) { |
| 2566 | rtc::Event event; |
| 2567 | encoder_queue_->PostTask([this, adaptation_constraint, &event] { |
| 2568 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2569 | if (!resource_adaptation_processor_) { |
| 2570 | // The VideoStreamEncoder was stopped and the processor destroyed before |
| 2571 | // this task had a chance to execute. No action needed. |
| 2572 | return; |
| 2573 | } |
| 2574 | adaptation_constraints_.push_back(adaptation_constraint); |
| 2575 | video_stream_adapter_->AddAdaptationConstraint(adaptation_constraint); |
| 2576 | event.Set(); |
| 2577 | }); |
| 2578 | event.Wait(rtc::Event::kForever); |
| 2579 | } |
| 2580 |
| 2581 | void VideoStreamEncoder::AddRestrictionsListenerForTesting( |
| 2582 | VideoSourceRestrictionsListener* restrictions_listener) { |
| 2583 | rtc::Event event; |
| 2584 | encoder_queue_->PostTask([this, restrictions_listener, &event] { |
| 2585 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2586 | RTC_DCHECK(resource_adaptation_processor_); |
| 2587 | video_stream_adapter_->AddRestrictionsListener(restrictions_listener); |
| 2588 | event.Set(); |
| 2589 | }); |
| 2590 | event.Wait(rtc::Event::kForever); |
| 2591 | } |
| 2592 |
| 2593 | void VideoStreamEncoder::RemoveRestrictionsListenerForTesting( |
| 2594 | VideoSourceRestrictionsListener* restrictions_listener) { |
| 2595 | rtc::Event event; |
| 2596 | encoder_queue_->PostTask([this, restrictions_listener, &event] { |
| 2597 | RTC_DCHECK_RUN_ON(encoder_queue_.get()); |
| 2598 | RTC_DCHECK(resource_adaptation_processor_); |
| 2599 | video_stream_adapter_->RemoveRestrictionsListener(restrictions_listener); |
| 2600 | event.Set(); |
| 2601 | }); |
| 2602 | event.Wait(rtc::Event::kForever); |
| 2603 | } |
| 2604 |
| 2605 | // RTC_RUN_ON(&encoder_queue_) |
| 2606 | void VideoStreamEncoder::ProcessDroppedFrame( |
| 2607 | const VideoFrame& frame, |
| 2608 | VideoStreamEncoderObserver::DropReason reason) { |
| 2609 | accumulated_update_rect_.Union(frame.update_rect()); |
| 2610 | accumulated_update_rect_is_valid_ &= frame.has_update_rect(); |
| 2611 | if (auto converted_reason = MaybeConvertDropReason(reason)) { |
| 2612 | OnDroppedFrame(*converted_reason); |
| 2613 | } |
| 2614 | encoder_stats_observer_->OnFrameDropped(reason); |
| 2615 | } |
| 2616 |
| 2617 | } // namespace webrtc |
| 2618 |