blob: 5609e93b647948967a88f4b5d3e4d303e4cfaa81 [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
Sergey Silkinbe0adee2019-06-26 14:11:03 +0200125 // Bitrate thresholds for resolution.
126 struct ResolutionBitrateThresholds {
127 ResolutionBitrateThresholds(int frame_size_pixels,
128 int min_start_bitrate_bps,
129 int min_bitrate_bps,
130 int max_bitrate_bps)
131 : frame_size_pixels(frame_size_pixels),
132 min_start_bitrate_bps(min_start_bitrate_bps),
133 min_bitrate_bps(min_bitrate_bps),
134 max_bitrate_bps(max_bitrate_bps) {}
135 // Size of video frame, in pixels, the bitrate thresholds are intended for.
136 int frame_size_pixels = 0;
137 // Recommended minimum bitrate to start encoding.
138 int min_start_bitrate_bps = 0;
139 // Recommended minimum bitrate.
140 int min_bitrate_bps = 0;
141 // Recommended maximum bitrate.
142 int max_bitrate_bps = 0;
143 };
144
Erik Språnge2fd86a2018-10-24 11:32:39 +0200145 // Struct containing metadata about the encoder implementing this interface.
146 struct EncoderInfo {
Erik Språngdbdd8392019-01-17 15:27:50 +0100147 static constexpr uint8_t kMaxFramerateFraction =
148 std::numeric_limits<uint8_t>::max();
149
Erik Språnge2fd86a2018-10-24 11:32:39 +0200150 EncoderInfo();
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100151 EncoderInfo(const EncoderInfo&);
152
Erik Språnge2fd86a2018-10-24 11:32:39 +0200153 ~EncoderInfo();
154
155 // Any encoder implementation wishing to use the WebRTC provided
156 // quality scaler must populate this field.
157 ScalingSettings scaling_settings;
158
159 // If true, encoder supports working with a native handle (e.g. texture
160 // handle for hw codecs) rather than requiring a raw I420 buffer.
161 bool supports_native_handle;
162
163 // The name of this particular encoder implementation, e.g. "libvpx".
164 std::string implementation_name;
Erik Språngd3438aa2018-11-08 16:56:43 +0100165
166 // If this field is true, the encoder rate controller must perform
167 // well even in difficult situations, and produce close to the specified
168 // target bitrate seen over a reasonable time window, drop frames if
169 // necessary in order to keep the rate correct, and react quickly to
170 // changing bitrate targets. If this method returns true, we disable the
171 // frame dropper in the media optimization module and rely entirely on the
172 // encoder to produce media at a bitrate that closely matches the target.
173 // Any overshooting may result in delay buildup. If this method returns
174 // false (default behavior), the media opt frame dropper will drop input
175 // frames if it suspect encoder misbehavior. Misbehavior is common,
176 // especially in hardware codecs. Disable media opt at your own risk.
177 bool has_trusted_rate_controller;
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100178
179 // If this field is true, the encoder uses hardware support and different
180 // thresholds will be used in CPU adaptation.
181 bool is_hardware_accelerated;
182
183 // If this field is true, the encoder uses internal camera sources, meaning
184 // that it does not require/expect frames to be delivered via
185 // webrtc::VideoEncoder::Encode.
186 // Internal source encoders are deprecated and support for them will be
187 // phased out.
188 bool has_internal_source;
Erik Språngdbdd8392019-01-17 15:27:50 +0100189
190 // For each spatial layer (simulcast stream or SVC layer), represented as an
191 // element in |fps_allocation| a vector indicates how many temporal layers
192 // the encoder is using for that spatial layer.
193 // For each spatial/temporal layer pair, the frame rate fraction is given as
194 // an 8bit unsigned integer where 0 = 0% and 255 = 100%.
195 //
196 // If the vector is empty for a given spatial layer, it indicates that frame
197 // rates are not defined and we can't count on any specific frame rate to be
198 // generated. Likely this indicates Vp8TemporalLayersType::kBitrateDynamic.
199 //
200 // The encoder may update this on a per-frame basis in response to both
201 // internal and external signals.
202 //
203 // Spatial layers are treated independently, but temporal layers are
204 // cumulative. For instance, if:
205 // fps_allocation[0][0] = kFullFramerate / 2;
206 // fps_allocation[0][1] = kFullFramerate;
207 // Then half of the frames are in the base layer and half is in TL1, but
208 // since TL1 is assumed to depend on the base layer, the frame rate is
209 // indicated as the full 100% for the top layer.
210 //
211 // Defaults to a single spatial layer containing a single temporal layer
212 // with a 100% frame rate fraction.
213 absl::InlinedVector<uint8_t, kMaxTemporalStreams>
214 fps_allocation[kMaxSpatialLayers];
Sergey Silkinbe0adee2019-06-26 14:11:03 +0200215
216 // Recommended bitrate thresholds for different resolutions.
217 std::vector<ResolutionBitrateThresholds> resolution_bitrate_thresholds;
Erik Språnge2fd86a2018-10-24 11:32:39 +0200218 };
219
Erik Språng4d9df382019-03-27 15:00:43 +0100220 struct RateControlParameters {
Erik Språng4c6ca302019-04-08 15:14:01 +0200221 RateControlParameters();
222 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng16cb8f52019-04-12 13:59:09 +0200223 double framerate_fps);
224 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +0200225 double framerate_fps,
226 DataRate bandwidth_allocation);
227 virtual ~RateControlParameters();
228
Erik Språng4d9df382019-03-27 15:00:43 +0100229 // Target bitrate, per spatial/temporal layer.
230 // A target bitrate of 0bps indicates a layer should not be encoded at all.
231 VideoBitrateAllocation bitrate;
232 // Target framerate, in fps. A value <= 0.0 is invalid and should be
233 // interpreted as framerate target not available. In this case the encoder
234 // should fall back to the max framerate specified in |codec_settings| of
235 // the last InitEncode() call.
236 double framerate_fps;
237 // The network bandwidth available for video. This is at least
238 // |bitrate.get_sum_bps()|, but may be higher if the application is not
239 // network constrained.
240 DataRate bandwidth_allocation;
241 };
242
Elad Alon6c371ca2019-04-04 12:28:51 +0200243 struct LossNotification {
244 // The timestamp of the last decodable frame *prior* to the last received.
245 // (The last received - described below - might itself be decodable or not.)
246 uint32_t timestamp_of_last_decodable;
247 // The timestamp of the last received frame.
248 uint32_t timestamp_of_last_received;
249 // Describes whether the dependencies of the last received frame were
250 // all decodable.
251 // |false| if some dependencies were undecodable, |true| if all dependencies
252 // were decodable, and |nullopt| if the dependencies are unknown.
Elad Alon20789e42019-04-09 11:56:14 +0200253 absl::optional<bool> dependencies_of_last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200254 // Describes whether the received frame was decodable.
255 // |false| if some dependency was undecodable or if some packet belonging
256 // to the last received frame was missed.
257 // |true| if all dependencies were decodable and all packets belonging
258 // to the last received frame were received.
259 // |nullopt| if no packet belonging to the last frame was missed, but the
260 // last packet in the frame was not yet received.
Elad Alon20789e42019-04-09 11:56:14 +0200261 absl::optional<bool> last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200262 };
263
Elad Alon370f93a2019-06-11 14:57:57 +0200264 // Negotiated capabilities which the VideoEncoder may expect the other
265 // side to use.
266 struct Capabilities {
267 explicit Capabilities(bool loss_notification)
268 : loss_notification(loss_notification) {}
269 bool loss_notification;
270 };
271
272 struct Settings {
273 Settings(const Capabilities& capabilities,
274 int number_of_cores,
275 size_t max_payload_size)
276 : capabilities(capabilities),
277 number_of_cores(number_of_cores),
278 max_payload_size(max_payload_size) {}
279
280 Capabilities capabilities;
281 int number_of_cores;
282 size_t max_payload_size;
283 };
284
ilnikd60d06a2017-04-05 03:02:20 -0700285 static VideoCodecVP8 GetDefaultVp8Settings();
286 static VideoCodecVP9 GetDefaultVp9Settings();
287 static VideoCodecH264 GetDefaultH264Settings();
288
289 virtual ~VideoEncoder() {}
290
291 // Initialize the encoder with the information from the codecSettings
292 //
293 // Input:
294 // - codec_settings : Codec settings
Elad Alon370f93a2019-06-11 14:57:57 +0200295 // - settings : Settings affecting the encoding itself.
296 // Input for deprecated version:
ilnikd60d06a2017-04-05 03:02:20 -0700297 // - number_of_cores : Number of cores available for the encoder
298 // - max_payload_size : The maximum size each payload is allowed
299 // to have. Usually MTU - overhead.
300 //
301 // Return value : Set bit rate if OK
302 // <0 - Errors:
303 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
304 // WEBRTC_VIDEO_CODEC_ERR_SIZE
ilnikd60d06a2017-04-05 03:02:20 -0700305 // WEBRTC_VIDEO_CODEC_MEMORY
306 // WEBRTC_VIDEO_CODEC_ERROR
Elad Alon370f93a2019-06-11 14:57:57 +0200307 // TODO(bugs.webrtc.org/10720): After updating downstream projects and posting
308 // an announcement to discuss-webrtc, remove the three-parameters variant
309 // and make the two-parameters variant pure-virtual.
310 /* RTC_DEPRECATED */ virtual int32_t InitEncode(
311 const VideoCodec* codec_settings,
312 int32_t number_of_cores,
313 size_t max_payload_size);
314 virtual int InitEncode(const VideoCodec* codec_settings,
315 const VideoEncoder::Settings& settings);
ilnikd60d06a2017-04-05 03:02:20 -0700316
317 // Register an encode complete callback object.
318 //
319 // Input:
320 // - callback : Callback object which handles encoded images.
321 //
322 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
323 virtual int32_t RegisterEncodeCompleteCallback(
324 EncodedImageCallback* callback) = 0;
325
326 // Free encoder memory.
327 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
328 virtual int32_t Release() = 0;
329
330 // Encode an I420 image (as a part of a video stream). The encoded image
331 // will be returned to the user through the encode complete callback.
332 //
333 // Input:
334 // - frame : Image to be encoded
335 // - frame_types : Frame type to be generated by the encoder.
336 //
337 // Return value : WEBRTC_VIDEO_CODEC_OK if OK
338 // <0 - Errors:
339 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
340 // WEBRTC_VIDEO_CODEC_MEMORY
341 // WEBRTC_VIDEO_CODEC_ERROR
ilnikd60d06a2017-04-05 03:02:20 -0700342 virtual int32_t Encode(const VideoFrame& frame,
Niels Möller9d766b92019-03-28 09:19:35 +0100343 const std::vector<VideoFrameType>* frame_types) = 0;
ilnikd60d06a2017-04-05 03:02:20 -0700344
Erik Språng4d9df382019-03-27 15:00:43 +0100345 // Sets rate control parameters: bitrate, framerate, etc. These settings are
346 // instantaneous (i.e. not moving averages) and should apply from now until
347 // the next call to SetRates().
Erik Språng157b7812019-05-13 11:37:12 +0200348 virtual void SetRates(const RateControlParameters& parameters) = 0;
Erik Språng4d9df382019-03-27 15:00:43 +0100349
Elad Aloncde8ab22019-03-20 11:56:20 +0100350 // Inform the encoder when the packet loss rate changes.
351 //
352 // Input: - packet_loss_rate : The packet loss rate (0.0 to 1.0).
353 virtual void OnPacketLossRateUpdate(float packet_loss_rate);
354
355 // Inform the encoder when the round trip time changes.
356 //
357 // Input: - rtt_ms : The new RTT, in milliseconds.
358 virtual void OnRttUpdate(int64_t rtt_ms);
359
Elad Alon6c371ca2019-04-04 12:28:51 +0200360 // Called when a loss notification is received.
361 virtual void OnLossNotification(const LossNotification& loss_notification);
362
Erik Språngd3438aa2018-11-08 16:56:43 +0100363 // Returns meta-data about the encoder, such as implementation name.
364 // The output of this method may change during runtime. For instance if a
365 // hardware encoder fails, it may fall back to doing software encoding using
366 // an implementation with different characteristics.
Erik Språnge2fd86a2018-10-24 11:32:39 +0200367 virtual EncoderInfo GetEncoderInfo() const;
ilnikd60d06a2017-04-05 03:02:20 -0700368};
ilnikd60d06a2017-04-05 03:02:20 -0700369} // namespace webrtc
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200370#endif // API_VIDEO_CODECS_VIDEO_ENCODER_H_