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