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