blob: 6ff7e328a1488fbdb735661613560b801de2a8c2 [file] [log] [blame]
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001/*
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 */
11
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020012#include "modules/video_coding/codecs/vp9/vp9_impl.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000013
14#include <stdlib.h>
15#include <string.h>
16#include <time.h>
17#include <vector>
18
19#include "vpx/vpx_encoder.h"
20#include "vpx/vpx_decoder.h"
21#include "vpx/vp8cx.h"
22#include "vpx/vp8dx.h"
23
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020024#include "common_video/include/video_frame_buffer.h"
25#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkin86684962018-03-28 19:32:37 +020026#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020027#include "rtc_base/checks.h"
28#include "rtc_base/keep_ref_until_done.h"
29#include "rtc_base/logging.h"
Magnus Jedvert46a27652017-11-13 14:10:02 +010030#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/timeutils.h"
32#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000033
34namespace webrtc {
35
Marco6e89b252015-07-07 14:40:38 -070036// Only positive speeds, range for real-time coding currently is: 5 - 8.
37// Lower means slower/better quality, higher means fastest/lower quality.
38int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070039#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080040 return 8;
41#else
Marco6e89b252015-07-07 14:40:38 -070042 // For smaller resolutions, use lower speed setting (get some coding gain at
43 // the cost of increased encoding complexity).
44 if (width * height <= 352 * 288)
45 return 5;
46 else
47 return 7;
Marco002f0d02015-12-17 09:49:31 -080048#endif
Marco6e89b252015-07-07 14:40:38 -070049}
50
Peter Boström12996152016-05-14 02:03:18 +020051bool VP9Encoder::IsSupported() {
52 return true;
53}
54
Magnus Jedvert46a27652017-11-13 14:10:02 +010055std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
56 return rtc::MakeUnique<VP9EncoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000057}
58
asaperssona9455ab2015-07-31 06:10:09 -070059void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
60 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080061 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070062 enc->GetEncodedLayerFrame(pkt);
63}
64
marpan@webrtc.org5b883172014-11-01 06:10:48 +000065VP9EncoderImpl::VP9EncoderImpl()
66 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070067 encoded_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000068 inited_(false),
69 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000070 cpu_speed_(3),
71 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -070072 encoder_(nullptr),
73 config_(nullptr),
74 raw_(nullptr),
75 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +020076 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020077 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -070078 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080079 num_spatial_layers_(0),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020080 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +020081 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000082 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080083 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +000084}
85
86VP9EncoderImpl::~VP9EncoderImpl() {
87 Release();
88}
89
90int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010091 int ret_val = WEBRTC_VIDEO_CODEC_OK;
92
sprang3958ed82017-08-17 08:12:10 -070093 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080094 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070095 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +000096 }
sprang3958ed82017-08-17 08:12:10 -070097 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +010098 if (inited_) {
99 if (vpx_codec_destroy(encoder_)) {
100 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
101 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000102 }
103 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700104 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000105 }
sprang3958ed82017-08-17 08:12:10 -0700106 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000107 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700108 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000109 }
sprang3958ed82017-08-17 08:12:10 -0700110 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000111 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700112 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 }
114 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100115 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000116}
117
sprangce4aef12015-11-02 07:23:20 -0800118bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
119 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
120 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100121 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800122}
123
Erik Språng566124a2018-04-23 12:32:22 +0200124bool VP9EncoderImpl::SetSvcRates(
125 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700126 uint8_t i = 0;
127
Sergey Silkin86684962018-03-28 19:32:37 +0200128 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200129
sprangce4aef12015-11-02 07:23:20 -0800130 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200131 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200132 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200133 config_->ss_target_bitrate[sl_idx] =
134 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
135
136 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
137 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
138 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
139 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200140
141 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
142 if (is_layer_enabled && !was_layer_enabled) {
143 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
144 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
145 // TODO(wemb:1526): remove key frame request when issue is fixed.
146 force_key_frame_ = true;
147 }
148 }
sprangce4aef12015-11-02 07:23:20 -0800149 }
150 } else {
151 float rate_ratio[VPX_MAX_LAYERS] = {0};
152 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700153
sprangce4aef12015-11-02 07:23:20 -0800154 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800155 if (svc_params_.scaling_factor_num[i] <= 0 ||
156 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100157 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800158 return false;
159 }
160 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800161 static_cast<float>(svc_params_.scaling_factor_num[i]) /
162 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800163 total += rate_ratio[i];
164 }
165
166 for (i = 0; i < num_spatial_layers_; ++i) {
167 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
168 config_->rc_target_bitrate * rate_ratio[i] / total);
169 if (num_temporal_layers_ == 1) {
170 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
171 } else if (num_temporal_layers_ == 2) {
172 config_->layer_target_bitrate[i * num_temporal_layers_] =
173 config_->ss_target_bitrate[i] * 2 / 3;
174 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
175 config_->ss_target_bitrate[i];
176 } else if (num_temporal_layers_ == 3) {
177 config_->layer_target_bitrate[i * num_temporal_layers_] =
178 config_->ss_target_bitrate[i] / 2;
179 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
180 config_->layer_target_bitrate[i * num_temporal_layers_] +
181 (config_->ss_target_bitrate[i] / 4);
182 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
183 config_->ss_target_bitrate[i];
184 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100185 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
186 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800187 return false;
188 }
asaperssona9455ab2015-07-31 06:10:09 -0700189 }
190 }
191
192 // For now, temporal layers only supported when having one spatial layer.
193 if (num_spatial_layers_ == 1) {
194 for (i = 0; i < num_temporal_layers_; ++i) {
195 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
196 }
197 }
198
199 return true;
200}
201
Erik Språng08127a92016-11-16 16:41:30 +0100202int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200203 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100204 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000205 if (!inited_) {
206 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
207 }
208 if (encoder_->err) {
209 return WEBRTC_VIDEO_CODEC_ERROR;
210 }
Erik Språng08127a92016-11-16 16:41:30 +0100211 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000212 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
213 }
214 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100215 if (codec_.maxBitrate > 0 &&
216 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
217 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000218 }
Erik Språng08127a92016-11-16 16:41:30 +0100219
Erik Språng08127a92016-11-16 16:41:30 +0100220 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700221
Sergey Silkin86684962018-03-28 19:32:37 +0200222 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700223 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
224 }
225
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000226 // Update encoder context
227 if (vpx_codec_enc_config_set(encoder_, config_)) {
228 return WEBRTC_VIDEO_CODEC_ERROR;
229 }
230 return WEBRTC_VIDEO_CODEC_OK;
231}
232
233int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
234 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000235 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700236 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000237 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
238 }
239 if (inst->maxFramerate < 1) {
240 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
241 }
242 // Allow zero to represent an unspecified maxBitRate
243 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
244 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
245 }
246 if (inst->width < 1 || inst->height < 1) {
247 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
248 }
249 if (number_of_cores < 1) {
250 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
251 }
hta257dc392016-10-25 09:05:06 -0700252 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700253 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
254 }
ilnik2a8c2f52017-02-15 02:23:28 -0800255 // libvpx probably does not support more than 3 spatial layers.
256 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700257 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
258 }
philipelcfc319b2015-11-10 07:17:23 -0800259
asapersson86956de2016-01-26 01:05:20 -0800260 int ret_val = Release();
261 if (ret_val < 0) {
262 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000263 }
sprang3958ed82017-08-17 08:12:10 -0700264 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000265 encoder_ = new vpx_codec_ctx_t;
266 }
sprang3958ed82017-08-17 08:12:10 -0700267 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000268 config_ = new vpx_codec_enc_cfg_t;
269 }
270 timestamp_ = 0;
271 if (&codec_ != inst) {
272 codec_ = *inst;
273 }
asaperssona9455ab2015-07-31 06:10:09 -0700274
hta257dc392016-10-25 09:05:06 -0700275 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200276 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700277 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700278 if (num_temporal_layers_ == 0)
279 num_temporal_layers_ = 1;
280
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000281 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700282 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800283 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000284 }
nisseeb44b392017-04-28 07:18:05 -0700285 encoded_image_._size =
286 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000287 encoded_image_._buffer = new uint8_t[encoded_image_._size];
288 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700289 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000290 // pointer will be set in encode. Setting align to 1, as it is meaningless
291 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700292 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
293 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000294 // Populate encoder configuration with default values.
295 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
296 return WEBRTC_VIDEO_CODEC_ERROR;
297 }
298 config_->g_w = codec_.width;
299 config_->g_h = codec_.height;
300 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Niels Möller65fb4042018-04-25 14:46:06 +0200301 config_->g_error_resilient =
302 (num_spatial_layers_ > 1 || num_temporal_layers_ > 1) ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000303 // Setting the time base of the codec.
304 config_->g_timebase.num = 1;
305 config_->g_timebase.den = 90000;
306 config_->g_lag_in_frames = 0; // 0- no frame lagging
307 config_->g_threads = 1;
308 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700309 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000310 config_->rc_end_usage = VPX_CBR;
311 config_->g_pass = VPX_RC_ONE_PASS;
312 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000313 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000314 config_->rc_undershoot_pct = 50;
315 config_->rc_overshoot_pct = 50;
316 config_->rc_buf_initial_sz = 500;
317 config_->rc_buf_optimal_sz = 600;
318 config_->rc_buf_sz = 1000;
319 // Set the maximum target size of any key-frame.
320 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700321 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000322 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700323 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100324 // Needs to be set (in svc mode) to get correct periodic key frame interval
325 // (will have no effect in non-svc).
326 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000327 } else {
328 config_->kf_mode = VPX_KF_DISABLED;
329 }
hta257dc392016-10-25 09:05:06 -0700330 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000331 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800332 config_->g_threads =
333 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700334
Marco6e89b252015-07-07 14:40:38 -0700335 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700336
337 // TODO(asapersson): Check configuration of temporal switch up and increase
338 // pattern length.
hta257dc392016-10-25 09:05:06 -0700339 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200340
341 // TODO(ssilkin): Only non-flexible mode is supported for now.
342 RTC_DCHECK(!is_flexible_mode_);
343
344 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700345 gof_.SetGofInfoVP9(kTemporalStructureMode1);
346 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
347 config_->ts_number_layers = 1;
348 config_->ts_rate_decimator[0] = 1;
349 config_->ts_periodicity = 1;
350 config_->ts_layer_id[0] = 0;
351 } else if (num_temporal_layers_ == 2) {
352 gof_.SetGofInfoVP9(kTemporalStructureMode2);
353 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
354 config_->ts_number_layers = 2;
355 config_->ts_rate_decimator[0] = 2;
356 config_->ts_rate_decimator[1] = 1;
357 config_->ts_periodicity = 2;
358 config_->ts_layer_id[0] = 0;
359 config_->ts_layer_id[1] = 1;
360 } else if (num_temporal_layers_ == 3) {
361 gof_.SetGofInfoVP9(kTemporalStructureMode3);
362 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
363 config_->ts_number_layers = 3;
364 config_->ts_rate_decimator[0] = 4;
365 config_->ts_rate_decimator[1] = 2;
366 config_->ts_rate_decimator[2] = 1;
367 config_->ts_periodicity = 4;
368 config_->ts_layer_id[0] = 0;
369 config_->ts_layer_id[1] = 2;
370 config_->ts_layer_id[2] = 1;
371 config_->ts_layer_id[3] = 2;
372 } else {
373 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
374 }
375
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200376 inter_layer_pred_ = inst->VP9().interLayerPred;
377
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000378 return InitAndSetControlSettings(inst);
379}
380
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000381int VP9EncoderImpl::NumberOfThreads(int width,
382 int height,
383 int number_of_cores) {
384 // Keep the number of encoder threads equal to the possible number of column
385 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
386 if (width * height >= 1280 * 720 && number_of_cores > 4) {
387 return 4;
jianj23173a32017-07-12 16:11:09 -0700388 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000389 return 2;
390 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800391 // Use 2 threads for low res on ARM.
392#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
393 defined(WEBRTC_ANDROID)
394 if (width * height >= 320 * 180 && number_of_cores > 2) {
395 return 2;
396 }
397#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000398 // 1 thread less than VGA.
399 return 1;
400 }
401}
402
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000403int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100404 // Set QP-min/max per spatial and temporal layer.
405 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
406 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800407 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
408 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100409 }
asaperssona9455ab2015-07-31 06:10:09 -0700410 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800411 if (ExplicitlyConfiguredSpatialLayers()) {
412 for (int i = 0; i < num_spatial_layers_; ++i) {
413 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100414 const int scale_factor = codec_.width / layer.width;
415 RTC_DCHECK_GT(scale_factor, 0);
416
417 // Ensure scaler factor is integer.
418 if (scale_factor * layer.width != codec_.width) {
419 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
420 }
421
422 // Ensure scale factor is the same in both dimensions.
423 if (scale_factor * layer.height != codec_.height) {
424 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
425 }
426
427 // Ensure scale factor is power of two.
428 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
429 if (!is_pow_of_two) {
430 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
431 }
432
433 svc_params_.scaling_factor_num[i] = 1;
434 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800435 }
436 } else {
437 int scaling_factor_num = 256;
438 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800439 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800440 svc_params_.scaling_factor_num[i] = scaling_factor_num;
441 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800442 if (codec_.mode != kScreensharing)
443 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800444 }
asaperssona9455ab2015-07-31 06:10:09 -0700445 }
446
Sergey Silkin86684962018-03-28 19:32:37 +0200447 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200448 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200449 inst->startBitrate * 1000, inst->maxFramerate);
450 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700451 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
452 }
453
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000454 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
455 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
456 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000457 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
458 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
459 rc_max_intra_target_);
460 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700461 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700462
jianj822e5932017-07-12 16:09:58 -0700463 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700464 vpx_codec_control(
465 encoder_, VP9E_SET_SVC,
466 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200467
asaperssona9455ab2015-07-31 06:10:09 -0700468 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
469 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800470 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700471 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200472
473 if (num_spatial_layers_ > 1) {
474 switch (inter_layer_pred_) {
475 case InterLayerPredMode::kOn:
476 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
477 break;
478 case InterLayerPredMode::kOff:
479 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
480 break;
481 case InterLayerPredMode::kOnKeyPic:
482 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
483 break;
484 default:
485 RTC_NOTREACHED();
486 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200487
488 if (!is_flexible_mode_) {
489 // In RTP non-flexible mode, frame dropping of individual layers in a
490 // superframe leads to incorrect reference picture ID values in the
491 // RTP header. Dropping the entire superframe if the base is dropped
492 // or not dropping upper layers if base is not dropped mitigates
493 // the problem.
494 vpx_svc_frame_drop_t svc_drop_frame;
495 svc_drop_frame.framedrop_mode = CONSTRAINED_LAYER_DROP;
496 for (size_t i = 0; i < num_spatial_layers_; ++i) {
497 svc_drop_frame.framedrop_thresh[i] =
498 (i == 0) ? config_->rc_dropframe_thresh : 0;
499 }
500 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER,
501 &svc_drop_frame);
502 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200503 }
504
asaperssona9455ab2015-07-31 06:10:09 -0700505 // Register callback for getting each spatial layer.
506 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800507 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
508 reinterpret_cast<void*>(this)};
509 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
510 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700511
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000512 // Control function to set the number of column tiles in encoding a frame, in
513 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
514 // The number tile columns will be capped by the encoder based on image size
515 // (minimum width of tile column is 256 pixels, maximum is 4096).
516 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700517
518 // Turn on row-based multithreading.
519 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700520
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700521#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
522 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700523 // Do not enable the denoiser on ARM since optimization is pending.
524 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000525 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700526 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000527#endif
jianj6bf57e32017-06-05 13:43:49 -0700528
ivica242d6382015-09-04 06:13:23 -0700529 if (codec_.mode == kScreensharing) {
530 // Adjust internal parameters to screen content.
531 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700532 }
Marco2520e722015-09-16 14:05:00 -0700533 // Enable encoder skip of static/low content blocks.
534 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000535 inited_ = true;
536 return WEBRTC_VIDEO_CODEC_OK;
537}
538
539uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
540 // Set max to the optimal buffer level (normalized by target BR),
541 // and scaled by a scale_par.
542 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
543 // This value is presented in percentage of perFrameBw:
544 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
545 // The target in % is as follows:
546 float scale_par = 0.5;
547 uint32_t target_pct =
548 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
549 // Don't go below 3 times the per frame bandwidth.
550 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800551 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000552}
553
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700554int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000555 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700556 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000557 if (!inited_) {
558 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
559 }
sprang3958ed82017-08-17 08:12:10 -0700560 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000561 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
562 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200563
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000564 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200565 if (frame_types && !frame_types->empty()) {
566 if ((*frame_types)[0] == kVideoFrameKey) {
567 force_key_frame_ = true;
568 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000569 }
kwiberg352444f2016-11-28 15:58:53 -0800570 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
571 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700572
573 // Set input image for use in the callback.
574 // This was necessary since you need some information from input_image.
575 // You can save only the necessary information (such as timestamp) instead of
576 // doing this.
577 input_image_ = &input_image;
578
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000579 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
580 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000581 // Image in vpx_image_t format.
582 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000583 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
584 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
585 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
586 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
587 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
588 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000589
philipelcfc319b2015-11-10 07:17:23 -0800590 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200591 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000592 flags = VPX_EFLAG_FORCE_KF;
593 }
philipelcfc319b2015-11-10 07:17:23 -0800594
sprang3958ed82017-08-17 08:12:10 -0700595 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000596 uint32_t duration = 90000 / codec_.maxFramerate;
597 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
598 VPX_DL_REALTIME)) {
599 return WEBRTC_VIDEO_CODEC_ERROR;
600 }
601 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700602
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200603 const bool end_of_picture = true;
604 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200605
asaperssona9455ab2015-07-31 06:10:09 -0700606 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000607}
608
609void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800610 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200611 uint32_t timestamp,
612 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700613 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000614 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700615 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800616 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200617
618 vp9_info->first_frame_in_picture = first_frame_in_picture;
Åsa Perssonff24c042015-12-04 10:58:08 +0100619 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700620 vp9_info->inter_pic_predicted =
621 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700622 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
623 vp9_info->ss_data_available =
624 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
625 ? true
626 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700627
628 vpx_svc_layer_id_t layer_id = {0};
629 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
630
sprang3958ed82017-08-17 08:12:10 -0700631 RTC_CHECK_GT(num_temporal_layers_, 0);
632 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700633 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700634 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700635 vp9_info->temporal_idx = kNoTemporalIdx;
636 } else {
637 vp9_info->temporal_idx = layer_id.temporal_layer_id;
638 }
639 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700640 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700641 vp9_info->spatial_idx = kNoSpatialIdx;
642 } else {
643 vp9_info->spatial_idx = layer_id.spatial_layer_id;
644 }
645 if (layer_id.spatial_layer_id != 0) {
646 vp9_info->ss_data_available = false;
647 }
648
asaperssona9455ab2015-07-31 06:10:09 -0700649 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800650 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700651
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200652 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
653 pics_since_key_ = 0;
654 } else if (first_frame_in_picture) {
655 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700656 }
657
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200658 const bool is_key_pic = (pics_since_key_ == 0);
659 const bool is_inter_layer_pred_allowed =
660 (inter_layer_pred_ == InterLayerPredMode::kOn ||
661 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
662
663 // Always set inter_layer_predicted to true on high layer frame if inter-layer
664 // prediction (ILP) is allowed even if encoder didn't actually use it.
665 // Setting inter_layer_predicted to false would allow receiver to decode high
666 // layer frame without decoding low layer frame. If that would happen (e.g.
667 // if low layer frame is lost) then receiver won't be able to decode next high
668 // layer frame which uses ILP.
669 vp9_info->inter_layer_predicted =
670 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
671
672 const bool is_last_layer =
673 (layer_id.spatial_layer_id + 1 == num_spatial_layers_);
674 vp9_info->non_ref_for_inter_layer_pred =
675 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800676
ivica7f6a6fc2015-09-08 02:40:29 -0700677 // Always populate this, so that the packetizer can properly set the marker
678 // bit.
679 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800680
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200681 RTC_DCHECK(!vp9_info->flexible_mode);
682 vp9_info->gof_idx =
683 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
684 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
685 vp9_info->num_ref_pics =
686 is_key_pic ? 0 : gof_.num_ref_pics[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800687
asaperssona9455ab2015-07-31 06:10:09 -0700688 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700689 vp9_info->spatial_layer_resolution_present = true;
690 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
691 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800692 svc_params_.scaling_factor_num[i] /
693 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700694 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800695 svc_params_.scaling_factor_num[i] /
696 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700697 }
698 if (!vp9_info->flexible_mode) {
699 vp9_info->gof.CopyGofInfoVP9(gof_);
700 }
701 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000702}
703
asaperssona9455ab2015-07-31 06:10:09 -0700704int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800705 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700706
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200707 if (pkt->data.frame.sz == 0) {
708 // Ignore dropped frame.
709 return WEBRTC_VIDEO_CODEC_OK;
710 }
711
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200712 vpx_svc_layer_id_t layer_id = {0};
713 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
714
715 const bool first_frame_in_picture = encoded_image_._length == 0;
716 // Ensure we don't buffer layers of previous picture (superframe).
717 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
718
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200719 const bool end_of_picture = false;
720 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200721
asaperssond9f641e2016-01-21 01:11:35 -0800722 if (pkt->data.frame.sz > encoded_image_._size) {
723 delete[] encoded_image_._buffer;
724 encoded_image_._size = pkt->data.frame.sz;
725 encoded_image_._buffer = new uint8_t[encoded_image_._size];
726 }
asapersson86956de2016-01-26 01:05:20 -0800727 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
728 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800729
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200730 const bool is_key_frame =
731 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
732 // Ensure encoder issued key frame on request.
733 RTC_DCHECK(is_key_frame || !force_key_frame_);
734
asaperssona9455ab2015-07-31 06:10:09 -0700735 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800736 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200737 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200738 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200739 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000740 }
asapersson86956de2016-01-26 01:05:20 -0800741 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
742
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200743 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200744 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
745 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700746
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200747 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
748 encoded_image_._timeStamp = input_image_->timestamp();
749 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
750 encoded_image_.rotation_ = input_image_->rotation();
751 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
752 ? VideoContentType::SCREENSHARE
753 : VideoContentType::UNSPECIFIED;
754 encoded_image_._encodedHeight =
755 pkt->data.frame.height[layer_id.spatial_layer_id];
756 encoded_image_._encodedWidth =
757 pkt->data.frame.width[layer_id.spatial_layer_id];
758 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
759 int qp = -1;
760 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
761 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700762
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000763 return WEBRTC_VIDEO_CODEC_OK;
764}
765
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200766void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200767 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200768 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200769
770 // No data partitioning in VP9, so 1 partition only.
771 int part_idx = 0;
772 RTPFragmentationHeader frag_info;
773 frag_info.VerifyAndAllocateFragmentationHeader(1);
774 frag_info.fragmentationOffset[part_idx] = 0;
775 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
776 frag_info.fragmentationPlType[part_idx] = 0;
777 frag_info.fragmentationTimeDiff[part_idx] = 0;
778
779 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
780 &frag_info);
781 encoded_image_._length = 0;
782 }
783}
784
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000785int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000786 return WEBRTC_VIDEO_CODEC_OK;
787}
788
789int VP9EncoderImpl::RegisterEncodeCompleteCallback(
790 EncodedImageCallback* callback) {
791 encoded_complete_callback_ = callback;
792 return WEBRTC_VIDEO_CODEC_OK;
793}
794
Peter Boströmb7d9a972015-12-18 16:01:11 +0100795const char* VP9EncoderImpl::ImplementationName() const {
796 return "libvpx";
797}
798
Peter Boström12996152016-05-14 02:03:18 +0200799bool VP9Decoder::IsSupported() {
800 return true;
801}
802
Magnus Jedvert46a27652017-11-13 14:10:02 +0100803std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
804 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000805}
806
807VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700808 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000809 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700810 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +0200811 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000812
813VP9DecoderImpl::~VP9DecoderImpl() {
814 inited_ = true; // in order to do the actual release
815 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200816 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
817 if (num_buffers_in_use > 0) {
818 // The frame buffers are reference counted and frames are exposed after
819 // decoding. There may be valid usage cases where previous frames are still
820 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100821 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
822 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200823 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000824}
825
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000826int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000827 int ret_val = Release();
828 if (ret_val < 0) {
829 return ret_val;
830 }
sprang3958ed82017-08-17 08:12:10 -0700831 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000832 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000833 }
philipelcce46fc2015-12-21 03:04:49 -0800834 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000835 // Setting number of threads to a constant value (1)
836 cfg.threads = 1;
837 cfg.h = cfg.w = 0; // set after decode
838 vpx_codec_flags_t flags = 0;
839 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
840 return WEBRTC_VIDEO_CODEC_MEMORY;
841 }
Henrik Boström9695d852015-05-06 10:42:15 +0200842
843 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
844 return WEBRTC_VIDEO_CODEC_MEMORY;
845 }
846
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000847 inited_ = true;
848 // Always start with a complete key frame.
849 key_frame_required_ = true;
850 return WEBRTC_VIDEO_CODEC_OK;
851}
852
853int VP9DecoderImpl::Decode(const EncodedImage& input_image,
854 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000855 const CodecSpecificInfo* codec_specific_info,
856 int64_t /*render_time_ms*/) {
857 if (!inited_) {
858 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
859 }
sprang3958ed82017-08-17 08:12:10 -0700860 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000861 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
862 }
863 // Always start with a complete key frame.
864 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200865 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000866 return WEBRTC_VIDEO_CODEC_ERROR;
867 // We have a key frame - is it complete?
868 if (input_image._completeFrame) {
869 key_frame_required_ = false;
870 } else {
871 return WEBRTC_VIDEO_CODEC_ERROR;
872 }
873 }
sprang3958ed82017-08-17 08:12:10 -0700874 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000875 vpx_image_t* img;
876 uint8_t* buffer = input_image._buffer;
877 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700878 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000879 }
Henrik Boström9695d852015-05-06 10:42:15 +0200880 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
881 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800882 if (vpx_codec_decode(decoder_, buffer,
883 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000884 VPX_DL_REALTIME)) {
885 return WEBRTC_VIDEO_CODEC_ERROR;
886 }
Henrik Boström9695d852015-05-06 10:42:15 +0200887 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
888 // It may be released by libvpx during future vpx_codec_decode or
889 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000890 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800891 int qp;
892 vpx_codec_err_t vpx_ret =
893 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
894 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
895 int ret =
896 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000897 if (ret != 0) {
898 return ret;
899 }
900 return WEBRTC_VIDEO_CODEC_OK;
901}
902
asapersson1490f7a2016-09-23 02:09:46 -0700903int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
904 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800905 int64_t ntp_time_ms,
906 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700907 if (img == nullptr) {
908 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000909 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
910 }
Henrik Boström9695d852015-05-06 10:42:15 +0200911
912 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800913 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200914 // vpx_codec_decode calls or vpx_codec_destroy).
915 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
916 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700917 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200918 // using a WrappedI420Buffer.
919 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
920 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800921 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
922 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
923 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
924 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200925 // WrappedI420Buffer's mechanism for allowing the release of its frame
926 // buffer is through a callback function. This is where we should
927 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800928 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200929
nisseca6d5d12016-06-17 05:03:04 -0700930 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
931 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -0700932 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -0700933
Oskar Sundbom6bd39022017-11-16 10:54:49 +0100934 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000935 return WEBRTC_VIDEO_CODEC_OK;
936}
937
938int VP9DecoderImpl::RegisterDecodeCompleteCallback(
939 DecodedImageCallback* callback) {
940 decode_complete_callback_ = callback;
941 return WEBRTC_VIDEO_CODEC_OK;
942}
943
944int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100945 int ret_val = WEBRTC_VIDEO_CODEC_OK;
946
sprang3958ed82017-08-17 08:12:10 -0700947 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100948 if (inited_) {
949 // When a codec is destroyed libvpx will release any buffers of
950 // |frame_buffer_pool_| it is currently using.
951 if (vpx_codec_destroy(decoder_)) {
952 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
953 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000954 }
955 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -0700956 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000957 }
Henrik Boström9695d852015-05-06 10:42:15 +0200958 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
959 // still referenced externally are deleted once fully released, not returning
960 // to the pool.
961 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000962 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100963 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000964}
Peter Boströmb7d9a972015-12-18 16:01:11 +0100965
966const char* VP9DecoderImpl::ImplementationName() const {
967 return "libvpx";
968}
969
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000970} // namespace webrtc