blob: 9d1752e11d5c85a8fa61806c7976405b0f49e252 [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"
26#include "modules/video_coding/codecs/vp9/screenshare_layers.h"
Sergey Silkin86684962018-03-28 19:32:37 +020027#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
29#include "rtc_base/keep_ref_until_done.h"
30#include "rtc_base/logging.h"
Magnus Jedvert46a27652017-11-13 14:10:02 +010031#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020032#include "rtc_base/timeutils.h"
33#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000034
35namespace webrtc {
36
Marco6e89b252015-07-07 14:40:38 -070037// Only positive speeds, range for real-time coding currently is: 5 - 8.
38// Lower means slower/better quality, higher means fastest/lower quality.
39int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070040#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080041 return 8;
42#else
Marco6e89b252015-07-07 14:40:38 -070043 // For smaller resolutions, use lower speed setting (get some coding gain at
44 // the cost of increased encoding complexity).
45 if (width * height <= 352 * 288)
46 return 5;
47 else
48 return 7;
Marco002f0d02015-12-17 09:49:31 -080049#endif
Marco6e89b252015-07-07 14:40:38 -070050}
51
Peter Boström12996152016-05-14 02:03:18 +020052bool VP9Encoder::IsSupported() {
53 return true;
54}
55
Magnus Jedvert46a27652017-11-13 14:10:02 +010056std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
57 return rtc::MakeUnique<VP9EncoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000058}
59
asaperssona9455ab2015-07-31 06:10:09 -070060void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
61 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080062 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070063 enc->GetEncodedLayerFrame(pkt);
64}
65
marpan@webrtc.org5b883172014-11-01 06:10:48 +000066VP9EncoderImpl::VP9EncoderImpl()
67 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070068 encoded_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000069 inited_(false),
70 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000071 cpu_speed_(3),
72 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -070073 encoder_(nullptr),
74 config_(nullptr),
75 raw_(nullptr),
76 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +020077 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020078 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -070079 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080080 num_spatial_layers_(0),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020081 inter_layer_pred_(InterLayerPredMode::kOn),
Erik Språng08127a92016-11-16 16:41:30 +010082 is_flexible_mode_(false),
philipelcfc319b2015-11-10 07:17:23 -080083 frames_encoded_(0),
84 // Use two spatial when screensharing with flexible mode.
85 spatial_layer_(new ScreenshareLayersVP9(2)) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000086 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080087 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +000088}
89
90VP9EncoderImpl::~VP9EncoderImpl() {
91 Release();
92}
93
94int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010095 int ret_val = WEBRTC_VIDEO_CODEC_OK;
96
sprang3958ed82017-08-17 08:12:10 -070097 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080098 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070099 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000100 }
sprang3958ed82017-08-17 08:12:10 -0700101 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100102 if (inited_) {
103 if (vpx_codec_destroy(encoder_)) {
104 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
105 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000106 }
107 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700108 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000109 }
sprang3958ed82017-08-17 08:12:10 -0700110 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000111 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700112 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 }
sprang3958ed82017-08-17 08:12:10 -0700114 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000115 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700116 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000117 }
118 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100119 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000120}
121
sprangce4aef12015-11-02 07:23:20 -0800122bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
123 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
124 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100125 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800126}
127
Erik Språng566124a2018-04-23 12:32:22 +0200128bool VP9EncoderImpl::SetSvcRates(
129 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700130 uint8_t i = 0;
131
Sergey Silkin86684962018-03-28 19:32:37 +0200132 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
133 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
134
sprangce4aef12015-11-02 07:23:20 -0800135 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200136 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200137 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200138 config_->ss_target_bitrate[sl_idx] =
139 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
140
141 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
142 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
143 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
144 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200145
146 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
147 if (is_layer_enabled && !was_layer_enabled) {
148 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
149 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
150 // TODO(wemb:1526): remove key frame request when issue is fixed.
151 force_key_frame_ = true;
152 }
153 }
sprangce4aef12015-11-02 07:23:20 -0800154 }
155 } else {
156 float rate_ratio[VPX_MAX_LAYERS] = {0};
157 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700158
sprangce4aef12015-11-02 07:23:20 -0800159 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800160 if (svc_params_.scaling_factor_num[i] <= 0 ||
161 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100162 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800163 return false;
164 }
165 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800166 static_cast<float>(svc_params_.scaling_factor_num[i]) /
167 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800168 total += rate_ratio[i];
169 }
170
171 for (i = 0; i < num_spatial_layers_; ++i) {
172 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
173 config_->rc_target_bitrate * rate_ratio[i] / total);
174 if (num_temporal_layers_ == 1) {
175 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
176 } else if (num_temporal_layers_ == 2) {
177 config_->layer_target_bitrate[i * num_temporal_layers_] =
178 config_->ss_target_bitrate[i] * 2 / 3;
179 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
180 config_->ss_target_bitrate[i];
181 } else if (num_temporal_layers_ == 3) {
182 config_->layer_target_bitrate[i * num_temporal_layers_] =
183 config_->ss_target_bitrate[i] / 2;
184 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
185 config_->layer_target_bitrate[i * num_temporal_layers_] +
186 (config_->ss_target_bitrate[i] / 4);
187 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
188 config_->ss_target_bitrate[i];
189 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100190 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
191 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800192 return false;
193 }
asaperssona9455ab2015-07-31 06:10:09 -0700194 }
195 }
196
197 // For now, temporal layers only supported when having one spatial layer.
198 if (num_spatial_layers_ == 1) {
199 for (i = 0; i < num_temporal_layers_; ++i) {
200 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
201 }
202 }
203
204 return true;
205}
206
Erik Språng08127a92016-11-16 16:41:30 +0100207int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200208 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100209 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000210 if (!inited_) {
211 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
212 }
213 if (encoder_->err) {
214 return WEBRTC_VIDEO_CODEC_ERROR;
215 }
Erik Språng08127a92016-11-16 16:41:30 +0100216 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000217 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
218 }
219 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100220 if (codec_.maxBitrate > 0 &&
221 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
222 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000223 }
Erik Språng08127a92016-11-16 16:41:30 +0100224
Erik Språng08127a92016-11-16 16:41:30 +0100225 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700226
Sergey Silkin86684962018-03-28 19:32:37 +0200227 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700228 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
229 }
230
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000231 // Update encoder context
232 if (vpx_codec_enc_config_set(encoder_, config_)) {
233 return WEBRTC_VIDEO_CODEC_ERROR;
234 }
235 return WEBRTC_VIDEO_CODEC_OK;
236}
237
238int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
239 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000240 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700241 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000242 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
243 }
244 if (inst->maxFramerate < 1) {
245 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
246 }
247 // Allow zero to represent an unspecified maxBitRate
248 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
249 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
250 }
251 if (inst->width < 1 || inst->height < 1) {
252 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
253 }
254 if (number_of_cores < 1) {
255 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
256 }
hta257dc392016-10-25 09:05:06 -0700257 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700258 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
259 }
ilnik2a8c2f52017-02-15 02:23:28 -0800260 // libvpx probably does not support more than 3 spatial layers.
261 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700262 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
263 }
philipelcfc319b2015-11-10 07:17:23 -0800264
asapersson86956de2016-01-26 01:05:20 -0800265 int ret_val = Release();
266 if (ret_val < 0) {
267 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000268 }
sprang3958ed82017-08-17 08:12:10 -0700269 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000270 encoder_ = new vpx_codec_ctx_t;
271 }
sprang3958ed82017-08-17 08:12:10 -0700272 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000273 config_ = new vpx_codec_enc_cfg_t;
274 }
275 timestamp_ = 0;
276 if (&codec_ != inst) {
277 codec_ = *inst;
278 }
asaperssona9455ab2015-07-31 06:10:09 -0700279
hta257dc392016-10-25 09:05:06 -0700280 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200281 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700282 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700283 if (num_temporal_layers_ == 0)
284 num_temporal_layers_ = 1;
285
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000286 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700287 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800288 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000289 }
nisseeb44b392017-04-28 07:18:05 -0700290 encoded_image_._size =
291 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000292 encoded_image_._buffer = new uint8_t[encoded_image_._size];
293 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700294 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000295 // pointer will be set in encode. Setting align to 1, as it is meaningless
296 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700297 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
298 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000299 // Populate encoder configuration with default values.
300 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
301 return WEBRTC_VIDEO_CODEC_ERROR;
302 }
303 config_->g_w = codec_.width;
304 config_->g_h = codec_.height;
305 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Niels Möller65fb4042018-04-25 14:46:06 +0200306 config_->g_error_resilient =
307 (num_spatial_layers_ > 1 || num_temporal_layers_ > 1) ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000308 // Setting the time base of the codec.
309 config_->g_timebase.num = 1;
310 config_->g_timebase.den = 90000;
311 config_->g_lag_in_frames = 0; // 0- no frame lagging
312 config_->g_threads = 1;
313 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700314 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000315 config_->rc_end_usage = VPX_CBR;
316 config_->g_pass = VPX_RC_ONE_PASS;
317 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000318 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000319 config_->rc_undershoot_pct = 50;
320 config_->rc_overshoot_pct = 50;
321 config_->rc_buf_initial_sz = 500;
322 config_->rc_buf_optimal_sz = 600;
323 config_->rc_buf_sz = 1000;
324 // Set the maximum target size of any key-frame.
325 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700326 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000327 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700328 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100329 // Needs to be set (in svc mode) to get correct periodic key frame interval
330 // (will have no effect in non-svc).
331 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000332 } else {
333 config_->kf_mode = VPX_KF_DISABLED;
334 }
hta257dc392016-10-25 09:05:06 -0700335 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000336 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800337 config_->g_threads =
338 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700339
Marco6e89b252015-07-07 14:40:38 -0700340 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700341
342 // TODO(asapersson): Check configuration of temporal switch up and increase
343 // pattern length.
hta257dc392016-10-25 09:05:06 -0700344 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800345 if (is_flexible_mode_) {
346 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
347 config_->ts_number_layers = num_temporal_layers_;
348 if (codec_.mode == kScreensharing)
349 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
350 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700351 gof_.SetGofInfoVP9(kTemporalStructureMode1);
352 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
353 config_->ts_number_layers = 1;
354 config_->ts_rate_decimator[0] = 1;
355 config_->ts_periodicity = 1;
356 config_->ts_layer_id[0] = 0;
357 } else if (num_temporal_layers_ == 2) {
358 gof_.SetGofInfoVP9(kTemporalStructureMode2);
359 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
360 config_->ts_number_layers = 2;
361 config_->ts_rate_decimator[0] = 2;
362 config_->ts_rate_decimator[1] = 1;
363 config_->ts_periodicity = 2;
364 config_->ts_layer_id[0] = 0;
365 config_->ts_layer_id[1] = 1;
366 } else if (num_temporal_layers_ == 3) {
367 gof_.SetGofInfoVP9(kTemporalStructureMode3);
368 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
369 config_->ts_number_layers = 3;
370 config_->ts_rate_decimator[0] = 4;
371 config_->ts_rate_decimator[1] = 2;
372 config_->ts_rate_decimator[2] = 1;
373 config_->ts_periodicity = 4;
374 config_->ts_layer_id[0] = 0;
375 config_->ts_layer_id[1] = 2;
376 config_->ts_layer_id[2] = 1;
377 config_->ts_layer_id[3] = 2;
378 } else {
379 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
380 }
381
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200382 inter_layer_pred_ = inst->VP9().interLayerPred;
383
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000384 return InitAndSetControlSettings(inst);
385}
386
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000387int VP9EncoderImpl::NumberOfThreads(int width,
388 int height,
389 int number_of_cores) {
390 // Keep the number of encoder threads equal to the possible number of column
391 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
392 if (width * height >= 1280 * 720 && number_of_cores > 4) {
393 return 4;
jianj23173a32017-07-12 16:11:09 -0700394 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000395 return 2;
396 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800397 // Use 2 threads for low res on ARM.
398#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
399 defined(WEBRTC_ANDROID)
400 if (width * height >= 320 * 180 && number_of_cores > 2) {
401 return 2;
402 }
403#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000404 // 1 thread less than VGA.
405 return 1;
406 }
407}
408
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000409int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100410 // Set QP-min/max per spatial and temporal layer.
411 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
412 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800413 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
414 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100415 }
asaperssona9455ab2015-07-31 06:10:09 -0700416 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800417 if (ExplicitlyConfiguredSpatialLayers()) {
418 for (int i = 0; i < num_spatial_layers_; ++i) {
419 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100420 const int scale_factor = codec_.width / layer.width;
421 RTC_DCHECK_GT(scale_factor, 0);
422
423 // Ensure scaler factor is integer.
424 if (scale_factor * layer.width != codec_.width) {
425 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
426 }
427
428 // Ensure scale factor is the same in both dimensions.
429 if (scale_factor * layer.height != codec_.height) {
430 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
431 }
432
433 // Ensure scale factor is power of two.
434 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
435 if (!is_pow_of_two) {
436 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
437 }
438
439 svc_params_.scaling_factor_num[i] = 1;
440 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800441 }
442 } else {
443 int scaling_factor_num = 256;
444 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800445 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800446 svc_params_.scaling_factor_num[i] = scaling_factor_num;
447 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800448 if (codec_.mode != kScreensharing)
449 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800450 }
asaperssona9455ab2015-07-31 06:10:09 -0700451 }
452
Sergey Silkin86684962018-03-28 19:32:37 +0200453 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200454 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200455 inst->startBitrate * 1000, inst->maxFramerate);
456 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700457 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
458 }
459
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000460 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
461 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
462 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000463 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
464 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
465 rc_max_intra_target_);
466 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700467 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700468
jianj822e5932017-07-12 16:09:58 -0700469 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700470 vpx_codec_control(
471 encoder_, VP9E_SET_SVC,
472 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200473
asaperssona9455ab2015-07-31 06:10:09 -0700474 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
475 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800476 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700477 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200478
479 if (num_spatial_layers_ > 1) {
480 switch (inter_layer_pred_) {
481 case InterLayerPredMode::kOn:
482 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
483 break;
484 case InterLayerPredMode::kOff:
485 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
486 break;
487 case InterLayerPredMode::kOnKeyPic:
488 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
489 break;
490 default:
491 RTC_NOTREACHED();
492 }
493 }
494
asaperssona9455ab2015-07-31 06:10:09 -0700495 // Register callback for getting each spatial layer.
496 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800497 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
498 reinterpret_cast<void*>(this)};
499 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
500 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700501
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000502 // Control function to set the number of column tiles in encoding a frame, in
503 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
504 // The number tile columns will be capped by the encoder based on image size
505 // (minimum width of tile column is 256 pixels, maximum is 4096).
506 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700507
508 // Turn on row-based multithreading.
509 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700510
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700511#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
512 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700513 // Do not enable the denoiser on ARM since optimization is pending.
514 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000515 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700516 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000517#endif
jianj6bf57e32017-06-05 13:43:49 -0700518
ivica242d6382015-09-04 06:13:23 -0700519 if (codec_.mode == kScreensharing) {
520 // Adjust internal parameters to screen content.
521 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700522 }
Marco2520e722015-09-16 14:05:00 -0700523 // Enable encoder skip of static/low content blocks.
524 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000525 inited_ = true;
526 return WEBRTC_VIDEO_CODEC_OK;
527}
528
529uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
530 // Set max to the optimal buffer level (normalized by target BR),
531 // and scaled by a scale_par.
532 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
533 // This value is presented in percentage of perFrameBw:
534 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
535 // The target in % is as follows:
536 float scale_par = 0.5;
537 uint32_t target_pct =
538 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
539 // Don't go below 3 times the per frame bandwidth.
540 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800541 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000542}
543
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700544int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000545 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700546 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000547 if (!inited_) {
548 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
549 }
sprang3958ed82017-08-17 08:12:10 -0700550 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000551 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
552 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200553
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000554 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200555 if (frame_types && !frame_types->empty()) {
556 if ((*frame_types)[0] == kVideoFrameKey) {
557 force_key_frame_ = true;
558 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000559 }
kwiberg352444f2016-11-28 15:58:53 -0800560 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
561 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700562
563 // Set input image for use in the callback.
564 // This was necessary since you need some information from input_image.
565 // You can save only the necessary information (such as timestamp) instead of
566 // doing this.
567 input_image_ = &input_image;
568
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000569 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
570 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000571 // Image in vpx_image_t format.
572 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000573 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
574 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
575 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
576 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
577 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
578 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000579
philipelcfc319b2015-11-10 07:17:23 -0800580 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200581 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000582 flags = VPX_EFLAG_FORCE_KF;
583 }
philipelcfc319b2015-11-10 07:17:23 -0800584
585 if (is_flexible_mode_) {
586 SuperFrameRefSettings settings;
587
588 // These structs are copied when calling vpx_codec_control,
589 // therefore it is ok for them to go out of scope.
590 vpx_svc_ref_frame_config enc_layer_conf;
591 vpx_svc_layer_id layer_id;
592
593 if (codec_.mode == kRealtimeVideo) {
594 // Real time video not yet implemented in flexible mode.
595 RTC_NOTREACHED();
596 } else {
597 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200598 force_key_frame_);
philipelcfc319b2015-11-10 07:17:23 -0800599 }
600 enc_layer_conf = GenerateRefsAndFlags(settings);
601 layer_id.temporal_layer_id = 0;
602 layer_id.spatial_layer_id = settings.start_layer;
603 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
604 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
605 }
606
sprang3958ed82017-08-17 08:12:10 -0700607 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000608 uint32_t duration = 90000 / codec_.maxFramerate;
609 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
610 VPX_DL_REALTIME)) {
611 return WEBRTC_VIDEO_CODEC_ERROR;
612 }
613 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700614
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200615 const bool end_of_picture = true;
616 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200617
asaperssona9455ab2015-07-31 06:10:09 -0700618 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000619}
620
621void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800622 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200623 uint32_t timestamp,
624 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700625 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000626 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700627 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800628 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200629
630 vp9_info->first_frame_in_picture = first_frame_in_picture;
Åsa Perssonff24c042015-12-04 10:58:08 +0100631 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700632 vp9_info->inter_pic_predicted =
633 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700634 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
635 vp9_info->ss_data_available =
636 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
637 ? true
638 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700639
640 vpx_svc_layer_id_t layer_id = {0};
641 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
642
sprang3958ed82017-08-17 08:12:10 -0700643 RTC_CHECK_GT(num_temporal_layers_, 0);
644 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700645 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700646 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700647 vp9_info->temporal_idx = kNoTemporalIdx;
648 } else {
649 vp9_info->temporal_idx = layer_id.temporal_layer_id;
650 }
651 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700652 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700653 vp9_info->spatial_idx = kNoSpatialIdx;
654 } else {
655 vp9_info->spatial_idx = layer_id.spatial_layer_id;
656 }
657 if (layer_id.spatial_layer_id != 0) {
658 vp9_info->ss_data_available = false;
659 }
660
asaperssona9455ab2015-07-31 06:10:09 -0700661 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800662 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700663
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200664 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
665 pics_since_key_ = 0;
666 } else if (first_frame_in_picture) {
667 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700668 }
669
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200670 const bool is_key_pic = (pics_since_key_ == 0);
671 const bool is_inter_layer_pred_allowed =
672 (inter_layer_pred_ == InterLayerPredMode::kOn ||
673 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
674
675 // Always set inter_layer_predicted to true on high layer frame if inter-layer
676 // prediction (ILP) is allowed even if encoder didn't actually use it.
677 // Setting inter_layer_predicted to false would allow receiver to decode high
678 // layer frame without decoding low layer frame. If that would happen (e.g.
679 // if low layer frame is lost) then receiver won't be able to decode next high
680 // layer frame which uses ILP.
681 vp9_info->inter_layer_predicted =
682 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
683
684 const bool is_last_layer =
685 (layer_id.spatial_layer_id + 1 == num_spatial_layers_);
686 vp9_info->non_ref_for_inter_layer_pred =
687 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800688
ivica7f6a6fc2015-09-08 02:40:29 -0700689 // Always populate this, so that the packetizer can properly set the marker
690 // bit.
691 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800692
693 vp9_info->num_ref_pics = 0;
694 if (vp9_info->flexible_mode) {
695 vp9_info->gof_idx = kNoGofIdx;
696 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
697 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
698 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
699 }
700 } else {
701 vp9_info->gof_idx =
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200702 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800703 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800704 }
philipelcfc319b2015-11-10 07:17:23 -0800705
asaperssona9455ab2015-07-31 06:10:09 -0700706 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700707 vp9_info->spatial_layer_resolution_present = true;
708 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
709 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800710 svc_params_.scaling_factor_num[i] /
711 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700712 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800713 svc_params_.scaling_factor_num[i] /
714 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700715 }
716 if (!vp9_info->flexible_mode) {
717 vp9_info->gof.CopyGofInfoVP9(gof_);
718 }
719 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000720}
721
asaperssona9455ab2015-07-31 06:10:09 -0700722int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800723 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700724
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200725 if (pkt->data.frame.sz == 0) {
726 // Ignore dropped frame.
727 return WEBRTC_VIDEO_CODEC_OK;
728 }
729
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200730 vpx_svc_layer_id_t layer_id = {0};
731 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
732
733 const bool first_frame_in_picture = encoded_image_._length == 0;
734 // Ensure we don't buffer layers of previous picture (superframe).
735 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
736
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200737 const bool end_of_picture = false;
738 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200739
asaperssond9f641e2016-01-21 01:11:35 -0800740 if (pkt->data.frame.sz > encoded_image_._size) {
741 delete[] encoded_image_._buffer;
742 encoded_image_._size = pkt->data.frame.sz;
743 encoded_image_._buffer = new uint8_t[encoded_image_._size];
744 }
asapersson86956de2016-01-26 01:05:20 -0800745 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
746 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800747
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200748 if (is_flexible_mode_ && codec_.mode == kScreensharing) {
philipelcfc319b2015-11-10 07:17:23 -0800749 spatial_layer_->LayerFrameEncoded(
750 static_cast<unsigned int>(encoded_image_._length),
751 layer_id.spatial_layer_id);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200752 }
philipelcfc319b2015-11-10 07:17:23 -0800753
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200754 const bool is_key_frame =
755 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
756 // Ensure encoder issued key frame on request.
757 RTC_DCHECK(is_key_frame || !force_key_frame_);
758
asaperssona9455ab2015-07-31 06:10:09 -0700759 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800760 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200761 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200762 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200763 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000764 }
asapersson86956de2016-01-26 01:05:20 -0800765 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
766
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200767 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200768 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
769 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700770
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200771 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
772 encoded_image_._timeStamp = input_image_->timestamp();
773 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
774 encoded_image_.rotation_ = input_image_->rotation();
775 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
776 ? VideoContentType::SCREENSHARE
777 : VideoContentType::UNSPECIFIED;
778 encoded_image_._encodedHeight =
779 pkt->data.frame.height[layer_id.spatial_layer_id];
780 encoded_image_._encodedWidth =
781 pkt->data.frame.width[layer_id.spatial_layer_id];
782 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
783 int qp = -1;
784 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
785 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700786
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000787 return WEBRTC_VIDEO_CODEC_OK;
788}
789
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200790void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200791 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200792 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200793
794 // No data partitioning in VP9, so 1 partition only.
795 int part_idx = 0;
796 RTPFragmentationHeader frag_info;
797 frag_info.VerifyAndAllocateFragmentationHeader(1);
798 frag_info.fragmentationOffset[part_idx] = 0;
799 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
800 frag_info.fragmentationPlType[part_idx] = 0;
801 frag_info.fragmentationTimeDiff[part_idx] = 0;
802
803 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
804 &frag_info);
805 encoded_image_._length = 0;
806 }
807}
808
philipelcfc319b2015-11-10 07:17:23 -0800809vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
810 const SuperFrameRefSettings& settings) {
811 static const vpx_enc_frame_flags_t kAllFlags =
812 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
813 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
814 vpx_svc_ref_frame_config sf_conf = {};
815 if (settings.is_keyframe) {
816 // Used later on to make sure we don't make any invalid references.
817 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
818 for (int layer = settings.start_layer; layer <= settings.stop_layer;
819 ++layer) {
820 num_ref_pics_[layer] = 0;
821 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
822 // When encoding a keyframe only the alt_fb_idx is used
823 // to specify which layer ends up in which buffer.
824 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
825 }
826 } else {
827 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
828 ++layer_idx) {
829 vpx_enc_frame_flags_t layer_flags = kAllFlags;
830 num_ref_pics_[layer_idx] = 0;
831 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
832 settings.layer[layer_idx].ref_buf2,
833 settings.layer[layer_idx].ref_buf3};
834
835 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
836 if (refs[ref_idx] == -1)
837 continue;
838
839 RTC_DCHECK_GE(refs[ref_idx], 0);
840 RTC_DCHECK_LE(refs[ref_idx], 7);
841 // Easier to remove flags from all flags rather than having to
842 // build the flags from 0.
843 switch (num_ref_pics_[layer_idx]) {
844 case 0: {
845 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
846 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
847 break;
848 }
849 case 1: {
850 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
851 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
852 break;
853 }
854 case 2: {
855 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
856 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
857 break;
858 }
859 }
860 // Make sure we don't reference a buffer that hasn't been
861 // used at all or hasn't been used since a keyframe.
862 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
863
864 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
865 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
866 num_ref_pics_[layer_idx]++;
867 }
868
869 bool upd_buf_same_as_a_ref = false;
870 if (settings.layer[layer_idx].upd_buf != -1) {
871 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
872 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
873 switch (ref_idx) {
874 case 0: {
875 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
876 break;
877 }
878 case 1: {
879 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
880 break;
881 }
882 case 2: {
883 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
884 break;
885 }
886 }
887 upd_buf_same_as_a_ref = true;
888 break;
889 }
890 }
891 if (!upd_buf_same_as_a_ref) {
892 // If we have three references and a buffer is specified to be
893 // updated, then that buffer must be the same as one of the
894 // three references.
895 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
896
897 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
898 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
899 }
900
901 int updated_buffer = settings.layer[layer_idx].upd_buf;
902 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
903 sf_conf.frame_flags[layer_idx] = layer_flags;
904 }
905 }
906 }
907 ++frames_encoded_;
908 return sf_conf;
909}
910
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000911int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000912 return WEBRTC_VIDEO_CODEC_OK;
913}
914
915int VP9EncoderImpl::RegisterEncodeCompleteCallback(
916 EncodedImageCallback* callback) {
917 encoded_complete_callback_ = callback;
918 return WEBRTC_VIDEO_CODEC_OK;
919}
920
Peter Boströmb7d9a972015-12-18 16:01:11 +0100921const char* VP9EncoderImpl::ImplementationName() const {
922 return "libvpx";
923}
924
Peter Boström12996152016-05-14 02:03:18 +0200925bool VP9Decoder::IsSupported() {
926 return true;
927}
928
Magnus Jedvert46a27652017-11-13 14:10:02 +0100929std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
930 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000931}
932
933VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700934 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000935 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700936 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +0200937 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000938
939VP9DecoderImpl::~VP9DecoderImpl() {
940 inited_ = true; // in order to do the actual release
941 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200942 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
943 if (num_buffers_in_use > 0) {
944 // The frame buffers are reference counted and frames are exposed after
945 // decoding. There may be valid usage cases where previous frames are still
946 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100947 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
948 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200949 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000950}
951
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000952int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000953 int ret_val = Release();
954 if (ret_val < 0) {
955 return ret_val;
956 }
sprang3958ed82017-08-17 08:12:10 -0700957 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000958 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000959 }
philipelcce46fc2015-12-21 03:04:49 -0800960 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000961 // Setting number of threads to a constant value (1)
962 cfg.threads = 1;
963 cfg.h = cfg.w = 0; // set after decode
964 vpx_codec_flags_t flags = 0;
965 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
966 return WEBRTC_VIDEO_CODEC_MEMORY;
967 }
Henrik Boström9695d852015-05-06 10:42:15 +0200968
969 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
970 return WEBRTC_VIDEO_CODEC_MEMORY;
971 }
972
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000973 inited_ = true;
974 // Always start with a complete key frame.
975 key_frame_required_ = true;
976 return WEBRTC_VIDEO_CODEC_OK;
977}
978
979int VP9DecoderImpl::Decode(const EncodedImage& input_image,
980 bool missing_frames,
981 const RTPFragmentationHeader* fragmentation,
982 const CodecSpecificInfo* codec_specific_info,
983 int64_t /*render_time_ms*/) {
984 if (!inited_) {
985 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
986 }
sprang3958ed82017-08-17 08:12:10 -0700987 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000988 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
989 }
990 // Always start with a complete key frame.
991 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200992 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000993 return WEBRTC_VIDEO_CODEC_ERROR;
994 // We have a key frame - is it complete?
995 if (input_image._completeFrame) {
996 key_frame_required_ = false;
997 } else {
998 return WEBRTC_VIDEO_CODEC_ERROR;
999 }
1000 }
sprang3958ed82017-08-17 08:12:10 -07001001 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001002 vpx_image_t* img;
1003 uint8_t* buffer = input_image._buffer;
1004 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001005 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001006 }
Henrik Boström9695d852015-05-06 10:42:15 +02001007 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1008 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001009 if (vpx_codec_decode(decoder_, buffer,
1010 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001011 VPX_DL_REALTIME)) {
1012 return WEBRTC_VIDEO_CODEC_ERROR;
1013 }
Henrik Boström9695d852015-05-06 10:42:15 +02001014 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1015 // It may be released by libvpx during future vpx_codec_decode or
1016 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001017 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001018 int qp;
1019 vpx_codec_err_t vpx_ret =
1020 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1021 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1022 int ret =
1023 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001024 if (ret != 0) {
1025 return ret;
1026 }
1027 return WEBRTC_VIDEO_CODEC_OK;
1028}
1029
asapersson1490f7a2016-09-23 02:09:46 -07001030int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1031 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001032 int64_t ntp_time_ms,
1033 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001034 if (img == nullptr) {
1035 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001036 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1037 }
Henrik Boström9695d852015-05-06 10:42:15 +02001038
1039 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001040 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001041 // vpx_codec_decode calls or vpx_codec_destroy).
1042 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1043 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001044 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +02001045 // using a WrappedI420Buffer.
1046 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
1047 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -08001048 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1049 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1050 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1051 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001052 // WrappedI420Buffer's mechanism for allowing the release of its frame
1053 // buffer is through a callback function. This is where we should
1054 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -08001055 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +02001056
nisseca6d5d12016-06-17 05:03:04 -07001057 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1058 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001059 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001060
Oskar Sundbom6bd39022017-11-16 10:54:49 +01001061 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001062 return WEBRTC_VIDEO_CODEC_OK;
1063}
1064
1065int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1066 DecodedImageCallback* callback) {
1067 decode_complete_callback_ = callback;
1068 return WEBRTC_VIDEO_CODEC_OK;
1069}
1070
1071int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001072 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1073
sprang3958ed82017-08-17 08:12:10 -07001074 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001075 if (inited_) {
1076 // When a codec is destroyed libvpx will release any buffers of
1077 // |frame_buffer_pool_| it is currently using.
1078 if (vpx_codec_destroy(decoder_)) {
1079 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1080 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001081 }
1082 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001083 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001084 }
Henrik Boström9695d852015-05-06 10:42:15 +02001085 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1086 // still referenced externally are deleted once fully released, not returning
1087 // to the pool.
1088 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001089 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001090 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001091}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001092
1093const char* VP9DecoderImpl::ImplementationName() const {
1094 return "libvpx";
1095}
1096
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001097} // namespace webrtc