1 /* 2 * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 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 #ifndef VIDEO_VIDEO_STREAM_ENCODER_H_ 12 #define VIDEO_VIDEO_STREAM_ENCODER_H_ 13 14 #include <atomic> 15 #include <map> 16 #include <memory> 17 #include <string> 18 #include <vector> 19 20 #include "api/adaptation/resource.h" 21 #include "api/units/data_rate.h" 22 #include "api/video/video_bitrate_allocator.h" 23 #include "api/video/video_rotation.h" 24 #include "api/video/video_sink_interface.h" 25 #include "api/video/video_stream_encoder_interface.h" 26 #include "api/video/video_stream_encoder_observer.h" 27 #include "api/video/video_stream_encoder_settings.h" 28 #include "api/video_codecs/video_codec.h" 29 #include "api/video_codecs/video_encoder.h" 30 #include "call/adaptation/adaptation_constraint.h" 31 #include "call/adaptation/resource_adaptation_processor.h" 32 #include "call/adaptation/resource_adaptation_processor_interface.h" 33 #include "call/adaptation/video_source_restrictions.h" 34 #include "call/adaptation/video_stream_input_state_provider.h" 35 #include "modules/video_coding/utility/frame_dropper.h" 36 #include "rtc_base/experiments/rate_control_settings.h" 37 #include "rtc_base/numerics/exp_filter.h" 38 #include "rtc_base/race_checker.h" 39 #include "rtc_base/rate_statistics.h" 40 #include "rtc_base/task_queue.h" 41 #include "rtc_base/task_utils/pending_task_safety_flag.h" 42 #include "rtc_base/thread_annotations.h" 43 #include "rtc_base/thread_checker.h" 44 #include "system_wrappers/include/clock.h" 45 #include "video/adaptation/video_stream_encoder_resource_manager.h" 46 #include "video/encoder_bitrate_adjuster.h" 47 #include "video/frame_encode_metadata_writer.h" 48 #include "video/video_source_sink_controller.h" 49 50 namespace webrtc { 51 52 // VideoStreamEncoder represent a video encoder that accepts raw video frames as 53 // input and produces an encoded bit stream. 54 // Usage: 55 // Instantiate. 56 // Call SetSink. 57 // Call SetSource. 58 // Call ConfigureEncoder with the codec settings. 59 // Call Stop() when done. 60 class VideoStreamEncoder : public VideoStreamEncoderInterface, 61 private EncodedImageCallback, 62 public VideoSourceRestrictionsListener { 63 public: 64 VideoStreamEncoder(Clock* clock, 65 uint32_t number_of_cores, 66 VideoStreamEncoderObserver* encoder_stats_observer, 67 const VideoStreamEncoderSettings& settings, 68 std::unique_ptr<OveruseFrameDetector> overuse_detector, 69 TaskQueueFactory* task_queue_factory); 70 ~VideoStreamEncoder() override; 71 72 void AddAdaptationResource(rtc::scoped_refptr<Resource> resource) override; 73 std::vector<rtc::scoped_refptr<Resource>> GetAdaptationResources() override; 74 75 void SetSource(rtc::VideoSourceInterface<VideoFrame>* source, 76 const DegradationPreference& degradation_preference) override; 77 78 void SetSink(EncoderSink* sink, bool rotation_applied) override; 79 80 // TODO(perkj): Can we remove VideoCodec.startBitrate ? 81 void SetStartBitrate(int start_bitrate_bps) override; 82 83 void SetFecControllerOverride( 84 FecControllerOverride* fec_controller_override) override; 85 86 void ConfigureEncoder(VideoEncoderConfig config, 87 size_t max_data_payload_length) override; 88 89 // Permanently stop encoding. After this method has returned, it is 90 // guaranteed that no encoded frames will be delivered to the sink. 91 void Stop() override; 92 93 void SendKeyFrame() override; 94 95 void OnLossNotification( 96 const VideoEncoder::LossNotification& loss_notification) override; 97 98 void OnBitrateUpdated(DataRate target_bitrate, 99 DataRate stable_target_bitrate, 100 DataRate target_headroom, 101 uint8_t fraction_lost, 102 int64_t round_trip_time_ms, 103 double cwnd_reduce_ratio) override; 104 105 DataRate UpdateTargetBitrate(DataRate target_bitrate, 106 double cwnd_reduce_ratio); 107 108 protected: 109 // Used for testing. For example the |ScalingObserverInterface| methods must 110 // be called on |encoder_queue_|. encoder_queue()111 rtc::TaskQueue* encoder_queue() { return &encoder_queue_; } 112 113 void OnVideoSourceRestrictionsUpdated( 114 VideoSourceRestrictions restrictions, 115 const VideoAdaptationCounters& adaptation_counters, 116 rtc::scoped_refptr<Resource> reason, 117 const VideoSourceRestrictions& unfiltered_restrictions) override; 118 119 // Used for injected test resources. 120 // TODO(eshr): Move all adaptation tests out of VideoStreamEncoder tests. 121 void InjectAdaptationResource(rtc::scoped_refptr<Resource> resource, 122 VideoAdaptationReason reason); 123 void InjectAdaptationConstraint(AdaptationConstraint* adaptation_constraint); 124 125 void AddRestrictionsListenerForTesting( 126 VideoSourceRestrictionsListener* restrictions_listener); 127 void RemoveRestrictionsListenerForTesting( 128 VideoSourceRestrictionsListener* restrictions_listener); 129 130 private: 131 class VideoFrameInfo { 132 public: VideoFrameInfo(int width,int height,bool is_texture)133 VideoFrameInfo(int width, int height, bool is_texture) 134 : width(width), height(height), is_texture(is_texture) {} 135 int width; 136 int height; 137 bool is_texture; pixel_count()138 int pixel_count() const { return width * height; } 139 }; 140 141 struct EncoderRateSettings { 142 EncoderRateSettings(); 143 EncoderRateSettings(const VideoBitrateAllocation& bitrate, 144 double framerate_fps, 145 DataRate bandwidth_allocation, 146 DataRate encoder_target, 147 DataRate stable_encoder_target); 148 bool operator==(const EncoderRateSettings& rhs) const; 149 bool operator!=(const EncoderRateSettings& rhs) const; 150 151 VideoEncoder::RateControlParameters rate_control; 152 // This is the scalar target bitrate before the VideoBitrateAllocator, i.e. 153 // the |target_bitrate| argument of the OnBitrateUpdated() method. This is 154 // needed because the bitrate allocator may truncate the total bitrate and a 155 // later call to the same allocator instance, e.g. 156 // |using last_encoder_rate_setings_->bitrate.get_sum_bps()|, may trick it 157 // into thinking the available bitrate has decreased since the last call. 158 DataRate encoder_target; 159 DataRate stable_encoder_target; 160 }; 161 162 class DegradationPreferenceManager; 163 164 void ReconfigureEncoder() RTC_RUN_ON(&encoder_queue_); 165 void OnEncoderSettingsChanged() RTC_RUN_ON(&encoder_queue_); 166 167 // Implements VideoSinkInterface. 168 void OnFrame(const VideoFrame& video_frame) override; 169 void OnDiscardedFrame() override; 170 171 void MaybeEncodeVideoFrame(const VideoFrame& frame, 172 int64_t time_when_posted_in_ms); 173 174 void EncodeVideoFrame(const VideoFrame& frame, 175 int64_t time_when_posted_in_ms); 176 // Indicates wether frame should be dropped because the pixel count is too 177 // large for the current bitrate configuration. 178 bool DropDueToSize(uint32_t pixel_count) const RTC_RUN_ON(&encoder_queue_); 179 180 // Implements EncodedImageCallback. 181 EncodedImageCallback::Result OnEncodedImage( 182 const EncodedImage& encoded_image, 183 const CodecSpecificInfo* codec_specific_info) override; 184 185 void OnDroppedFrame(EncodedImageCallback::DropReason reason) override; 186 187 bool EncoderPaused() const; 188 void TraceFrameDropStart(); 189 void TraceFrameDropEnd(); 190 191 // Returns a copy of |rate_settings| with the |bitrate| field updated using 192 // the current VideoBitrateAllocator. 193 EncoderRateSettings UpdateBitrateAllocation( 194 const EncoderRateSettings& rate_settings) RTC_RUN_ON(&encoder_queue_); 195 196 uint32_t GetInputFramerateFps() RTC_RUN_ON(&encoder_queue_); 197 void SetEncoderRates(const EncoderRateSettings& rate_settings) 198 RTC_RUN_ON(&encoder_queue_); 199 200 void RunPostEncode(const EncodedImage& encoded_image, 201 int64_t time_sent_us, 202 int temporal_index, 203 DataSize frame_size); 204 bool HasInternalSource() const RTC_RUN_ON(&encoder_queue_); 205 void ReleaseEncoder() RTC_RUN_ON(&encoder_queue_); 206 // After calling this function |resource_adaptation_processor_| will be null. 207 void ShutdownResourceAdaptationQueue(); 208 209 void CheckForAnimatedContent(const VideoFrame& frame, 210 int64_t time_when_posted_in_ms) 211 RTC_RUN_ON(&encoder_queue_); 212 213 // TODO(bugs.webrtc.org/11341) : Remove this version of RequestEncoderSwitch. 214 void QueueRequestEncoderSwitch( 215 const EncoderSwitchRequestCallback::Config& conf) 216 RTC_RUN_ON(&encoder_queue_); 217 void QueueRequestEncoderSwitch(const webrtc::SdpVideoFormat& format) 218 RTC_RUN_ON(&encoder_queue_); 219 220 TaskQueueBase* const main_queue_; 221 222 const uint32_t number_of_cores_; 223 224 const bool quality_scaling_experiment_enabled_; 225 226 EncoderSink* sink_; 227 const VideoStreamEncoderSettings settings_; 228 const RateControlSettings rate_control_settings_; 229 230 std::unique_ptr<VideoEncoderFactory::EncoderSelectorInterface> const 231 encoder_selector_; 232 VideoStreamEncoderObserver* const encoder_stats_observer_; 233 234 VideoEncoderConfig encoder_config_ RTC_GUARDED_BY(&encoder_queue_); 235 std::unique_ptr<VideoEncoder> encoder_ RTC_GUARDED_BY(&encoder_queue_) 236 RTC_PT_GUARDED_BY(&encoder_queue_); 237 bool encoder_initialized_; 238 std::unique_ptr<VideoBitrateAllocator> rate_allocator_ 239 RTC_GUARDED_BY(&encoder_queue_) RTC_PT_GUARDED_BY(&encoder_queue_); 240 int max_framerate_ RTC_GUARDED_BY(&encoder_queue_); 241 242 // Set when ConfigureEncoder has been called in order to lazy reconfigure the 243 // encoder on the next frame. 244 bool pending_encoder_reconfiguration_ RTC_GUARDED_BY(&encoder_queue_); 245 // Set when configuration must create a new encoder object, e.g., 246 // because of a codec change. 247 bool pending_encoder_creation_ RTC_GUARDED_BY(&encoder_queue_); 248 249 absl::optional<VideoFrameInfo> last_frame_info_ 250 RTC_GUARDED_BY(&encoder_queue_); 251 int crop_width_ RTC_GUARDED_BY(&encoder_queue_); 252 int crop_height_ RTC_GUARDED_BY(&encoder_queue_); 253 absl::optional<uint32_t> encoder_target_bitrate_bps_ 254 RTC_GUARDED_BY(&encoder_queue_); 255 size_t max_data_payload_length_ RTC_GUARDED_BY(&encoder_queue_); 256 absl::optional<EncoderRateSettings> last_encoder_rate_settings_ 257 RTC_GUARDED_BY(&encoder_queue_); 258 bool encoder_paused_and_dropped_frame_ RTC_GUARDED_BY(&encoder_queue_); 259 260 // Set to true if at least one frame was sent to encoder since last encoder 261 // initialization. 262 bool was_encode_called_since_last_initialization_ 263 RTC_GUARDED_BY(&encoder_queue_); 264 265 bool encoder_failed_ RTC_GUARDED_BY(&encoder_queue_); 266 Clock* const clock_; 267 268 rtc::RaceChecker incoming_frame_race_checker_ 269 RTC_GUARDED_BY(incoming_frame_race_checker_); 270 std::atomic<int> posted_frames_waiting_for_encode_; 271 // Used to make sure incoming time stamp is increasing for every frame. 272 int64_t last_captured_timestamp_ RTC_GUARDED_BY(incoming_frame_race_checker_); 273 // Delta used for translating between NTP and internal timestamps. 274 const int64_t delta_ntp_internal_ms_ 275 RTC_GUARDED_BY(incoming_frame_race_checker_); 276 277 int64_t last_frame_log_ms_ RTC_GUARDED_BY(incoming_frame_race_checker_); 278 int captured_frame_count_ RTC_GUARDED_BY(&encoder_queue_); 279 int dropped_frame_cwnd_pushback_count_ RTC_GUARDED_BY(&encoder_queue_); 280 int dropped_frame_encoder_block_count_ RTC_GUARDED_BY(&encoder_queue_); 281 absl::optional<VideoFrame> pending_frame_ RTC_GUARDED_BY(&encoder_queue_); 282 int64_t pending_frame_post_time_us_ RTC_GUARDED_BY(&encoder_queue_); 283 284 VideoFrame::UpdateRect accumulated_update_rect_ 285 RTC_GUARDED_BY(&encoder_queue_); 286 bool accumulated_update_rect_is_valid_ RTC_GUARDED_BY(&encoder_queue_); 287 288 // Used for automatic content type detection. 289 absl::optional<VideoFrame::UpdateRect> last_update_rect_ 290 RTC_GUARDED_BY(&encoder_queue_); 291 Timestamp animation_start_time_ RTC_GUARDED_BY(&encoder_queue_); 292 bool cap_resolution_due_to_video_content_ RTC_GUARDED_BY(&encoder_queue_); 293 // Used to correctly ignore changes in update_rect introduced by 294 // resize triggered by animation detection. 295 enum class ExpectResizeState { 296 kNoResize, // Normal operation. 297 kResize, // Resize was triggered by the animation detection. 298 kFirstFrameAfterResize // Resize observed. 299 } expect_resize_state_ RTC_GUARDED_BY(&encoder_queue_); 300 301 FecControllerOverride* fec_controller_override_ 302 RTC_GUARDED_BY(&encoder_queue_); 303 absl::optional<int64_t> last_parameters_update_ms_ 304 RTC_GUARDED_BY(&encoder_queue_); 305 absl::optional<int64_t> last_encode_info_ms_ RTC_GUARDED_BY(&encoder_queue_); 306 307 VideoEncoder::EncoderInfo encoder_info_ RTC_GUARDED_BY(&encoder_queue_); 308 absl::optional<VideoEncoder::ResolutionBitrateLimits> encoder_bitrate_limits_ 309 RTC_GUARDED_BY(&encoder_queue_); 310 VideoEncoderFactory::CodecInfo codec_info_ RTC_GUARDED_BY(&encoder_queue_); 311 VideoCodec send_codec_ RTC_GUARDED_BY(&encoder_queue_); 312 313 FrameDropper frame_dropper_ RTC_GUARDED_BY(&encoder_queue_); 314 // If frame dropper is not force disabled, frame dropping might still be 315 // disabled if VideoEncoder::GetEncoderInfo() indicates that the encoder has a 316 // trusted rate controller. This is determined on a per-frame basis, as the 317 // encoder behavior might dynamically change. 318 bool force_disable_frame_dropper_ RTC_GUARDED_BY(&encoder_queue_); 319 RateStatistics input_framerate_ RTC_GUARDED_BY(&encoder_queue_); 320 // Incremented on worker thread whenever |frame_dropper_| determines that a 321 // frame should be dropped. Decremented on whichever thread runs 322 // OnEncodedImage(), which is only called by one thread but not necessarily 323 // the worker thread. 324 std::atomic<int> pending_frame_drops_; 325 326 // Congestion window frame drop ratio (drop 1 in every 327 // cwnd_frame_drop_interval_ frames). 328 absl::optional<int> cwnd_frame_drop_interval_ RTC_GUARDED_BY(&encoder_queue_); 329 // Frame counter for congestion window frame drop. 330 int cwnd_frame_counter_ RTC_GUARDED_BY(&encoder_queue_); 331 332 std::unique_ptr<EncoderBitrateAdjuster> bitrate_adjuster_ 333 RTC_GUARDED_BY(&encoder_queue_); 334 335 // TODO(sprang): Change actually support keyframe per simulcast stream, or 336 // turn this into a simple bool |pending_keyframe_request_|. 337 std::vector<VideoFrameType> next_frame_types_ RTC_GUARDED_BY(&encoder_queue_); 338 339 FrameEncodeMetadataWriter frame_encode_metadata_writer_; 340 341 // Experiment groups parsed from field trials for realtime video ([0]) and 342 // screenshare ([1]). 0 means no group specified. Positive values are 343 // experiment group numbers incremented by 1. 344 const std::array<uint8_t, 2> experiment_groups_; 345 346 struct EncoderSwitchExperiment { 347 struct Thresholds { 348 absl::optional<DataRate> bitrate; 349 absl::optional<int> pixel_count; 350 }; 351 352 // Codec --> switching thresholds 353 std::map<VideoCodecType, Thresholds> codec_thresholds; 354 355 // To smooth out the target bitrate so that we don't trigger a switch 356 // too easily. 357 rtc::ExpFilter bitrate_filter{1.0}; 358 359 // Codec/implementation to switch to 360 std::string to_codec; 361 absl::optional<std::string> to_param; 362 absl::optional<std::string> to_value; 363 364 // Thresholds for the currently used codecs. 365 Thresholds current_thresholds; 366 367 // Updates the |bitrate_filter|, so not const. 368 bool IsBitrateBelowThreshold(const DataRate& target_bitrate); 369 bool IsPixelCountBelowThreshold(int pixel_count) const; 370 void SetCodec(VideoCodecType codec); 371 }; 372 373 EncoderSwitchExperiment ParseEncoderSwitchFieldTrial() const; 374 375 EncoderSwitchExperiment encoder_switch_experiment_ 376 RTC_GUARDED_BY(&encoder_queue_); 377 378 struct AutomaticAnimationDetectionExperiment { 379 bool enabled = false; 380 int min_duration_ms = 2000; 381 double min_area_ratio = 0.8; 382 int min_fps = 10; ParserAutomaticAnimationDetectionExperiment383 std::unique_ptr<StructParametersParser> Parser() { 384 return StructParametersParser::Create( 385 "enabled", &enabled, // 386 "min_duration_ms", &min_duration_ms, // 387 "min_area_ratio", &min_area_ratio, // 388 "min_fps", &min_fps); 389 } 390 }; 391 392 AutomaticAnimationDetectionExperiment 393 ParseAutomatincAnimationDetectionFieldTrial() const; 394 395 AutomaticAnimationDetectionExperiment 396 automatic_animation_detection_experiment_ RTC_GUARDED_BY(&encoder_queue_); 397 398 // An encoder switch is only requested once, this variable is used to keep 399 // track of whether a request has been made or not. 400 bool encoder_switch_requested_ RTC_GUARDED_BY(&encoder_queue_); 401 402 // Provies video stream input states: current resolution and frame rate. 403 VideoStreamInputStateProvider input_state_provider_; 404 405 std::unique_ptr<VideoStreamAdapter> video_stream_adapter_ 406 RTC_GUARDED_BY(&encoder_queue_); 407 // Responsible for adapting input resolution or frame rate to ensure resources 408 // (e.g. CPU or bandwidth) are not overused. Adding resources can occur on any 409 // thread. 410 std::unique_ptr<ResourceAdaptationProcessorInterface> 411 resource_adaptation_processor_; 412 std::unique_ptr<DegradationPreferenceManager> degradation_preference_manager_ 413 RTC_GUARDED_BY(&encoder_queue_); 414 std::vector<AdaptationConstraint*> adaptation_constraints_ 415 RTC_GUARDED_BY(&encoder_queue_); 416 // Handles input, output and stats reporting related to VideoStreamEncoder 417 // specific resources, such as "encode usage percent" measurements and "QP 418 // scaling". Also involved with various mitigations such as inital frame 419 // dropping. 420 // The manager primarily operates on the |encoder_queue_| but its lifetime is 421 // tied to the VideoStreamEncoder (which is destroyed off the encoder queue) 422 // and its resource list is accessible from any thread. 423 VideoStreamEncoderResourceManager stream_resource_manager_ 424 RTC_GUARDED_BY(&encoder_queue_); 425 std::vector<rtc::scoped_refptr<Resource>> additional_resources_ 426 RTC_GUARDED_BY(&encoder_queue_); 427 // Carries out the VideoSourceRestrictions provided by the 428 // ResourceAdaptationProcessor, i.e. reconfigures the source of video frames 429 // to provide us with different resolution or frame rate. 430 // This class is thread-safe. 431 VideoSourceSinkController video_source_sink_controller_ 432 RTC_GUARDED_BY(main_queue_); 433 434 // Public methods are proxied to the task queues. The queues must be destroyed 435 // first to make sure no tasks run that use other members. 436 rtc::TaskQueue encoder_queue_; 437 438 // Used to cancel any potentially pending tasks to the main thread. 439 ScopedTaskSafety task_safety_; 440 441 RTC_DISALLOW_COPY_AND_ASSIGN(VideoStreamEncoder); 442 }; 443 444 } // namespace webrtc 445 446 #endif // VIDEO_VIDEO_STREAM_ENCODER_H_ 447