You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

437 lines
18 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  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/units/data_rate.h"
  18. #include "api/video/video_bitrate_allocator.h"
  19. #include "api/video/video_rotation.h"
  20. #include "api/video/video_sink_interface.h"
  21. #include "api/video/video_stream_encoder_interface.h"
  22. #include "api/video/video_stream_encoder_observer.h"
  23. #include "api/video/video_stream_encoder_settings.h"
  24. #include "api/video_codecs/video_codec.h"
  25. #include "api/video_codecs/video_encoder.h"
  26. #include "modules/video_coding/utility/frame_dropper.h"
  27. #include "modules/video_coding/utility/quality_scaler.h"
  28. #include "rtc_base/critical_section.h"
  29. #include "rtc_base/event.h"
  30. #include "rtc_base/experiments/balanced_degradation_settings.h"
  31. #include "rtc_base/experiments/quality_scaler_settings.h"
  32. #include "rtc_base/experiments/rate_control_settings.h"
  33. #include "rtc_base/numerics/exp_filter.h"
  34. #include "rtc_base/race_checker.h"
  35. #include "rtc_base/rate_statistics.h"
  36. #include "rtc_base/synchronization/sequence_checker.h"
  37. #include "rtc_base/task_queue.h"
  38. #include "system_wrappers/include/clock.h"
  39. #include "video/encoder_bitrate_adjuster.h"
  40. #include "video/frame_encode_metadata_writer.h"
  41. #include "video/overuse_frame_detector.h"
  42. namespace webrtc {
  43. // VideoStreamEncoder represent a video encoder that accepts raw video frames as
  44. // input and produces an encoded bit stream.
  45. // Usage:
  46. // Instantiate.
  47. // Call SetSink.
  48. // Call SetSource.
  49. // Call ConfigureEncoder with the codec settings.
  50. // Call Stop() when done.
  51. class VideoStreamEncoder : public VideoStreamEncoderInterface,
  52. private EncodedImageCallback,
  53. // Protected only to provide access to tests.
  54. protected AdaptationObserverInterface {
  55. public:
  56. VideoStreamEncoder(Clock* clock,
  57. uint32_t number_of_cores,
  58. VideoStreamEncoderObserver* encoder_stats_observer,
  59. const VideoStreamEncoderSettings& settings,
  60. std::unique_ptr<OveruseFrameDetector> overuse_detector,
  61. TaskQueueFactory* task_queue_factory);
  62. ~VideoStreamEncoder() override;
  63. void SetSource(rtc::VideoSourceInterface<VideoFrame>* source,
  64. const DegradationPreference& degradation_preference) override;
  65. void SetSink(EncoderSink* sink, bool rotation_applied) override;
  66. // TODO(perkj): Can we remove VideoCodec.startBitrate ?
  67. void SetStartBitrate(int start_bitrate_bps) override;
  68. void SetBitrateAllocationObserver(
  69. VideoBitrateAllocationObserver* bitrate_observer) override;
  70. void SetFecControllerOverride(
  71. FecControllerOverride* fec_controller_override) override;
  72. void ConfigureEncoder(VideoEncoderConfig config,
  73. size_t max_data_payload_length) override;
  74. // Permanently stop encoding. After this method has returned, it is
  75. // guaranteed that no encoded frames will be delivered to the sink.
  76. void Stop() override;
  77. void SendKeyFrame() override;
  78. void OnLossNotification(
  79. const VideoEncoder::LossNotification& loss_notification) override;
  80. void OnBitrateUpdated(DataRate target_bitrate,
  81. DataRate stable_target_bitrate,
  82. DataRate target_headroom,
  83. uint8_t fraction_lost,
  84. int64_t round_trip_time_ms) override;
  85. protected:
  86. // Used for testing. For example the |ScalingObserverInterface| methods must
  87. // be called on |encoder_queue_|.
  88. rtc::TaskQueue* encoder_queue() { return &encoder_queue_; }
  89. // AdaptationObserverInterface implementation.
  90. // These methods are protected for easier testing.
  91. void AdaptUp(AdaptReason reason) override;
  92. bool AdaptDown(AdaptReason reason) override;
  93. private:
  94. class VideoSourceProxy;
  95. class VideoFrameInfo {
  96. public:
  97. VideoFrameInfo(int width, int height, bool is_texture)
  98. : width(width), height(height), is_texture(is_texture) {}
  99. int width;
  100. int height;
  101. bool is_texture;
  102. int pixel_count() const { return width * height; }
  103. };
  104. struct EncoderRateSettings {
  105. EncoderRateSettings();
  106. EncoderRateSettings(const VideoBitrateAllocation& bitrate,
  107. double framerate_fps,
  108. DataRate bandwidth_allocation,
  109. DataRate encoder_target,
  110. DataRate stable_encoder_target);
  111. bool operator==(const EncoderRateSettings& rhs) const;
  112. bool operator!=(const EncoderRateSettings& rhs) const;
  113. VideoEncoder::RateControlParameters rate_control;
  114. // This is the scalar target bitrate before the VideoBitrateAllocator, i.e.
  115. // the |target_bitrate| argument of the OnBitrateUpdated() method. This is
  116. // needed because the bitrate allocator may truncate the total bitrate and a
  117. // later call to the same allocator instance, e.g.
  118. // |using last_encoder_rate_setings_->bitrate.get_sum_bps()|, may trick it
  119. // into thinking the available bitrate has decreased since the last call.
  120. DataRate encoder_target;
  121. DataRate stable_encoder_target;
  122. };
  123. void ReconfigureEncoder() RTC_RUN_ON(&encoder_queue_);
  124. void ConfigureQualityScaler(const VideoEncoder::EncoderInfo& encoder_info);
  125. // Implements VideoSinkInterface.
  126. void OnFrame(const VideoFrame& video_frame) override;
  127. void OnDiscardedFrame() override;
  128. void MaybeEncodeVideoFrame(const VideoFrame& frame,
  129. int64_t time_when_posted_in_ms);
  130. void EncodeVideoFrame(const VideoFrame& frame,
  131. int64_t time_when_posted_in_ms);
  132. // Indicates wether frame should be dropped because the pixel count is too
  133. // large for the current bitrate configuration.
  134. bool DropDueToSize(uint32_t pixel_count) const RTC_RUN_ON(&encoder_queue_);
  135. // Implements EncodedImageCallback.
  136. EncodedImageCallback::Result OnEncodedImage(
  137. const EncodedImage& encoded_image,
  138. const CodecSpecificInfo* codec_specific_info,
  139. const RTPFragmentationHeader* fragmentation) override;
  140. void OnDroppedFrame(EncodedImageCallback::DropReason reason) override;
  141. bool EncoderPaused() const;
  142. void TraceFrameDropStart();
  143. void TraceFrameDropEnd();
  144. // Returns a copy of |rate_settings| with the |bitrate| field updated using
  145. // the current VideoBitrateAllocator, and notifies any listeners of the new
  146. // allocation.
  147. EncoderRateSettings UpdateBitrateAllocationAndNotifyObserver(
  148. const EncoderRateSettings& rate_settings) RTC_RUN_ON(&encoder_queue_);
  149. uint32_t GetInputFramerateFps() RTC_RUN_ON(&encoder_queue_);
  150. void SetEncoderRates(const EncoderRateSettings& rate_settings)
  151. RTC_RUN_ON(&encoder_queue_);
  152. // Class holding adaptation information.
  153. class AdaptCounter final {
  154. public:
  155. AdaptCounter();
  156. ~AdaptCounter();
  157. // Get number of adaptation downscales for |reason|.
  158. VideoStreamEncoderObserver::AdaptationSteps Counts(int reason) const;
  159. std::string ToString() const;
  160. void IncrementFramerate(int reason);
  161. void IncrementResolution(int reason);
  162. void DecrementFramerate(int reason);
  163. void DecrementResolution(int reason);
  164. void DecrementFramerate(int reason, int cur_fps);
  165. // Gets the total number of downgrades (for all adapt reasons).
  166. int FramerateCount() const;
  167. int ResolutionCount() const;
  168. // Gets the total number of downgrades for |reason|.
  169. int FramerateCount(int reason) const;
  170. int ResolutionCount(int reason) const;
  171. int TotalCount(int reason) const;
  172. private:
  173. std::string ToString(const std::vector<int>& counters) const;
  174. int Count(const std::vector<int>& counters) const;
  175. void MoveCount(std::vector<int>* counters, int from_reason);
  176. // Degradation counters holding number of framerate/resolution reductions
  177. // per adapt reason.
  178. std::vector<int> fps_counters_;
  179. std::vector<int> resolution_counters_;
  180. };
  181. AdaptCounter& GetAdaptCounter() RTC_RUN_ON(&encoder_queue_);
  182. const AdaptCounter& GetConstAdaptCounter() RTC_RUN_ON(&encoder_queue_);
  183. void UpdateAdaptationStats(AdaptReason reason) RTC_RUN_ON(&encoder_queue_);
  184. VideoStreamEncoderObserver::AdaptationSteps GetActiveCounts(
  185. AdaptReason reason) RTC_RUN_ON(&encoder_queue_);
  186. bool CanAdaptUpResolution(int pixels, uint32_t bitrate_bps) const
  187. RTC_RUN_ON(&encoder_queue_);
  188. void RunPostEncode(EncodedImage encoded_image,
  189. int64_t time_sent_us,
  190. int temporal_index);
  191. bool HasInternalSource() const RTC_RUN_ON(&encoder_queue_);
  192. void ReleaseEncoder() RTC_RUN_ON(&encoder_queue_);
  193. rtc::Event shutdown_event_;
  194. const uint32_t number_of_cores_;
  195. // Counts how many frames we've dropped in the initial framedrop phase.
  196. int initial_framedrop_;
  197. const bool initial_framedrop_on_bwe_enabled_;
  198. bool has_seen_first_significant_bwe_change_ = false;
  199. const bool quality_scaling_experiment_enabled_;
  200. const std::unique_ptr<VideoSourceProxy> source_proxy_;
  201. EncoderSink* sink_;
  202. const VideoStreamEncoderSettings settings_;
  203. const RateControlSettings rate_control_settings_;
  204. const QualityScalerSettings quality_scaler_settings_;
  205. const std::unique_ptr<OveruseFrameDetector> overuse_detector_
  206. RTC_PT_GUARDED_BY(&encoder_queue_);
  207. std::unique_ptr<QualityScaler> quality_scaler_ RTC_GUARDED_BY(&encoder_queue_)
  208. RTC_PT_GUARDED_BY(&encoder_queue_);
  209. VideoStreamEncoderObserver* const encoder_stats_observer_;
  210. // |thread_checker_| checks that public methods that are related to lifetime
  211. // of VideoStreamEncoder are called on the same thread.
  212. rtc::ThreadChecker thread_checker_;
  213. VideoEncoderConfig encoder_config_ RTC_GUARDED_BY(&encoder_queue_);
  214. std::unique_ptr<VideoEncoder> encoder_ RTC_GUARDED_BY(&encoder_queue_)
  215. RTC_PT_GUARDED_BY(&encoder_queue_);
  216. bool encoder_initialized_;
  217. std::unique_ptr<VideoBitrateAllocator> rate_allocator_
  218. RTC_GUARDED_BY(&encoder_queue_) RTC_PT_GUARDED_BY(&encoder_queue_);
  219. // The maximum frame rate of the current codec configuration, as determined
  220. // at the last ReconfigureEncoder() call.
  221. int max_framerate_ RTC_GUARDED_BY(&encoder_queue_);
  222. // Set when ConfigureEncoder has been called in order to lazy reconfigure the
  223. // encoder on the next frame.
  224. bool pending_encoder_reconfiguration_ RTC_GUARDED_BY(&encoder_queue_);
  225. // Set when configuration must create a new encoder object, e.g.,
  226. // because of a codec change.
  227. bool pending_encoder_creation_ RTC_GUARDED_BY(&encoder_queue_);
  228. absl::optional<VideoFrameInfo> last_frame_info_
  229. RTC_GUARDED_BY(&encoder_queue_);
  230. int crop_width_ RTC_GUARDED_BY(&encoder_queue_);
  231. int crop_height_ RTC_GUARDED_BY(&encoder_queue_);
  232. uint32_t encoder_start_bitrate_bps_ RTC_GUARDED_BY(&encoder_queue_);
  233. int set_start_bitrate_bps_ RTC_GUARDED_BY(&encoder_queue_);
  234. int64_t set_start_bitrate_time_ms_ RTC_GUARDED_BY(&encoder_queue_);
  235. bool has_seen_first_bwe_drop_ RTC_GUARDED_BY(&encoder_queue_);
  236. size_t max_data_payload_length_ RTC_GUARDED_BY(&encoder_queue_);
  237. absl::optional<EncoderRateSettings> last_encoder_rate_settings_
  238. RTC_GUARDED_BY(&encoder_queue_);
  239. bool encoder_paused_and_dropped_frame_ RTC_GUARDED_BY(&encoder_queue_);
  240. // Set to true if at least one frame was sent to encoder since last encoder
  241. // initialization.
  242. bool was_encode_called_since_last_initialization_
  243. RTC_GUARDED_BY(&encoder_queue_);
  244. bool encoder_failed_ RTC_GUARDED_BY(&encoder_queue_);
  245. Clock* const clock_;
  246. // Counters used for deciding if the video resolution or framerate is
  247. // currently restricted, and if so, why, on a per degradation preference
  248. // basis.
  249. // TODO(sprang): Replace this with a state holding a relative overuse measure
  250. // instead, that can be translated into suitable down-scale or fps limit.
  251. std::map<const DegradationPreference, AdaptCounter> adapt_counters_
  252. RTC_GUARDED_BY(&encoder_queue_);
  253. // Set depending on degradation preferences.
  254. DegradationPreference degradation_preference_ RTC_GUARDED_BY(&encoder_queue_);
  255. const BalancedDegradationSettings balanced_settings_;
  256. struct AdaptationRequest {
  257. // The pixel count produced by the source at the time of the adaptation.
  258. int input_pixel_count_;
  259. // Framerate received from the source at the time of the adaptation.
  260. int framerate_fps_;
  261. // Indicates if request was to adapt up or down.
  262. enum class Mode { kAdaptUp, kAdaptDown } mode_;
  263. };
  264. // Stores a snapshot of the last adaptation request triggered by an AdaptUp
  265. // or AdaptDown signal.
  266. absl::optional<AdaptationRequest> last_adaptation_request_
  267. RTC_GUARDED_BY(&encoder_queue_);
  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. int64_t last_frame_log_ms_ RTC_GUARDED_BY(incoming_frame_race_checker_);
  277. int captured_frame_count_ RTC_GUARDED_BY(&encoder_queue_);
  278. int dropped_frame_count_ RTC_GUARDED_BY(&encoder_queue_);
  279. absl::optional<VideoFrame> pending_frame_ RTC_GUARDED_BY(&encoder_queue_);
  280. int64_t pending_frame_post_time_us_ RTC_GUARDED_BY(&encoder_queue_);
  281. VideoFrame::UpdateRect accumulated_update_rect_
  282. RTC_GUARDED_BY(&encoder_queue_);
  283. VideoBitrateAllocationObserver* bitrate_observer_
  284. RTC_GUARDED_BY(&encoder_queue_);
  285. FecControllerOverride* fec_controller_override_
  286. RTC_GUARDED_BY(&encoder_queue_);
  287. absl::optional<int64_t> last_parameters_update_ms_
  288. RTC_GUARDED_BY(&encoder_queue_);
  289. absl::optional<int64_t> last_encode_info_ms_ RTC_GUARDED_BY(&encoder_queue_);
  290. VideoEncoder::EncoderInfo encoder_info_ RTC_GUARDED_BY(&encoder_queue_);
  291. absl::optional<VideoEncoder::ResolutionBitrateLimits> encoder_bitrate_limits_
  292. RTC_GUARDED_BY(&encoder_queue_);
  293. VideoEncoderFactory::CodecInfo codec_info_ RTC_GUARDED_BY(&encoder_queue_);
  294. VideoCodec send_codec_ RTC_GUARDED_BY(&encoder_queue_);
  295. FrameDropper frame_dropper_ RTC_GUARDED_BY(&encoder_queue_);
  296. // If frame dropper is not force disabled, frame dropping might still be
  297. // disabled if VideoEncoder::GetEncoderInfo() indicates that the encoder has a
  298. // trusted rate controller. This is determined on a per-frame basis, as the
  299. // encoder behavior might dynamically change.
  300. bool force_disable_frame_dropper_ RTC_GUARDED_BY(&encoder_queue_);
  301. RateStatistics input_framerate_ RTC_GUARDED_BY(&encoder_queue_);
  302. // Incremented on worker thread whenever |frame_dropper_| determines that a
  303. // frame should be dropped. Decremented on whichever thread runs
  304. // OnEncodedImage(), which is only called by one thread but not necessarily
  305. // the worker thread.
  306. std::atomic<int> pending_frame_drops_;
  307. std::unique_ptr<EncoderBitrateAdjuster> bitrate_adjuster_
  308. RTC_GUARDED_BY(&encoder_queue_);
  309. // TODO(sprang): Change actually support keyframe per simulcast stream, or
  310. // turn this into a simple bool |pending_keyframe_request_|.
  311. std::vector<VideoFrameType> next_frame_types_ RTC_GUARDED_BY(&encoder_queue_);
  312. FrameEncodeMetadataWriter frame_encode_metadata_writer_;
  313. // Experiment groups parsed from field trials for realtime video ([0]) and
  314. // screenshare ([1]). 0 means no group specified. Positive values are
  315. // experiment group numbers incremented by 1.
  316. const std::array<uint8_t, 2> experiment_groups_;
  317. // TODO(philipel): Remove this lock and run on |encoder_queue_| instead.
  318. rtc::CriticalSection encoded_image_lock_;
  319. int64_t next_frame_id_ RTC_GUARDED_BY(encoded_image_lock_);
  320. // This array is used as a map from simulcast id to an encoder's buffer
  321. // state. For every buffer of the encoder we keep track of the last frame id
  322. // that updated that buffer.
  323. std::array<std::array<int64_t, kMaxEncoderBuffers>, kMaxSimulcastStreams>
  324. encoder_buffer_state_ RTC_GUARDED_BY(encoded_image_lock_);
  325. struct EncoderSwitchExperiment {
  326. struct Thresholds {
  327. absl::optional<DataRate> bitrate;
  328. absl::optional<int> pixel_count;
  329. };
  330. // Codec --> switching thresholds
  331. std::map<VideoCodecType, Thresholds> codec_thresholds;
  332. // To smooth out the target bitrate so that we don't trigger a switch
  333. // too easily.
  334. rtc::ExpFilter bitrate_filter{1.0};
  335. // Codec/implementation to switch to
  336. std::string to_codec;
  337. absl::optional<std::string> to_param;
  338. absl::optional<std::string> to_value;
  339. // Thresholds for the currently used codecs.
  340. Thresholds current_thresholds;
  341. // Updates the |bitrate_filter|, so not const.
  342. bool IsBitrateBelowThreshold(const DataRate& target_bitrate);
  343. bool IsPixelCountBelowThreshold(int pixel_count) const;
  344. void SetCodec(VideoCodecType codec);
  345. };
  346. EncoderSwitchExperiment ParseEncoderSwitchFieldTrial() const;
  347. EncoderSwitchExperiment encoder_switch_experiment_
  348. RTC_GUARDED_BY(&encoder_queue_);
  349. // An encoder switch is only requested once, this variable is used to keep
  350. // track of whether a request has been made or not.
  351. bool encoder_switch_requested_ RTC_GUARDED_BY(&encoder_queue_);
  352. // All public methods are proxied to |encoder_queue_|. It must must be
  353. // destroyed first to make sure no tasks are run that use other members.
  354. rtc::TaskQueue encoder_queue_;
  355. RTC_DISALLOW_COPY_AND_ASSIGN(VideoStreamEncoder);
  356. };
  357. } // namespace webrtc
  358. #endif // VIDEO_VIDEO_STREAM_ENCODER_H_