blob: c01309f3e604d4545ed30a452cc57bd957952181 [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 };
Niels Möller225c7872018-02-22 15:03:53 +010089 // Quality scaling is enabled if thresholds are provided.
ilnikd60d06a2017-04-05 03:02:20 -070090 struct ScalingSettings {
Niels Möller225c7872018-02-22 15:03:53 +010091 private:
92 // Private magic type for kOff, implicitly convertible to
93 // ScalingSettings.
94 struct KOff {};
95
96 public:
97 // TODO(nisse): Would be nicer if kOff were a constant ScalingSettings
Danil Chapovalov0bc58cf2018-06-21 13:32:56 +020098 // rather than a magic value. However, absl::optional is not trivially copy
Niels Möller225c7872018-02-22 15:03:53 +010099 // constructible, and hence a constant ScalingSettings needs a static
100 // initializer, which is strongly discouraged in Chrome. We can hopefully
101 // fix this when we switch to absl::optional or std::optional.
102 static constexpr KOff kOff = {};
103
104 ScalingSettings(int low, int high);
105 ScalingSettings(int low, int high, int min_pixels);
mflodman351424e2017-08-10 02:43:14 -0700106 ScalingSettings(const ScalingSettings&);
Niels Möller225c7872018-02-22 15:03:53 +0100107 ScalingSettings(KOff); // NOLINT(runtime/explicit)
mflodman351424e2017-08-10 02:43:14 -0700108 ~ScalingSettings();
109
Erik Språnge2fd86a2018-10-24 11:32:39 +0200110 absl::optional<QpThresholds> thresholds;
asapersson142fcc92017-08-17 08:58:54 -0700111
112 // We will never ask for a resolution lower than this.
113 // TODO(kthelgason): Lower this limit when better testing
114 // on MediaCodec and fallback implementations are in place.
115 // See https://bugs.chromium.org/p/webrtc/issues/detail?id=7206
Erik Språnge2fd86a2018-10-24 11:32:39 +0200116 int min_pixels_per_frame = 320 * 180;
Niels Möller225c7872018-02-22 15:03:53 +0100117
118 private:
119 // Private constructor; to get an object without thresholds, use
120 // the magic constant ScalingSettings::kOff.
121 ScalingSettings();
ilnikd60d06a2017-04-05 03:02:20 -0700122 };
ilnikd60d06a2017-04-05 03:02:20 -0700123
Erik Språnge2fd86a2018-10-24 11:32:39 +0200124 // Struct containing metadata about the encoder implementing this interface.
125 struct EncoderInfo {
Erik Språngdbdd8392019-01-17 15:27:50 +0100126 static constexpr uint8_t kMaxFramerateFraction =
127 std::numeric_limits<uint8_t>::max();
128
Erik Språnge2fd86a2018-10-24 11:32:39 +0200129 EncoderInfo();
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100130 EncoderInfo(const EncoderInfo&);
131
Erik Språnge2fd86a2018-10-24 11:32:39 +0200132 ~EncoderInfo();
133
134 // Any encoder implementation wishing to use the WebRTC provided
135 // quality scaler must populate this field.
136 ScalingSettings scaling_settings;
137
138 // If true, encoder supports working with a native handle (e.g. texture
139 // handle for hw codecs) rather than requiring a raw I420 buffer.
140 bool supports_native_handle;
141
142 // The name of this particular encoder implementation, e.g. "libvpx".
143 std::string implementation_name;
Erik Språngd3438aa2018-11-08 16:56:43 +0100144
145 // If this field is true, the encoder rate controller must perform
146 // well even in difficult situations, and produce close to the specified
147 // target bitrate seen over a reasonable time window, drop frames if
148 // necessary in order to keep the rate correct, and react quickly to
149 // changing bitrate targets. If this method returns true, we disable the
150 // frame dropper in the media optimization module and rely entirely on the
151 // encoder to produce media at a bitrate that closely matches the target.
152 // Any overshooting may result in delay buildup. If this method returns
153 // false (default behavior), the media opt frame dropper will drop input
154 // frames if it suspect encoder misbehavior. Misbehavior is common,
155 // especially in hardware codecs. Disable media opt at your own risk.
156 bool has_trusted_rate_controller;
Mirta Dvornicic897a9912018-11-30 13:12:21 +0100157
158 // If this field is true, the encoder uses hardware support and different
159 // thresholds will be used in CPU adaptation.
160 bool is_hardware_accelerated;
161
162 // If this field is true, the encoder uses internal camera sources, meaning
163 // that it does not require/expect frames to be delivered via
164 // webrtc::VideoEncoder::Encode.
165 // Internal source encoders are deprecated and support for them will be
166 // phased out.
167 bool has_internal_source;
Erik Språngdbdd8392019-01-17 15:27:50 +0100168
169 // For each spatial layer (simulcast stream or SVC layer), represented as an
170 // element in |fps_allocation| a vector indicates how many temporal layers
171 // the encoder is using for that spatial layer.
172 // For each spatial/temporal layer pair, the frame rate fraction is given as
173 // an 8bit unsigned integer where 0 = 0% and 255 = 100%.
174 //
175 // If the vector is empty for a given spatial layer, it indicates that frame
176 // rates are not defined and we can't count on any specific frame rate to be
177 // generated. Likely this indicates Vp8TemporalLayersType::kBitrateDynamic.
178 //
179 // The encoder may update this on a per-frame basis in response to both
180 // internal and external signals.
181 //
182 // Spatial layers are treated independently, but temporal layers are
183 // cumulative. For instance, if:
184 // fps_allocation[0][0] = kFullFramerate / 2;
185 // fps_allocation[0][1] = kFullFramerate;
186 // Then half of the frames are in the base layer and half is in TL1, but
187 // since TL1 is assumed to depend on the base layer, the frame rate is
188 // indicated as the full 100% for the top layer.
189 //
190 // Defaults to a single spatial layer containing a single temporal layer
191 // with a 100% frame rate fraction.
192 absl::InlinedVector<uint8_t, kMaxTemporalStreams>
193 fps_allocation[kMaxSpatialLayers];
Erik Språnge2fd86a2018-10-24 11:32:39 +0200194 };
195
Erik Språng4d9df382019-03-27 15:00:43 +0100196 struct RateControlParameters {
Erik Språng4c6ca302019-04-08 15:14:01 +0200197 RateControlParameters();
198 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng16cb8f52019-04-12 13:59:09 +0200199 double framerate_fps);
200 RateControlParameters(const VideoBitrateAllocation& bitrate,
Erik Språng4c6ca302019-04-08 15:14:01 +0200201 double framerate_fps,
202 DataRate bandwidth_allocation);
203 virtual ~RateControlParameters();
204
Erik Språng4d9df382019-03-27 15:00:43 +0100205 // Target bitrate, per spatial/temporal layer.
206 // A target bitrate of 0bps indicates a layer should not be encoded at all.
207 VideoBitrateAllocation bitrate;
208 // Target framerate, in fps. A value <= 0.0 is invalid and should be
209 // interpreted as framerate target not available. In this case the encoder
210 // should fall back to the max framerate specified in |codec_settings| of
211 // the last InitEncode() call.
212 double framerate_fps;
213 // The network bandwidth available for video. This is at least
214 // |bitrate.get_sum_bps()|, but may be higher if the application is not
215 // network constrained.
216 DataRate bandwidth_allocation;
217 };
218
Elad Alon6c371ca2019-04-04 12:28:51 +0200219 struct LossNotification {
220 // The timestamp of the last decodable frame *prior* to the last received.
221 // (The last received - described below - might itself be decodable or not.)
222 uint32_t timestamp_of_last_decodable;
223 // The timestamp of the last received frame.
224 uint32_t timestamp_of_last_received;
225 // Describes whether the dependencies of the last received frame were
226 // all decodable.
227 // |false| if some dependencies were undecodable, |true| if all dependencies
228 // were decodable, and |nullopt| if the dependencies are unknown.
Elad Alon20789e42019-04-09 11:56:14 +0200229 absl::optional<bool> dependencies_of_last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200230 // Describes whether the received frame was decodable.
231 // |false| if some dependency was undecodable or if some packet belonging
232 // to the last received frame was missed.
233 // |true| if all dependencies were decodable and all packets belonging
234 // to the last received frame were received.
235 // |nullopt| if no packet belonging to the last frame was missed, but the
236 // last packet in the frame was not yet received.
Elad Alon20789e42019-04-09 11:56:14 +0200237 absl::optional<bool> last_received_decodable;
Elad Alon6c371ca2019-04-04 12:28:51 +0200238 };
239
ilnikd60d06a2017-04-05 03:02:20 -0700240 static VideoCodecVP8 GetDefaultVp8Settings();
241 static VideoCodecVP9 GetDefaultVp9Settings();
242 static VideoCodecH264 GetDefaultH264Settings();
243
244 virtual ~VideoEncoder() {}
245
246 // Initialize the encoder with the information from the codecSettings
247 //
248 // Input:
249 // - codec_settings : Codec settings
250 // - number_of_cores : Number of cores available for the encoder
251 // - max_payload_size : The maximum size each payload is allowed
252 // to have. Usually MTU - overhead.
253 //
254 // Return value : Set bit rate if OK
255 // <0 - Errors:
256 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
257 // WEBRTC_VIDEO_CODEC_ERR_SIZE
ilnikd60d06a2017-04-05 03:02:20 -0700258 // WEBRTC_VIDEO_CODEC_MEMORY
259 // WEBRTC_VIDEO_CODEC_ERROR
Philip Eliasson49d661a2019-06-11 11:55:47 +0000260 virtual int32_t InitEncode(const VideoCodec* codec_settings,
261 int32_t number_of_cores,
262 size_t max_payload_size) = 0;
ilnikd60d06a2017-04-05 03:02:20 -0700263
264 // Register an encode complete callback object.
265 //
266 // Input:
267 // - callback : Callback object which handles encoded images.
268 //
269 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
270 virtual int32_t RegisterEncodeCompleteCallback(
271 EncodedImageCallback* callback) = 0;
272
273 // Free encoder memory.
274 // Return value : WEBRTC_VIDEO_CODEC_OK if OK, < 0 otherwise.
275 virtual int32_t Release() = 0;
276
277 // Encode an I420 image (as a part of a video stream). The encoded image
278 // will be returned to the user through the encode complete callback.
279 //
280 // Input:
281 // - frame : Image to be encoded
282 // - frame_types : Frame type to be generated by the encoder.
283 //
284 // Return value : WEBRTC_VIDEO_CODEC_OK if OK
285 // <0 - Errors:
286 // WEBRTC_VIDEO_CODEC_ERR_PARAMETER
287 // WEBRTC_VIDEO_CODEC_MEMORY
288 // WEBRTC_VIDEO_CODEC_ERROR
ilnikd60d06a2017-04-05 03:02:20 -0700289 virtual int32_t Encode(const VideoFrame& frame,
Niels Möller9d766b92019-03-28 09:19:35 +0100290 const std::vector<VideoFrameType>* frame_types) = 0;
ilnikd60d06a2017-04-05 03:02:20 -0700291
Erik Språng4d9df382019-03-27 15:00:43 +0100292 // Sets rate control parameters: bitrate, framerate, etc. These settings are
293 // instantaneous (i.e. not moving averages) and should apply from now until
294 // the next call to SetRates().
Erik Språng157b7812019-05-13 11:37:12 +0200295 virtual void SetRates(const RateControlParameters& parameters) = 0;
Erik Språng4d9df382019-03-27 15:00:43 +0100296
Elad Aloncde8ab22019-03-20 11:56:20 +0100297 // Inform the encoder when the packet loss rate changes.
298 //
299 // Input: - packet_loss_rate : The packet loss rate (0.0 to 1.0).
300 virtual void OnPacketLossRateUpdate(float packet_loss_rate);
301
302 // Inform the encoder when the round trip time changes.
303 //
304 // Input: - rtt_ms : The new RTT, in milliseconds.
305 virtual void OnRttUpdate(int64_t rtt_ms);
306
Elad Alon6c371ca2019-04-04 12:28:51 +0200307 // Called when a loss notification is received.
308 virtual void OnLossNotification(const LossNotification& loss_notification);
309
Erik Språngd3438aa2018-11-08 16:56:43 +0100310 // Returns meta-data about the encoder, such as implementation name.
311 // The output of this method may change during runtime. For instance if a
312 // hardware encoder fails, it may fall back to doing software encoding using
313 // an implementation with different characteristics.
Erik Språnge2fd86a2018-10-24 11:32:39 +0200314 virtual EncoderInfo GetEncoderInfo() const;
ilnikd60d06a2017-04-05 03:02:20 -0700315};
ilnikd60d06a2017-04-05 03:02:20 -0700316} // namespace webrtc
Mirko Bonadei92ea95e2017-09-15 06:47:31 +0200317#endif // API_VIDEO_CODECS_VIDEO_ENCODER_H_