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