video_stream_encoder.h 19 KB

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