blob: d2e4877b8414c79b9f8d4f9aeecea1db00c16176 [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"
Erik Språng4d9df382019-03-27 15:00:43 +010021#include "api/units/data_rate.h"
Niels Möller4dc66c52018-10-05 14:17:58 +020022#include "api/video/encoded_image.h"
Erik Språngec475652018-05-15 15:12:55 +020023#include "api/video/video_bitrate_allocation.h"
Erik Språngf93eda12019-01-16 17:10:57 +010024#include "api/video/video_codec_constants.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "api/video/video_frame.h"
Niels Möller802506c2018-05-31 10:44:51 +020026#include "api/video_codecs/video_codec.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/checks.h"
Mirko Bonadei276827c2018-10-16 14:13:50 +020028#include "rtc_base/system/rtc_export.h"
ilnikd60d06a2017-04-05 03:02:20 -070029
30namespace webrtc {
31
32class RTPFragmentationHeader;
33// TODO(pbos): Expose these through a public (root) header or change these APIs.
34struct CodecSpecificInfo;
ilnikd60d06a2017-04-05 03:02:20 -070035
36class EncodedImageCallback {
37 public:
38 virtual ~EncodedImageCallback() {}
39
40 struct Result {
41 enum Error {
42 OK,
43
44 // Failed to send the packet.
45 ERROR_SEND_FAILED,
46 };
47
mflodman351424e2017-08-10 02:43:14 -070048 explicit Result(Error error) : error(error) {}
ilnikd60d06a2017-04-05 03:02:20 -070049 Result(Error error, uint32_t frame_id) : error(error), frame_id(frame_id) {}
50
51 Error error;
52
53 // Frame ID assigned to the frame. The frame ID should be the same as the ID
54 // seen by the receiver for this frame. RTP timestamp of the frame is used
55 // as frame ID when RTP is used to send video. Must be used only when
56 // error=OK.
57 uint32_t frame_id = 0;
58
59 // Tells the encoder that the next frame is should be dropped.
60 bool drop_next_frame = false;
61 };
62
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +020063 // Used to signal the encoder about reason a frame is dropped.
64 // kDroppedByMediaOptimizations - dropped by MediaOptimizations (for rate
65 // limiting purposes).
66 // kDroppedByEncoder - dropped by encoder's internal rate limiter.
67 enum class DropReason : uint8_t {
68 kDroppedByMediaOptimizations,
69 kDroppedByEncoder
70 };
71
ilnikd60d06a2017-04-05 03:02:20 -070072 // Callback function which is called when an image has been encoded.
73 virtual Result OnEncodedImage(
74 const EncodedImage& encoded_image,
75 const CodecSpecificInfo* codec_specific_info,
76 const RTPFragmentationHeader* fragmentation) = 0;
77
Ilya Nikolaevskiyd79314f2017-10-23 10:45:37 +020078 virtual void OnDroppedFrame(DropReason reason) {}
ilnikd60d06a2017-04-05 03:02:20 -070079};
80
Mirko Bonadei276827c2018-10-16 14:13:50 +020081class RTC_EXPORT VideoEncoder {
ilnikd60d06a2017-04-05 03:02:20 -070082 public:
ilnikd60d06a2017-04-05 03:02:20 -070083 struct QpThresholds {
84 QpThresholds(int l, int h) : low(l), high(h) {}
85 QpThresholds() : low(-1), high(-1) {}
86 int low;
87 int high;
88 };
Elad Alon370f93a2019-06-11 14:57:57 +020089
Niels Möller225c7872018-02-22 15:03:53 +010090 // Quality scaling is enabled if thresholds are provided.
ilnikd60d06a2017-04-05 03:02:20 -070091 struct ScalingSettings {
Niels Möller225c7872018-02-22 15:03:53 +010092 private:
93 // Private magic type for kOff, implicitly convertible to
94 // ScalingSettings.
95 struct KOff {};
96
97 public:
98 // TODO(nisse): Would be nicer if kOff were a constant ScalingSettings
Danil Chapovalov0bc58cf2018-06-21 13:32:56 +020099 // rather than a magic value. However, absl::optional is not trivially copy
Niels Möller225c7872018-02-22 15:03:53 +0100100 // constructible, and hence a constant ScalingSettings needs a static
101 // initializer, which is strongly discouraged in Chrome. We can hopefully
102 // fix this when we switch to absl::optional or std::optional.
103 static constexpr KOff kOff = {};
104
105 ScalingSettings(int low, int high);
106 ScalingSettings(int low, int high, int min_pixels);
mflodman351424e2017-08-10 02:43:14 -0700107 ScalingSettings(const ScalingSettings&);
Niels Möller225c7872018-02-22 15:03:53 +0100108 ScalingSettings(KOff); // NOLINT(runtime/explicit)
mflodman351424e2017-08-10 02:43:14 -0700109 ~ScalingSettings();
110
Erik Språnge2fd86a2018-10-24 11:32:39 +0200111 absl::optional<QpThresholds> thresholds;
asapersson142fcc92017-08-17 08:58:54 -0700112
113 // We will never ask for a resolution lower than this.
114 // TODO(kthelgason): Lower this limit when better testing
115 // on MediaCodec and fallback implementations are in place.
116 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7206
Erik Språnge2fd86a2018-10-24 11:32:39 +0200117 int min_pixels_per_frame = 320 * 180;
Niels Möller225c7872018-02-22 15:03:53 +0100118
119 private:
120 // Private constructor; to get an object without thresholds, use
121 // the magic constant ScalingSettings::kOff.
122 ScalingSettings();
ilnikd60d06a2017-04-05 03:02:20 -0700123 };
ilnikd60d06a2017-04-05 03:02:20 -0700124
Erik Språnge2fd86a2018-10-24 11:32:39 +0200125 // Struct containing metadata about the encoder implementing this interface.
126 struct EncoderInfo {
Erik Språngdbdd8392019-01-17 15:27:50 +0100127 static constexpr uint8_t kMaxFramerateFraction =
128 std::numeric_limits<uint8_t>::max();
129
Erik Språnge2fd86a2018-10-24 11:32:39 +0200130 EncoderInfo();
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100131 EncoderInfo(const EncoderInfo&);
132
Erik Språnge2fd86a2018-10-24 11:32:39 +0200133 ~EncoderInfo();
134
135 // Any encoder implementation wishing to use the WebRTC provided
136 // quality scaler must populate this field.
137 ScalingSettings scaling_settings;
138
139 // If true, encoder supports working with a native handle (e.g. texture
140 // handle for hw codecs) rather than requiring a raw I420 buffer.
141 bool supports_native_handle;
142
143 // The name of this particular encoder implementation, e.g. "libvpx".
144 std::string implementation_name;
Erik Språngd3438aa2018-11-08 16:56:43 +0100145
146 // If this field is true, the encoder rate controller must perform
147 // well even in difficult situations, and produce close to the specified
148 // target bitrate seen over a reasonable time window, drop frames if
149 // necessary in order to keep the rate correct, and react quickly to
150 // changing bitrate targets. If this method returns true, we disable the
151 // frame dropper in the media optimization module and rely entirely on the
152 // encoder to produce media at a bitrate that closely matches the target.
153 // Any overshooting may result in delay buildup. If this method returns
154 // false (default behavior), the media opt frame dropper will drop input
155 // frames if it suspect encoder misbehavior. Misbehavior is common,
156 // especially in hardware codecs. Disable media opt at your own risk.
157 bool has_trusted_rate_controller;
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100158
159 // If this field is true, the encoder uses hardware support and different
160 // thresholds will be used in CPU adaptation.
161 bool is_hardware_accelerated;
162
163 // If this field is true, the encoder uses internal camera sources, meaning
164 // that it does not require/expect frames to be delivered via
165 // webrtc::VideoEncoder::Encode.
166 // Internal source encoders are deprecated and support for them will be
167 // phased out.
168 bool has_internal_source;
Erik Språngdbdd8392019-01-17 15:27:50 +0100169
170 // For each spatial layer (simulcast stream or SVC layer), represented as an
171 // element in |fps_allocation| a vector indicates how many temporal layers
172 // the encoder is using for that spatial layer.
173 // For each spatial/temporal layer pair, the frame rate fraction is given as
174 // an 8bit unsigned integer where 0 = 0% and 255 = 100%.
175 //
176 // If the vector is empty for a given spatial layer, it indicates that frame
177 // rates are not defined and we can't count on any specific frame rate to be
178 // generated. Likely this indicates Vp8TemporalLayersType::kBitrateDynamic.
179 //
180 // The encoder may update this on a per-frame basis in response to both
181 // internal and external signals.
182 //
183 // Spatial layers are treated independently, but temporal layers are
184 // cumulative. For instance, if:
185 // fps_allocation[0][0] = kFullFramerate / 2;
186 // fps_allocation[0][1] = kFullFramerate;
187 // Then half of the frames are in the base layer and half is in TL1, but
188 // since TL1 is assumed to depend on the base layer, the frame rate is
189 // indicated as the full 100% for the top layer.
190 //
191 // Defaults to a single spatial layer containing a single temporal layer
192 // with a 100% frame rate fraction.
193 absl::InlinedVector<uint8_t, kMaxTemporalStreams>
194 fps_allocation[kMaxSpatialLayers];
Erik Språnge2fd86a2018-10-24 11:32:39 +0200195 };
196
Erik Språng4d9df382019-03-27 15:00:43 +0100197 struct RateControlParameters {
Erik Språng4c6ca302019-04-08 15:14:01 +0200198 RateControlParameters();
199 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng16cb8f52019-04-12 13:59:09 +0200200 double framerate_fps);
201 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +0200202 double framerate_fps,
203 DataRate bandwidth_allocation);
204 virtual ~RateControlParameters();
205
Erik Språng4d9df382019-03-27 15:00:43 +0100206 // Target bitrate, per spatial/temporal layer.
207 // A target bitrate of 0bps indicates a layer should not be encoded at all.
208 VideoBitrateAllocation bitrate;
209 // Target framerate, in fps. A value <= 0.0 is invalid and should be
210 // interpreted as framerate target not available. In this case the encoder
211 // should fall back to the max framerate specified in |codec_settings| of
212 // the last InitEncode() call.
213 double framerate_fps;
214 // The network bandwidth available for video. This is at least
215 // |bitrate.get_sum_bps()|, but may be higher if the application is not
216 // network constrained.
217 DataRate bandwidth_allocation;
218 };
219
Elad Alon6c371ca2019-04-04 12:28:51 +0200220 struct LossNotification {
221 // The timestamp of the last decodable frame *prior* to the last received.
222 // (The last received - described below - might itself be decodable or not.)
223 uint32_t timestamp_of_last_decodable;
224 // The timestamp of the last received frame.
225 uint32_t timestamp_of_last_received;
226 // Describes whether the dependencies of the last received frame were
227 // all decodable.
228 // |false| if some dependencies were undecodable, |true| if all dependencies
229 // were decodable, and |nullopt| if the dependencies are unknown.
Elad Alon20789e42019-04-09 11:56:14 +0200230 absl::optional<bool> dependencies_of_last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200231 // Describes whether the received frame was decodable.
232 // |false| if some dependency was undecodable or if some packet belonging
233 // to the last received frame was missed.
234 // |true| if all dependencies were decodable and all packets belonging
235 // to the last received frame were received.
236 // |nullopt| if no packet belonging to the last frame was missed, but the
237 // last packet in the frame was not yet received.
Elad Alon20789e42019-04-09 11:56:14 +0200238 absl::optional<bool> last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200239 };
240
Elad Alon370f93a2019-06-11 14:57:57 +0200241 // Negotiated capabilities which the VideoEncoder may expect the other
242 // side to use.
243 struct Capabilities {
244 explicit Capabilities(bool loss_notification)
245 : loss_notification(loss_notification) {}
246 bool loss_notification;
247 };
248
249 struct Settings {
250 Settings(const Capabilities& capabilities,
251 int number_of_cores,
252 size_t max_payload_size)
253 : capabilities(capabilities),
254 number_of_cores(number_of_cores),
255 max_payload_size(max_payload_size) {}
256
257 Capabilities capabilities;
258 int number_of_cores;
259 size_t max_payload_size;
260 };
261
ilnikd60d06a2017-04-05 03:02:20 -0700262 static VideoCodecVP8 GetDefaultVp8Settings();
263 static VideoCodecVP9 GetDefaultVp9Settings();
264 static VideoCodecH264 GetDefaultH264Settings();
265
266 virtual ~VideoEncoder() {}
267
268 // Initialize the encoder with the information from the codecSettings
269 //
270 // Input:
271 // - codec_settings : Codec settings
Elad Alon370f93a2019-06-11 14:57:57 +0200272 // - settings : Settings affecting the encoding itself.
273 // Input for deprecated version:
ilnikd60d06a2017-04-05 03:02:20 -0700274 // - number_of_cores : Number of cores available for the encoder
275 // - max_payload_size : The maximum size each payload is allowed
276 // to have. Usually MTU - overhead.
277 //
278 // Return value : Set bit rate if OK
279 // <0 - Errors:
280 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
281 // WEBRTC_VIDEO_CODEC_ERR_SIZE
ilnikd60d06a2017-04-05 03:02:20 -0700282 // WEBRTC_VIDEO_CODEC_MEMORY
283 // WEBRTC_VIDEO_CODEC_ERROR
Elad Alon370f93a2019-06-11 14:57:57 +0200284 // TODO(bugs.webrtc.org/10720): After updating downstream projects and posting
285 // an announcement to discuss-webrtc, remove the three-parameters variant
286 // and make the two-parameters variant pure-virtual.
287 /* RTC_DEPRECATED */ virtual int32_t InitEncode(
288 const VideoCodec* codec_settings,
289 int32_t number_of_cores,
290 size_t max_payload_size);
291 virtual int InitEncode(const VideoCodec* codec_settings,
292 const VideoEncoder::Settings& settings);
ilnikd60d06a2017-04-05 03:02:20 -0700293
294 // Register an encode complete callback object.
295 //
296 // Input:
297 // - callback : Callback object which handles encoded images.
298 //
299 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
300 virtual int32_t RegisterEncodeCompleteCallback(
301 EncodedImageCallback* callback) = 0;
302
303 // Free encoder memory.
304 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
305 virtual int32_t Release() = 0;
306
307 // Encode an I420 image (as a part of a video stream). The encoded image
308 // will be returned to the user through the encode complete callback.
309 //
310 // Input:
311 // - frame : Image to be encoded
312 // - frame_types : Frame type to be generated by the encoder.
313 //
314 // Return value : WEBRTC_VIDEO_CODEC_OK if OK
315 // <0 - Errors:
316 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
317 // WEBRTC_VIDEO_CODEC_MEMORY
318 // WEBRTC_VIDEO_CODEC_ERROR
ilnikd60d06a2017-04-05 03:02:20 -0700319 virtual int32_t Encode(const VideoFrame& frame,
Niels Möller9d766b92019-03-28 09:19:35 +0100320 const std::vector<VideoFrameType>* frame_types) = 0;
ilnikd60d06a2017-04-05 03:02:20 -0700321
Erik Språng4d9df382019-03-27 15:00:43 +0100322 // Sets rate control parameters: bitrate, framerate, etc. These settings are
323 // instantaneous (i.e. not moving averages) and should apply from now until
324 // the next call to SetRates().
Erik Språng157b7812019-05-13 11:37:12 +0200325 virtual void SetRates(const RateControlParameters& parameters) = 0;
Erik Språng4d9df382019-03-27 15:00:43 +0100326
Elad Aloncde8ab22019-03-20 11:56:20 +0100327 // Inform the encoder when the packet loss rate changes.
328 //
329 // Input: - packet_loss_rate : The packet loss rate (0.0 to 1.0).
330 virtual void OnPacketLossRateUpdate(float packet_loss_rate);
331
332 // Inform the encoder when the round trip time changes.
333 //
334 // Input: - rtt_ms : The new RTT, in milliseconds.
335 virtual void OnRttUpdate(int64_t rtt_ms);
336
Elad Alon6c371ca2019-04-04 12:28:51 +0200337 // Called when a loss notification is received.
338 virtual void OnLossNotification(const LossNotification& loss_notification);
339
Erik Språngd3438aa2018-11-08 16:56:43 +0100340 // Returns meta-data about the encoder, such as implementation name.
341 // The output of this method may change during runtime. For instance if a
342 // hardware encoder fails, it may fall back to doing software encoding using
343 // an implementation with different characteristics.
Erik Språnge2fd86a2018-10-24 11:32:39 +0200344 virtual EncoderInfo GetEncoderInfo() const;
ilnikd60d06a2017-04-05 03:02:20 -0700345};
ilnikd60d06a2017-04-05 03:02:20 -0700346} // namespace webrtc
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200347#endif // API_VIDEO_CODECS_VIDEO_ENCODER_H_