blob: 766ea75712fa8d9e43fe3c8bc8f52859eb4f8abe [file] [log] [blame]
ilnikd60d06a2017-04-05 03:02:20 -07001/*
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
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#ifndef API_VIDEO_CODECS_VIDEO_ENCODER_H_
12#define API_VIDEO_CODECS_VIDEO_ENCODER_H_
ilnikd60d06a2017-04-05 03:02:20 -070013
Erik Språngdbdd8392019-01-17 15:27:50 +010014#include <limits>
ilnikd60d06a2017-04-05 03:02:20 -070015#include <memory>
16#include <string>
17#include <vector>
18
Erik Språngdbdd8392019-01-17 15:27:50 +010019#include "absl/container/inlined_vector.h"
Danil Chapovalov0bc58cf2018-06-21 13:32:56 +020020#include "absl/types/optional.h"
Elad Alon8f01c4e2019-06-28 15:19:43 +020021#include "api/fec_controller_override.h"
Erik Språng4d9df382019-03-27 15:00:43 +010022#include "api/units/data_rate.h"
Niels Möller4dc66c52018-10-05 14:17:58 +020023#include "api/video/encoded_image.h"
Erik Språngec475652018-05-15 15:12:55 +020024#include "api/video/video_bitrate_allocation.h"
Erik Språngf93eda12019-01-16 17:10:57 +010025#include "api/video/video_codec_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "api/video/video_frame.h"
Niels Möller802506c2018-05-31 10:44:51 +020027#include "api/video_codecs/video_codec.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
Mirko Bonadei276827c2018-10-16 14:13:50 +020029#include "rtc_base/system/rtc_export.h"
ilnikd60d06a2017-04-05 03:02:20 -070030
31namespace webrtc {
32
33class RTPFragmentationHeader;
34// TODO(pbos): Expose these through a public (root) header or change these APIs.
35struct CodecSpecificInfo;
ilnikd60d06a2017-04-05 03:02:20 -070036
37class EncodedImageCallback {
38 public:
39 virtual ~EncodedImageCallback() {}
40
41 struct Result {
42 enum Error {
43 OK,
44
45 // Failed to send the packet.
46 ERROR_SEND_FAILED,
47 };
48
mflodman351424e2017-08-10 02:43:14 -070049 explicit Result(Error error) : error(error) {}
ilnikd60d06a2017-04-05 03:02:20 -070050 Result(Error error, uint32_t frame_id) : error(error), frame_id(frame_id) {}
51
52 Error error;
53
54 // Frame ID assigned to the frame. The frame ID should be the same as the ID
55 // seen by the receiver for this frame. RTP timestamp of the frame is used
56 // as frame ID when RTP is used to send video. Must be used only when
57 // error=OK.
58 uint32_t frame_id = 0;
59
60 // Tells the encoder that the next frame is should be dropped.
61 bool drop_next_frame = false;
62 };
63
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +020064 // Used to signal the encoder about reason a frame is dropped.
65 // kDroppedByMediaOptimizations - dropped by MediaOptimizations (for rate
66 // limiting purposes).
67 // kDroppedByEncoder - dropped by encoder's internal rate limiter.
68 enum class DropReason : uint8_t {
69 kDroppedByMediaOptimizations,
70 kDroppedByEncoder
71 };
72
ilnikd60d06a2017-04-05 03:02:20 -070073 // Callback function which is called when an image has been encoded.
74 virtual Result OnEncodedImage(
75 const EncodedImage& encoded_image,
76 const CodecSpecificInfo* codec_specific_info,
77 const RTPFragmentationHeader* fragmentation) = 0;
78
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +020079 virtual void OnDroppedFrame(DropReason reason) {}
ilnikd60d06a2017-04-05 03:02:20 -070080};
81
Mirko Bonadei276827c2018-10-16 14:13:50 +020082class RTC_EXPORT VideoEncoder {
ilnikd60d06a2017-04-05 03:02:20 -070083 public:
ilnikd60d06a2017-04-05 03:02:20 -070084 struct QpThresholds {
85 QpThresholds(int l, int h) : low(l), high(h) {}
86 QpThresholds() : low(-1), high(-1) {}
87 int low;
88 int high;
89 };
Elad Alon370f93a2019-06-11 14:57:57 +020090
Niels Möller225c7872018-02-22 15:03:53 +010091 // Quality scaling is enabled if thresholds are provided.
ilnikd60d06a2017-04-05 03:02:20 -070092 struct ScalingSettings {
Niels Möller225c7872018-02-22 15:03:53 +010093 private:
94 // Private magic type for kOff, implicitly convertible to
95 // ScalingSettings.
96 struct KOff {};
97
98 public:
99 // TODO(nisse): Would be nicer if kOff were a constant ScalingSettings
Danil Chapovalov0bc58cf2018-06-21 13:32:56 +0200100 // rather than a magic value. However, absl::optional is not trivially copy
Niels Möller225c7872018-02-22 15:03:53 +0100101 // constructible, and hence a constant ScalingSettings needs a static
102 // initializer, which is strongly discouraged in Chrome. We can hopefully
103 // fix this when we switch to absl::optional or std::optional.
104 static constexpr KOff kOff = {};
105
106 ScalingSettings(int low, int high);
107 ScalingSettings(int low, int high, int min_pixels);
mflodman351424e2017-08-10 02:43:14 -0700108 ScalingSettings(const ScalingSettings&);
Niels Möller225c7872018-02-22 15:03:53 +0100109 ScalingSettings(KOff); // NOLINT(runtime/explicit)
mflodman351424e2017-08-10 02:43:14 -0700110 ~ScalingSettings();
111
Erik Språnge2fd86a2018-10-24 11:32:39 +0200112 absl::optional<QpThresholds> thresholds;
asapersson142fcc92017-08-17 08:58:54 -0700113
114 // We will never ask for a resolution lower than this.
115 // TODO(kthelgason): Lower this limit when better testing
116 // on MediaCodec and fallback implementations are in place.
117 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7206
Erik Språnge2fd86a2018-10-24 11:32:39 +0200118 int min_pixels_per_frame = 320 * 180;
Niels Möller225c7872018-02-22 15:03:53 +0100119
120 private:
121 // Private constructor; to get an object without thresholds, use
122 // the magic constant ScalingSettings::kOff.
123 ScalingSettings();
ilnikd60d06a2017-04-05 03:02:20 -0700124 };
ilnikd60d06a2017-04-05 03:02:20 -0700125
Sergey Silkin3d642f82019-07-03 15:09:33 +0200126 // Bitrate limits for resolution.
127 struct ResolutionBitrateLimits {
128 ResolutionBitrateLimits(int frame_size_pixels,
129 int min_start_bitrate_bps,
130 int min_bitrate_bps,
131 int max_bitrate_bps)
Sergey Silkinbe0adee2019-06-26 14:11:03 +0200132 : frame_size_pixels(frame_size_pixels),
133 min_start_bitrate_bps(min_start_bitrate_bps),
134 min_bitrate_bps(min_bitrate_bps),
135 max_bitrate_bps(max_bitrate_bps) {}
136 // Size of video frame, in pixels, the bitrate thresholds are intended for.
137 int frame_size_pixels = 0;
138 // Recommended minimum bitrate to start encoding.
139 int min_start_bitrate_bps = 0;
140 // Recommended minimum bitrate.
141 int min_bitrate_bps = 0;
142 // Recommended maximum bitrate.
143 int max_bitrate_bps = 0;
144 };
145
Erik Språnge2fd86a2018-10-24 11:32:39 +0200146 // Struct containing metadata about the encoder implementing this interface.
147 struct EncoderInfo {
Erik Språngdbdd8392019-01-17 15:27:50 +0100148 static constexpr uint8_t kMaxFramerateFraction =
149 std::numeric_limits<uint8_t>::max();
150
Erik Språnge2fd86a2018-10-24 11:32:39 +0200151 EncoderInfo();
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100152 EncoderInfo(const EncoderInfo&);
153
Erik Språnge2fd86a2018-10-24 11:32:39 +0200154 ~EncoderInfo();
155
156 // Any encoder implementation wishing to use the WebRTC provided
157 // quality scaler must populate this field.
158 ScalingSettings scaling_settings;
159
160 // If true, encoder supports working with a native handle (e.g. texture
161 // handle for hw codecs) rather than requiring a raw I420 buffer.
162 bool supports_native_handle;
163
164 // The name of this particular encoder implementation, e.g. "libvpx".
165 std::string implementation_name;
Erik Språngd3438aa2018-11-08 16:56:43 +0100166
167 // If this field is true, the encoder rate controller must perform
168 // well even in difficult situations, and produce close to the specified
169 // target bitrate seen over a reasonable time window, drop frames if
170 // necessary in order to keep the rate correct, and react quickly to
171 // changing bitrate targets. If this method returns true, we disable the
172 // frame dropper in the media optimization module and rely entirely on the
173 // encoder to produce media at a bitrate that closely matches the target.
174 // Any overshooting may result in delay buildup. If this method returns
175 // false (default behavior), the media opt frame dropper will drop input
176 // frames if it suspect encoder misbehavior. Misbehavior is common,
177 // especially in hardware codecs. Disable media opt at your own risk.
178 bool has_trusted_rate_controller;
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100179
180 // If this field is true, the encoder uses hardware support and different
181 // thresholds will be used in CPU adaptation.
182 bool is_hardware_accelerated;
183
184 // If this field is true, the encoder uses internal camera sources, meaning
185 // that it does not require/expect frames to be delivered via
186 // webrtc::VideoEncoder::Encode.
187 // Internal source encoders are deprecated and support for them will be
188 // phased out.
189 bool has_internal_source;
Erik Språngdbdd8392019-01-17 15:27:50 +0100190
191 // For each spatial layer (simulcast stream or SVC layer), represented as an
192 // element in |fps_allocation| a vector indicates how many temporal layers
193 // the encoder is using for that spatial layer.
194 // For each spatial/temporal layer pair, the frame rate fraction is given as
195 // an 8bit unsigned integer where 0 = 0% and 255 = 100%.
196 //
197 // If the vector is empty for a given spatial layer, it indicates that frame
198 // rates are not defined and we can't count on any specific frame rate to be
199 // generated. Likely this indicates Vp8TemporalLayersType::kBitrateDynamic.
200 //
201 // The encoder may update this on a per-frame basis in response to both
202 // internal and external signals.
203 //
204 // Spatial layers are treated independently, but temporal layers are
205 // cumulative. For instance, if:
206 // fps_allocation[0][0] = kFullFramerate / 2;
207 // fps_allocation[0][1] = kFullFramerate;
208 // Then half of the frames are in the base layer and half is in TL1, but
209 // since TL1 is assumed to depend on the base layer, the frame rate is
210 // indicated as the full 100% for the top layer.
211 //
212 // Defaults to a single spatial layer containing a single temporal layer
213 // with a 100% frame rate fraction.
214 absl::InlinedVector<uint8_t, kMaxTemporalStreams>
215 fps_allocation[kMaxSpatialLayers];
Sergey Silkinbe0adee2019-06-26 14:11:03 +0200216
Sergey Silkin3d642f82019-07-03 15:09:33 +0200217 // Recommended bitrate limits for different resolutions.
218 std::vector<ResolutionBitrateLimits> resolution_bitrate_limits;
Erik Språnge2fd86a2018-10-24 11:32:39 +0200219 };
220
Erik Språng4d9df382019-03-27 15:00:43 +0100221 struct RateControlParameters {
Erik Språng4c6ca302019-04-08 15:14:01 +0200222 RateControlParameters();
223 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng16cb8f52019-04-12 13:59:09 +0200224 double framerate_fps);
225 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +0200226 double framerate_fps,
227 DataRate bandwidth_allocation);
228 virtual ~RateControlParameters();
229
Erik Språng4d9df382019-03-27 15:00:43 +0100230 // Target bitrate, per spatial/temporal layer.
231 // A target bitrate of 0bps indicates a layer should not be encoded at all.
232 VideoBitrateAllocation bitrate;
233 // Target framerate, in fps. A value <= 0.0 is invalid and should be
234 // interpreted as framerate target not available. In this case the encoder
235 // should fall back to the max framerate specified in |codec_settings| of
236 // the last InitEncode() call.
237 double framerate_fps;
238 // The network bandwidth available for video. This is at least
239 // |bitrate.get_sum_bps()|, but may be higher if the application is not
240 // network constrained.
241 DataRate bandwidth_allocation;
Evan Shrubsole7c079f62019-09-26 09:55:03 +0200242
243 bool operator==(const RateControlParameters& rhs) const;
244 bool operator!=(const RateControlParameters& rhs) const;
Erik Språng4d9df382019-03-27 15:00:43 +0100245 };
246
Elad Alon6c371ca2019-04-04 12:28:51 +0200247 struct LossNotification {
248 // The timestamp of the last decodable frame *prior* to the last received.
249 // (The last received - described below - might itself be decodable or not.)
250 uint32_t timestamp_of_last_decodable;
251 // The timestamp of the last received frame.
252 uint32_t timestamp_of_last_received;
253 // Describes whether the dependencies of the last received frame were
254 // all decodable.
255 // |false| if some dependencies were undecodable, |true| if all dependencies
256 // were decodable, and |nullopt| if the dependencies are unknown.
Elad Alon20789e42019-04-09 11:56:14 +0200257 absl::optional<bool> dependencies_of_last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200258 // Describes whether the received frame was decodable.
259 // |false| if some dependency was undecodable or if some packet belonging
260 // to the last received frame was missed.
261 // |true| if all dependencies were decodable and all packets belonging
262 // to the last received frame were received.
263 // |nullopt| if no packet belonging to the last frame was missed, but the
264 // last packet in the frame was not yet received.
Elad Alon20789e42019-04-09 11:56:14 +0200265 absl::optional<bool> last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200266 };
267
Elad Alon370f93a2019-06-11 14:57:57 +0200268 // Negotiated capabilities which the VideoEncoder may expect the other
269 // side to use.
270 struct Capabilities {
271 explicit Capabilities(bool loss_notification)
272 : loss_notification(loss_notification) {}
273 bool loss_notification;
274 };
275
276 struct Settings {
277 Settings(const Capabilities& capabilities,
278 int number_of_cores,
279 size_t max_payload_size)
280 : capabilities(capabilities),
281 number_of_cores(number_of_cores),
282 max_payload_size(max_payload_size) {}
283
284 Capabilities capabilities;
285 int number_of_cores;
286 size_t max_payload_size;
287 };
288
ilnikd60d06a2017-04-05 03:02:20 -0700289 static VideoCodecVP8 GetDefaultVp8Settings();
290 static VideoCodecVP9 GetDefaultVp9Settings();
291 static VideoCodecH264 GetDefaultH264Settings();
292
293 virtual ~VideoEncoder() {}
294
Elad Alon8f01c4e2019-06-28 15:19:43 +0200295 // Set a FecControllerOverride, through which the encoder may override
296 // decisions made by FecController.
297 // TODO(bugs.webrtc.org/10769): Update downstream, then make pure-virtual.
298 virtual void SetFecControllerOverride(
299 FecControllerOverride* fec_controller_override);
300
ilnikd60d06a2017-04-05 03:02:20 -0700301 // Initialize the encoder with the information from the codecSettings
302 //
303 // Input:
304 // - codec_settings : Codec settings
Elad Alon370f93a2019-06-11 14:57:57 +0200305 // - settings : Settings affecting the encoding itself.
306 // Input for deprecated version:
ilnikd60d06a2017-04-05 03:02:20 -0700307 // - number_of_cores : Number of cores available for the encoder
308 // - max_payload_size : The maximum size each payload is allowed
309 // to have. Usually MTU - overhead.
310 //
311 // Return value : Set bit rate if OK
312 // <0 - Errors:
313 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
314 // WEBRTC_VIDEO_CODEC_ERR_SIZE
ilnikd60d06a2017-04-05 03:02:20 -0700315 // WEBRTC_VIDEO_CODEC_MEMORY
316 // WEBRTC_VIDEO_CODEC_ERROR
Elad Alon370f93a2019-06-11 14:57:57 +0200317 // TODO(bugs.webrtc.org/10720): After updating downstream projects and posting
318 // an announcement to discuss-webrtc, remove the three-parameters variant
319 // and make the two-parameters variant pure-virtual.
320 /* RTC_DEPRECATED */ virtual int32_t InitEncode(
321 const VideoCodec* codec_settings,
322 int32_t number_of_cores,
323 size_t max_payload_size);
324 virtual int InitEncode(const VideoCodec* codec_settings,
325 const VideoEncoder::Settings& settings);
ilnikd60d06a2017-04-05 03:02:20 -0700326
327 // Register an encode complete callback object.
328 //
329 // Input:
330 // - callback : Callback object which handles encoded images.
331 //
332 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
333 virtual int32_t RegisterEncodeCompleteCallback(
334 EncodedImageCallback* callback) = 0;
335
336 // Free encoder memory.
337 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
338 virtual int32_t Release() = 0;
339
340 // Encode an I420 image (as a part of a video stream). The encoded image
341 // will be returned to the user through the encode complete callback.
342 //
343 // Input:
344 // - frame : Image to be encoded
345 // - frame_types : Frame type to be generated by the encoder.
346 //
347 // Return value : WEBRTC_VIDEO_CODEC_OK if OK
348 // <0 - Errors:
349 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
350 // WEBRTC_VIDEO_CODEC_MEMORY
351 // WEBRTC_VIDEO_CODEC_ERROR
ilnikd60d06a2017-04-05 03:02:20 -0700352 virtual int32_t Encode(const VideoFrame& frame,
Niels Möller9d766b92019-03-28 09:19:35 +0100353 const std::vector<VideoFrameType>* frame_types) = 0;
ilnikd60d06a2017-04-05 03:02:20 -0700354
Erik Språng4d9df382019-03-27 15:00:43 +0100355 // Sets rate control parameters: bitrate, framerate, etc. These settings are
356 // instantaneous (i.e. not moving averages) and should apply from now until
357 // the next call to SetRates().
Erik Språng157b7812019-05-13 11:37:12 +0200358 virtual void SetRates(const RateControlParameters& parameters) = 0;
Erik Språng4d9df382019-03-27 15:00:43 +0100359
Elad Aloncde8ab22019-03-20 11:56:20 +0100360 // Inform the encoder when the packet loss rate changes.
361 //
362 // Input: - packet_loss_rate : The packet loss rate (0.0 to 1.0).
363 virtual void OnPacketLossRateUpdate(float packet_loss_rate);
364
365 // Inform the encoder when the round trip time changes.
366 //
367 // Input: - rtt_ms : The new RTT, in milliseconds.
368 virtual void OnRttUpdate(int64_t rtt_ms);
369
Elad Alon6c371ca2019-04-04 12:28:51 +0200370 // Called when a loss notification is received.
371 virtual void OnLossNotification(const LossNotification& loss_notification);
372
Erik Språngd3438aa2018-11-08 16:56:43 +0100373 // Returns meta-data about the encoder, such as implementation name.
374 // The output of this method may change during runtime. For instance if a
375 // hardware encoder fails, it may fall back to doing software encoding using
376 // an implementation with different characteristics.
Erik Språnge2fd86a2018-10-24 11:32:39 +0200377 virtual EncoderInfo GetEncoderInfo() const;
ilnikd60d06a2017-04-05 03:02:20 -0700378};
ilnikd60d06a2017-04-05 03:02:20 -0700379} // namespace webrtc
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200380#endif // API_VIDEO_CODECS_VIDEO_ENCODER_H_