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.

387 lines
16 KiB

​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
​
  1. /*
  2. * Copyright (c) 2014 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 API_VIDEO_CODECS_VIDEO_ENCODER_H_
  11. #define API_VIDEO_CODECS_VIDEO_ENCODER_H_
  12. #include <limits>
  13. #include <memory>
  14. #include <string>
  15. #include <vector>
  16. #include "absl/container/inlined_vector.h"
  17. #include "absl/types/optional.h"
  18. #include "api/fec_controller_override.h"
  19. #include "api/units/data_rate.h"
  20. #include "api/video/encoded_image.h"
  21. #include "api/video/video_bitrate_allocation.h"
  22. #include "api/video/video_codec_constants.h"
  23. #include "api/video/video_frame.h"
  24. #include "api/video_codecs/video_codec.h"
  25. #include "rtc_base/checks.h"
  26. #include "rtc_base/system/rtc_export.h"
  27. namespace webrtc {
  28. class RTPFragmentationHeader;
  29. // TODO(pbos): Expose these through a public (root) header or change these APIs.
  30. struct CodecSpecificInfo;
  31. class EncodedImageCallback {
  32. public:
  33. virtual ~EncodedImageCallback() {}
  34. struct Result {
  35. enum Error {
  36. OK,
  37. // Failed to send the packet.
  38. ERROR_SEND_FAILED,
  39. };
  40. explicit Result(Error error) : error(error) {}
  41. Result(Error error, uint32_t frame_id) : error(error), frame_id(frame_id) {}
  42. Error error;
  43. // Frame ID assigned to the frame. The frame ID should be the same as the ID
  44. // seen by the receiver for this frame. RTP timestamp of the frame is used
  45. // as frame ID when RTP is used to send video. Must be used only when
  46. // error=OK.
  47. uint32_t frame_id = 0;
  48. // Tells the encoder that the next frame is should be dropped.
  49. bool drop_next_frame = false;
  50. };
  51. // Used to signal the encoder about reason a frame is dropped.
  52. // kDroppedByMediaOptimizations - dropped by MediaOptimizations (for rate
  53. // limiting purposes).
  54. // kDroppedByEncoder - dropped by encoder's internal rate limiter.
  55. enum class DropReason : uint8_t {
  56. kDroppedByMediaOptimizations,
  57. kDroppedByEncoder
  58. };
  59. // Callback function which is called when an image has been encoded.
  60. virtual Result OnEncodedImage(
  61. const EncodedImage& encoded_image,
  62. const CodecSpecificInfo* codec_specific_info,
  63. const RTPFragmentationHeader* fragmentation) = 0;
  64. virtual void OnDroppedFrame(DropReason reason) {}
  65. };
  66. class RTC_EXPORT VideoEncoder {
  67. public:
  68. struct QpThresholds {
  69. QpThresholds(int l, int h) : low(l), high(h) {}
  70. QpThresholds() : low(-1), high(-1) {}
  71. int low;
  72. int high;
  73. };
  74. // Quality scaling is enabled if thresholds are provided.
  75. struct ScalingSettings {
  76. private:
  77. // Private magic type for kOff, implicitly convertible to
  78. // ScalingSettings.
  79. struct KOff {};
  80. public:
  81. // TODO(nisse): Would be nicer if kOff were a constant ScalingSettings
  82. // rather than a magic value. However, absl::optional is not trivially copy
  83. // constructible, and hence a constant ScalingSettings needs a static
  84. // initializer, which is strongly discouraged in Chrome. We can hopefully
  85. // fix this when we switch to absl::optional or std::optional.
  86. static constexpr KOff kOff = {};
  87. ScalingSettings(int low, int high);
  88. ScalingSettings(int low, int high, int min_pixels);
  89. ScalingSettings(const ScalingSettings&);
  90. ScalingSettings(KOff); // NOLINT(runtime/explicit)
  91. ~ScalingSettings();
  92. absl::optional<QpThresholds> thresholds;
  93. // We will never ask for a resolution lower than this.
  94. // TODO(kthelgason): Lower this limit when better testing
  95. // on MediaCodec and fallback implementations are in place.
  96. // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7206
  97. int min_pixels_per_frame = 320 * 180;
  98. private:
  99. // Private constructor; to get an object without thresholds, use
  100. // the magic constant ScalingSettings::kOff.
  101. ScalingSettings();
  102. };
  103. // Bitrate limits for resolution.
  104. struct ResolutionBitrateLimits {
  105. ResolutionBitrateLimits(int frame_size_pixels,
  106. int min_start_bitrate_bps,
  107. int min_bitrate_bps,
  108. int max_bitrate_bps)
  109. : frame_size_pixels(frame_size_pixels),
  110. min_start_bitrate_bps(min_start_bitrate_bps),
  111. min_bitrate_bps(min_bitrate_bps),
  112. max_bitrate_bps(max_bitrate_bps) {}
  113. // Size of video frame, in pixels, the bitrate thresholds are intended for.
  114. int frame_size_pixels = 0;
  115. // Recommended minimum bitrate to start encoding.
  116. int min_start_bitrate_bps = 0;
  117. // Recommended minimum bitrate.
  118. int min_bitrate_bps = 0;
  119. // Recommended maximum bitrate.
  120. int max_bitrate_bps = 0;
  121. };
  122. // Struct containing metadata about the encoder implementing this interface.
  123. struct EncoderInfo {
  124. static constexpr uint8_t kMaxFramerateFraction =
  125. std::numeric_limits<uint8_t>::max();
  126. EncoderInfo();
  127. EncoderInfo(const EncoderInfo&);
  128. ~EncoderInfo();
  129. // Any encoder implementation wishing to use the WebRTC provided
  130. // quality scaler must populate this field.
  131. ScalingSettings scaling_settings;
  132. // If true, encoder supports working with a native handle (e.g. texture
  133. // handle for hw codecs) rather than requiring a raw I420 buffer.
  134. bool supports_native_handle;
  135. // The name of this particular encoder implementation, e.g. "libvpx".
  136. std::string implementation_name;
  137. // If this field is true, the encoder rate controller must perform
  138. // well even in difficult situations, and produce close to the specified
  139. // target bitrate seen over a reasonable time window, drop frames if
  140. // necessary in order to keep the rate correct, and react quickly to
  141. // changing bitrate targets. If this method returns true, we disable the
  142. // frame dropper in the media optimization module and rely entirely on the
  143. // encoder to produce media at a bitrate that closely matches the target.
  144. // Any overshooting may result in delay buildup. If this method returns
  145. // false (default behavior), the media opt frame dropper will drop input
  146. // frames if it suspect encoder misbehavior. Misbehavior is common,
  147. // especially in hardware codecs. Disable media opt at your own risk.
  148. bool has_trusted_rate_controller;
  149. // If this field is true, the encoder uses hardware support and different
  150. // thresholds will be used in CPU adaptation.
  151. bool is_hardware_accelerated;
  152. // If this field is true, the encoder uses internal camera sources, meaning
  153. // that it does not require/expect frames to be delivered via
  154. // webrtc::VideoEncoder::Encode.
  155. // Internal source encoders are deprecated and support for them will be
  156. // phased out.
  157. bool has_internal_source;
  158. // For each spatial layer (simulcast stream or SVC layer), represented as an
  159. // element in |fps_allocation| a vector indicates how many temporal layers
  160. // the encoder is using for that spatial layer.
  161. // For each spatial/temporal layer pair, the frame rate fraction is given as
  162. // an 8bit unsigned integer where 0 = 0% and 255 = 100%.
  163. //
  164. // If the vector is empty for a given spatial layer, it indicates that frame
  165. // rates are not defined and we can't count on any specific frame rate to be
  166. // generated. Likely this indicates Vp8TemporalLayersType::kBitrateDynamic.
  167. //
  168. // The encoder may update this on a per-frame basis in response to both
  169. // internal and external signals.
  170. //
  171. // Spatial layers are treated independently, but temporal layers are
  172. // cumulative. For instance, if:
  173. // fps_allocation[0][0] = kFullFramerate / 2;
  174. // fps_allocation[0][1] = kFullFramerate;
  175. // Then half of the frames are in the base layer and half is in TL1, but
  176. // since TL1 is assumed to depend on the base layer, the frame rate is
  177. // indicated as the full 100% for the top layer.
  178. //
  179. // Defaults to a single spatial layer containing a single temporal layer
  180. // with a 100% frame rate fraction.
  181. absl::InlinedVector<uint8_t, kMaxTemporalStreams>
  182. fps_allocation[kMaxSpatialLayers];
  183. // Recommended bitrate limits for different resolutions.
  184. std::vector<ResolutionBitrateLimits> resolution_bitrate_limits;
  185. // If true, this encoder has internal support for generating simulcast
  186. // streams. Otherwise, an adapter class will be needed.
  187. // Even if true, the config provided to InitEncode() might not be supported,
  188. // in such case the encoder should return
  189. // WEBRTC_VIDEO_CODEC_ERR_SIMULCAST_PARAMETERS_NOT_SUPPORTED.
  190. bool supports_simulcast;
  191. };
  192. struct RateControlParameters {
  193. RateControlParameters();
  194. RateControlParameters(const VideoBitrateAllocation& bitrate,
  195. double framerate_fps);
  196. RateControlParameters(const VideoBitrateAllocation& bitrate,
  197. double framerate_fps,
  198. DataRate bandwidth_allocation);
  199. virtual ~RateControlParameters();
  200. // Target bitrate, per spatial/temporal layer.
  201. // A target bitrate of 0bps indicates a layer should not be encoded at all.
  202. VideoBitrateAllocation bitrate;
  203. // Target framerate, in fps. A value <= 0.0 is invalid and should be
  204. // interpreted as framerate target not available. In this case the encoder
  205. // should fall back to the max framerate specified in |codec_settings| of
  206. // the last InitEncode() call.
  207. double framerate_fps;
  208. // The network bandwidth available for video. This is at least
  209. // |bitrate.get_sum_bps()|, but may be higher if the application is not
  210. // network constrained.
  211. DataRate bandwidth_allocation;
  212. bool operator==(const RateControlParameters& rhs) const;
  213. bool operator!=(const RateControlParameters& rhs) const;
  214. };
  215. struct LossNotification {
  216. // The timestamp of the last decodable frame *prior* to the last received.
  217. // (The last received - described below - might itself be decodable or not.)
  218. uint32_t timestamp_of_last_decodable;
  219. // The timestamp of the last received frame.
  220. uint32_t timestamp_of_last_received;
  221. // Describes whether the dependencies of the last received frame were
  222. // all decodable.
  223. // |false| if some dependencies were undecodable, |true| if all dependencies
  224. // were decodable, and |nullopt| if the dependencies are unknown.
  225. absl::optional<bool> dependencies_of_last_received_decodable;
  226. // Describes whether the received frame was decodable.
  227. // |false| if some dependency was undecodable or if some packet belonging
  228. // to the last received frame was missed.
  229. // |true| if all dependencies were decodable and all packets belonging
  230. // to the last received frame were received.
  231. // |nullopt| if no packet belonging to the last frame was missed, but the
  232. // last packet in the frame was not yet received.
  233. absl::optional<bool> last_received_decodable;
  234. };
  235. // Negotiated capabilities which the VideoEncoder may expect the other
  236. // side to use.
  237. struct Capabilities {
  238. explicit Capabilities(bool loss_notification)
  239. : loss_notification(loss_notification) {}
  240. bool loss_notification;
  241. };
  242. struct Settings {
  243. Settings(const Capabilities& capabilities,
  244. int number_of_cores,
  245. size_t max_payload_size)
  246. : capabilities(capabilities),
  247. number_of_cores(number_of_cores),
  248. max_payload_size(max_payload_size) {}
  249. Capabilities capabilities;
  250. int number_of_cores;
  251. size_t max_payload_size;
  252. };
  253. static VideoCodecVP8 GetDefaultVp8Settings();
  254. static VideoCodecVP9 GetDefaultVp9Settings();
  255. static VideoCodecH264 GetDefaultH264Settings();
  256. virtual ~VideoEncoder() {}
  257. // Set a FecControllerOverride, through which the encoder may override
  258. // decisions made by FecController.
  259. // TODO(bugs.webrtc.org/10769): Update downstream, then make pure-virtual.
  260. virtual void SetFecControllerOverride(
  261. FecControllerOverride* fec_controller_override);
  262. // Initialize the encoder with the information from the codecSettings
  263. //
  264. // Input:
  265. // - codec_settings : Codec settings
  266. // - settings : Settings affecting the encoding itself.
  267. // Input for deprecated version:
  268. // - number_of_cores : Number of cores available for the encoder
  269. // - max_payload_size : The maximum size each payload is allowed
  270. // to have. Usually MTU - overhead.
  271. //
  272. // Return value : Set bit rate if OK
  273. // <0 - Errors:
  274. // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
  275. // WEBRTC_VIDEO_CODEC_ERR_SIZE
  276. // WEBRTC_VIDEO_CODEC_MEMORY
  277. // WEBRTC_VIDEO_CODEC_ERROR
  278. // TODO(bugs.webrtc.org/10720): After updating downstream projects and posting
  279. // an announcement to discuss-webrtc, remove the three-parameters variant
  280. // and make the two-parameters variant pure-virtual.
  281. /* RTC_DEPRECATED */ virtual int32_t InitEncode(
  282. const VideoCodec* codec_settings,
  283. int32_t number_of_cores,
  284. size_t max_payload_size);
  285. virtual int InitEncode(const VideoCodec* codec_settings,
  286. const VideoEncoder::Settings& settings);
  287. // Register an encode complete callback object.
  288. //
  289. // Input:
  290. // - callback : Callback object which handles encoded images.
  291. //
  292. // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
  293. virtual int32_t RegisterEncodeCompleteCallback(
  294. EncodedImageCallback* callback) = 0;
  295. // Free encoder memory.
  296. // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
  297. virtual int32_t Release() = 0;
  298. // Encode an I420 image (as a part of a video stream). The encoded image
  299. // will be returned to the user through the encode complete callback.
  300. //
  301. // Input:
  302. // - frame : Image to be encoded
  303. // - frame_types : Frame type to be generated by the encoder.
  304. //
  305. // Return value : WEBRTC_VIDEO_CODEC_OK if OK
  306. // <0 - Errors:
  307. // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
  308. // WEBRTC_VIDEO_CODEC_MEMORY
  309. // WEBRTC_VIDEO_CODEC_ERROR
  310. virtual int32_t Encode(const VideoFrame& frame,
  311. const std::vector<VideoFrameType>* frame_types) = 0;
  312. // Sets rate control parameters: bitrate, framerate, etc. These settings are
  313. // instantaneous (i.e. not moving averages) and should apply from now until
  314. // the next call to SetRates().
  315. virtual void SetRates(const RateControlParameters& parameters) = 0;
  316. // Inform the encoder when the packet loss rate changes.
  317. //
  318. // Input: - packet_loss_rate : The packet loss rate (0.0 to 1.0).
  319. virtual void OnPacketLossRateUpdate(float packet_loss_rate);
  320. // Inform the encoder when the round trip time changes.
  321. //
  322. // Input: - rtt_ms : The new RTT, in milliseconds.
  323. virtual void OnRttUpdate(int64_t rtt_ms);
  324. // Called when a loss notification is received.
  325. virtual void OnLossNotification(const LossNotification& loss_notification);
  326. // Returns meta-data about the encoder, such as implementation name.
  327. // The output of this method may change during runtime. For instance if a
  328. // hardware encoder fails, it may fall back to doing software encoding using
  329. // an implementation with different characteristics.
  330. virtual EncoderInfo GetEncoderInfo() const;
  331. };
  332. } // namespace webrtc
  333. #endif // API_VIDEO_CODECS_VIDEO_ENCODER_H_