video_stream_encoder.h 19 KB

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