blob: 4c4981d8449ffe987934e0814613c502c55edfed [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"
27#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),
philipelcfc319b2015-11-10 07:17:23 -080076 frames_since_kf_(0),
asaperssona9455ab2015-07-31 06:10:09 -070077 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080078 num_spatial_layers_(0),
Erik Språng08127a92016-11-16 16:41:30 +010079 is_flexible_mode_(false),
philipelcfc319b2015-11-10 07:17:23 -080080 frames_encoded_(0),
81 // Use two spatial when screensharing with flexible mode.
82 spatial_layer_(new ScreenshareLayersVP9(2)) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000083 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080084 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +000085}
86
87VP9EncoderImpl::~VP9EncoderImpl() {
88 Release();
89}
90
91int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010092 int ret_val = WEBRTC_VIDEO_CODEC_OK;
93
sprang3958ed82017-08-17 08:12:10 -070094 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080095 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070096 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +000097 }
sprang3958ed82017-08-17 08:12:10 -070098 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +010099 if (inited_) {
100 if (vpx_codec_destroy(encoder_)) {
101 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
102 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000103 }
104 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700105 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000106 }
sprang3958ed82017-08-17 08:12:10 -0700107 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000108 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700109 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000110 }
sprang3958ed82017-08-17 08:12:10 -0700111 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000112 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700113 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000114 }
115 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100116 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000117}
118
sprangce4aef12015-11-02 07:23:20 -0800119bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
120 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
121 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100122 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800123}
124
asaperssona9455ab2015-07-31 06:10:09 -0700125bool VP9EncoderImpl::SetSvcRates() {
asaperssona9455ab2015-07-31 06:10:09 -0700126 uint8_t i = 0;
127
sprangce4aef12015-11-02 07:23:20 -0800128 if (ExplicitlyConfiguredSpatialLayers()) {
129 if (num_temporal_layers_ > 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100130 RTC_LOG(LS_ERROR) << "Multiple temporal layers when manually specifying "
131 "spatial layers not implemented yet!";
asaperssona9455ab2015-07-31 06:10:09 -0700132 return false;
133 }
sprangce4aef12015-11-02 07:23:20 -0800134 int total_bitrate_bps = 0;
135 for (i = 0; i < num_spatial_layers_; ++i)
Sergey Silkin13e74342018-03-02 12:28:00 +0100136 total_bitrate_bps += codec_.spatialLayers[i].targetBitrate * 1000;
sprangce4aef12015-11-02 07:23:20 -0800137 // If total bitrate differs now from what has been specified at the
138 // beginning, update the bitrates in the same ratio as before.
139 for (i = 0; i < num_spatial_layers_; ++i) {
140 config_->ss_target_bitrate[i] = config_->layer_target_bitrate[i] =
141 static_cast<int>(static_cast<int64_t>(config_->rc_target_bitrate) *
Sergey Silkin13e74342018-03-02 12:28:00 +0100142 codec_.spatialLayers[i].targetBitrate * 1000 /
sprangce4aef12015-11-02 07:23:20 -0800143 total_bitrate_bps);
144 }
145 } else {
146 float rate_ratio[VPX_MAX_LAYERS] = {0};
147 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700148
sprangce4aef12015-11-02 07:23:20 -0800149 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800150 if (svc_params_.scaling_factor_num[i] <= 0 ||
151 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100152 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800153 return false;
154 }
155 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800156 static_cast<float>(svc_params_.scaling_factor_num[i]) /
157 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800158 total += rate_ratio[i];
159 }
160
161 for (i = 0; i < num_spatial_layers_; ++i) {
162 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
163 config_->rc_target_bitrate * rate_ratio[i] / total);
164 if (num_temporal_layers_ == 1) {
165 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
166 } else if (num_temporal_layers_ == 2) {
167 config_->layer_target_bitrate[i * num_temporal_layers_] =
168 config_->ss_target_bitrate[i] * 2 / 3;
169 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
170 config_->ss_target_bitrate[i];
171 } else if (num_temporal_layers_ == 3) {
172 config_->layer_target_bitrate[i * num_temporal_layers_] =
173 config_->ss_target_bitrate[i] / 2;
174 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
175 config_->layer_target_bitrate[i * num_temporal_layers_] +
176 (config_->ss_target_bitrate[i] / 4);
177 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
178 config_->ss_target_bitrate[i];
179 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100180 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
181 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800182 return false;
183 }
asaperssona9455ab2015-07-31 06:10:09 -0700184 }
185 }
186
187 // For now, temporal layers only supported when having one spatial layer.
188 if (num_spatial_layers_ == 1) {
189 for (i = 0; i < num_temporal_layers_; ++i) {
190 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
191 }
192 }
193
194 return true;
195}
196
Erik Språng08127a92016-11-16 16:41:30 +0100197int VP9EncoderImpl::SetRateAllocation(
198 const BitrateAllocation& bitrate_allocation,
199 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000200 if (!inited_) {
201 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
202 }
203 if (encoder_->err) {
204 return WEBRTC_VIDEO_CODEC_ERROR;
205 }
Erik Språng08127a92016-11-16 16:41:30 +0100206 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000207 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
208 }
209 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100210 if (codec_.maxBitrate > 0 &&
211 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
212 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000213 }
Erik Språng08127a92016-11-16 16:41:30 +0100214
215 // TODO(sprang): Actually use BitrateAllocation layer info.
216 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
217 codec_.maxFramerate = frame_rate;
218 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
asaperssona9455ab2015-07-31 06:10:09 -0700219
220 if (!SetSvcRates()) {
221 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
222 }
223
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000224 // Update encoder context
225 if (vpx_codec_enc_config_set(encoder_, config_)) {
226 return WEBRTC_VIDEO_CODEC_ERROR;
227 }
228 return WEBRTC_VIDEO_CODEC_OK;
229}
230
231int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
232 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000233 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700234 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000235 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
236 }
237 if (inst->maxFramerate < 1) {
238 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
239 }
240 // Allow zero to represent an unspecified maxBitRate
241 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
242 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
243 }
244 if (inst->width < 1 || inst->height < 1) {
245 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
246 }
247 if (number_of_cores < 1) {
248 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
249 }
hta257dc392016-10-25 09:05:06 -0700250 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700251 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
252 }
ilnik2a8c2f52017-02-15 02:23:28 -0800253 // libvpx probably does not support more than 3 spatial layers.
254 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700255 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
256 }
philipelcfc319b2015-11-10 07:17:23 -0800257
asapersson86956de2016-01-26 01:05:20 -0800258 int ret_val = Release();
259 if (ret_val < 0) {
260 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000261 }
sprang3958ed82017-08-17 08:12:10 -0700262 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000263 encoder_ = new vpx_codec_ctx_t;
264 }
sprang3958ed82017-08-17 08:12:10 -0700265 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000266 config_ = new vpx_codec_enc_cfg_t;
267 }
268 timestamp_ = 0;
269 if (&codec_ != inst) {
270 codec_ = *inst;
271 }
asaperssona9455ab2015-07-31 06:10:09 -0700272
hta257dc392016-10-25 09:05:06 -0700273 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
274 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700275 if (num_temporal_layers_ == 0)
276 num_temporal_layers_ = 1;
277
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000278 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700279 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800280 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000281 }
nisseeb44b392017-04-28 07:18:05 -0700282 encoded_image_._size =
283 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000284 encoded_image_._buffer = new uint8_t[encoded_image_._size];
285 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700286 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000287 // pointer will be set in encode. Setting align to 1, as it is meaningless
288 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700289 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
290 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000291 // Populate encoder configuration with default values.
292 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
293 return WEBRTC_VIDEO_CODEC_ERROR;
294 }
295 config_->g_w = codec_.width;
296 config_->g_h = codec_.height;
297 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700298 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000299 // Setting the time base of the codec.
300 config_->g_timebase.num = 1;
301 config_->g_timebase.den = 90000;
302 config_->g_lag_in_frames = 0; // 0- no frame lagging
303 config_->g_threads = 1;
304 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700305 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000306 config_->rc_end_usage = VPX_CBR;
307 config_->g_pass = VPX_RC_ONE_PASS;
308 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000309 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000310 config_->rc_undershoot_pct = 50;
311 config_->rc_overshoot_pct = 50;
312 config_->rc_buf_initial_sz = 500;
313 config_->rc_buf_optimal_sz = 600;
314 config_->rc_buf_sz = 1000;
315 // Set the maximum target size of any key-frame.
316 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700317 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000318 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700319 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100320 // Needs to be set (in svc mode) to get correct periodic key frame interval
321 // (will have no effect in non-svc).
322 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000323 } else {
324 config_->kf_mode = VPX_KF_DISABLED;
325 }
hta257dc392016-10-25 09:05:06 -0700326 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000327 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800328 config_->g_threads =
329 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700330
Marco6e89b252015-07-07 14:40:38 -0700331 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700332
333 // TODO(asapersson): Check configuration of temporal switch up and increase
334 // pattern length.
hta257dc392016-10-25 09:05:06 -0700335 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800336 if (is_flexible_mode_) {
337 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
338 config_->ts_number_layers = num_temporal_layers_;
339 if (codec_.mode == kScreensharing)
340 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
341 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700342 gof_.SetGofInfoVP9(kTemporalStructureMode1);
343 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
344 config_->ts_number_layers = 1;
345 config_->ts_rate_decimator[0] = 1;
346 config_->ts_periodicity = 1;
347 config_->ts_layer_id[0] = 0;
348 } else if (num_temporal_layers_ == 2) {
349 gof_.SetGofInfoVP9(kTemporalStructureMode2);
350 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
351 config_->ts_number_layers = 2;
352 config_->ts_rate_decimator[0] = 2;
353 config_->ts_rate_decimator[1] = 1;
354 config_->ts_periodicity = 2;
355 config_->ts_layer_id[0] = 0;
356 config_->ts_layer_id[1] = 1;
357 } else if (num_temporal_layers_ == 3) {
358 gof_.SetGofInfoVP9(kTemporalStructureMode3);
359 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
360 config_->ts_number_layers = 3;
361 config_->ts_rate_decimator[0] = 4;
362 config_->ts_rate_decimator[1] = 2;
363 config_->ts_rate_decimator[2] = 1;
364 config_->ts_periodicity = 4;
365 config_->ts_layer_id[0] = 0;
366 config_->ts_layer_id[1] = 2;
367 config_->ts_layer_id[2] = 1;
368 config_->ts_layer_id[3] = 2;
369 } else {
370 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
371 }
372
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000373 return InitAndSetControlSettings(inst);
374}
375
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000376int VP9EncoderImpl::NumberOfThreads(int width,
377 int height,
378 int number_of_cores) {
379 // Keep the number of encoder threads equal to the possible number of column
380 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
381 if (width * height >= 1280 * 720 && number_of_cores > 4) {
382 return 4;
jianj23173a32017-07-12 16:11:09 -0700383 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000384 return 2;
385 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800386 // Use 2 threads for low res on ARM.
387#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
388 defined(WEBRTC_ANDROID)
389 if (width * height >= 320 * 180 && number_of_cores > 2) {
390 return 2;
391 }
392#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000393 // 1 thread less than VGA.
394 return 1;
395 }
396}
397
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000398int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100399 // Set QP-min/max per spatial and temporal layer.
400 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
401 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800402 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
403 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100404 }
asaperssona9455ab2015-07-31 06:10:09 -0700405 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800406 if (ExplicitlyConfiguredSpatialLayers()) {
407 for (int i = 0; i < num_spatial_layers_; ++i) {
408 const auto& layer = codec_.spatialLayers[i];
Sergey Silkin13e74342018-03-02 12:28:00 +0100409 const int scale_factor = codec_.width / layer.width;
410 RTC_DCHECK_GT(scale_factor, 0);
411
412 // Ensure scaler factor is integer.
413 if (scale_factor * layer.width != codec_.width) {
414 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
415 }
416
417 // Ensure scale factor is the same in both dimensions.
418 if (scale_factor * layer.height != codec_.height) {
419 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
420 }
421
422 // Ensure scale factor is power of two.
423 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
424 if (!is_pow_of_two) {
425 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
426 }
427
428 svc_params_.scaling_factor_num[i] = 1;
429 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800430 }
431 } else {
432 int scaling_factor_num = 256;
433 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800434 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800435 svc_params_.scaling_factor_num[i] = scaling_factor_num;
436 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800437 if (codec_.mode != kScreensharing)
438 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800439 }
asaperssona9455ab2015-07-31 06:10:09 -0700440 }
441
442 if (!SetSvcRates()) {
443 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
444 }
445
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000446 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
447 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
448 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000449 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
450 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
451 rc_max_intra_target_);
452 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700453 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700454
jianj822e5932017-07-12 16:09:58 -0700455 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700456 vpx_codec_control(
457 encoder_, VP9E_SET_SVC,
458 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
459 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
460 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800461 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700462 }
463 // Register callback for getting each spatial layer.
464 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800465 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
466 reinterpret_cast<void*>(this)};
467 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
468 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700469
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000470 // Control function to set the number of column tiles in encoding a frame, in
471 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
472 // The number tile columns will be capped by the encoder based on image size
473 // (minimum width of tile column is 256 pixels, maximum is 4096).
474 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700475
476 // Turn on row-based multithreading.
477 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700478
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700479#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
480 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700481 // Do not enable the denoiser on ARM since optimization is pending.
482 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000483 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700484 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000485#endif
jianj6bf57e32017-06-05 13:43:49 -0700486
ivica242d6382015-09-04 06:13:23 -0700487 if (codec_.mode == kScreensharing) {
488 // Adjust internal parameters to screen content.
489 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700490 }
Marco2520e722015-09-16 14:05:00 -0700491 // Enable encoder skip of static/low content blocks.
492 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000493 inited_ = true;
494 return WEBRTC_VIDEO_CODEC_OK;
495}
496
497uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
498 // Set max to the optimal buffer level (normalized by target BR),
499 // and scaled by a scale_par.
500 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
501 // This value is presented in percentage of perFrameBw:
502 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
503 // The target in % is as follows:
504 float scale_par = 0.5;
505 uint32_t target_pct =
506 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
507 // Don't go below 3 times the per frame bandwidth.
508 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800509 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000510}
511
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700512int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000513 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700514 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000515 if (!inited_) {
516 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
517 }
sprang3958ed82017-08-17 08:12:10 -0700518 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000519 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
520 }
Peter Boström49e196a2015-10-23 15:58:18 +0200521 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000522 // We only support one stream at the moment.
523 if (frame_types && frame_types->size() > 0) {
524 frame_type = (*frame_types)[0];
525 }
kwiberg352444f2016-11-28 15:58:53 -0800526 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
527 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700528
529 // Set input image for use in the callback.
530 // This was necessary since you need some information from input_image.
531 // You can save only the necessary information (such as timestamp) instead of
532 // doing this.
533 input_image_ = &input_image;
534
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000535 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
536 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000537 // Image in vpx_image_t format.
538 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000539 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
540 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
541 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
542 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
543 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
544 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000545
philipelcfc319b2015-11-10 07:17:23 -0800546 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200547 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000548 if (send_keyframe) {
549 // Key frame request from caller.
550 flags = VPX_EFLAG_FORCE_KF;
551 }
philipelcfc319b2015-11-10 07:17:23 -0800552
553 if (is_flexible_mode_) {
554 SuperFrameRefSettings settings;
555
556 // These structs are copied when calling vpx_codec_control,
557 // therefore it is ok for them to go out of scope.
558 vpx_svc_ref_frame_config enc_layer_conf;
559 vpx_svc_layer_id layer_id;
560
561 if (codec_.mode == kRealtimeVideo) {
562 // Real time video not yet implemented in flexible mode.
563 RTC_NOTREACHED();
564 } else {
565 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
566 send_keyframe);
567 }
568 enc_layer_conf = GenerateRefsAndFlags(settings);
569 layer_id.temporal_layer_id = 0;
570 layer_id.spatial_layer_id = settings.start_layer;
571 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
572 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
573 }
574
sprang3958ed82017-08-17 08:12:10 -0700575 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000576 uint32_t duration = 90000 / codec_.maxFramerate;
577 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
578 VPX_DL_REALTIME)) {
579 return WEBRTC_VIDEO_CODEC_ERROR;
580 }
581 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700582
583 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000584}
585
586void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800587 const vpx_codec_cx_pkt& pkt,
588 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700589 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000590 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700591 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800592 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Åsa Perssonff24c042015-12-04 10:58:08 +0100593 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700594 vp9_info->inter_pic_predicted =
595 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700596 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
597 vp9_info->ss_data_available =
598 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
599 ? true
600 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700601
602 vpx_svc_layer_id_t layer_id = {0};
603 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
604
sprang3958ed82017-08-17 08:12:10 -0700605 RTC_CHECK_GT(num_temporal_layers_, 0);
606 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700607 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700608 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700609 vp9_info->temporal_idx = kNoTemporalIdx;
610 } else {
611 vp9_info->temporal_idx = layer_id.temporal_layer_id;
612 }
613 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700614 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700615 vp9_info->spatial_idx = kNoSpatialIdx;
616 } else {
617 vp9_info->spatial_idx = layer_id.spatial_layer_id;
618 }
619 if (layer_id.spatial_layer_id != 0) {
620 vp9_info->ss_data_available = false;
621 }
622
asaperssona9455ab2015-07-31 06:10:09 -0700623 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800624 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700625
philipelcfc319b2015-11-10 07:17:23 -0800626 bool is_first_frame = false;
627 if (is_flexible_mode_) {
628 is_first_frame =
629 layer_id.spatial_layer_id == spatial_layer_->GetStartLayer();
630 } else {
631 is_first_frame = layer_id.spatial_layer_id == 0;
632 }
633
634 if (is_first_frame) {
asaperssona9455ab2015-07-31 06:10:09 -0700635 // TODO(asapersson): this info has to be obtained from the encoder.
636 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800637 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700638 } else {
639 // TODO(asapersson): this info has to be obtained from the encoder.
640 vp9_info->inter_layer_predicted = true;
641 }
642
Niels Möllerbb894ff2018-03-15 12:28:53 +0100643 vp9_info->first_frame_in_picture = is_first_frame;
644
asapersson00ac85e2015-11-11 05:30:48 -0800645 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
646 frames_since_kf_ = 0;
647 }
648
ivica7f6a6fc2015-09-08 02:40:29 -0700649 // Always populate this, so that the packetizer can properly set the marker
650 // bit.
651 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800652
653 vp9_info->num_ref_pics = 0;
654 if (vp9_info->flexible_mode) {
655 vp9_info->gof_idx = kNoGofIdx;
656 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
657 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
658 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
659 }
660 } else {
661 vp9_info->gof_idx =
662 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800663 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800664 }
philipelcfc319b2015-11-10 07:17:23 -0800665
asaperssona9455ab2015-07-31 06:10:09 -0700666 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700667 vp9_info->spatial_layer_resolution_present = true;
668 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
669 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800670 svc_params_.scaling_factor_num[i] /
671 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700672 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800673 svc_params_.scaling_factor_num[i] /
674 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700675 }
676 if (!vp9_info->flexible_mode) {
677 vp9_info->gof.CopyGofInfoVP9(gof_);
678 }
679 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000680}
681
asaperssona9455ab2015-07-31 06:10:09 -0700682int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800683 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700684
asaperssond9f641e2016-01-21 01:11:35 -0800685 if (pkt->data.frame.sz > encoded_image_._size) {
686 delete[] encoded_image_._buffer;
687 encoded_image_._size = pkt->data.frame.sz;
688 encoded_image_._buffer = new uint8_t[encoded_image_._size];
689 }
asapersson86956de2016-01-26 01:05:20 -0800690 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
691 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800692
asapersson86956de2016-01-26 01:05:20 -0800693 // No data partitioning in VP9, so 1 partition only.
694 int part_idx = 0;
695 RTPFragmentationHeader frag_info;
696 frag_info.VerifyAndAllocateFragmentationHeader(1);
697 frag_info.fragmentationOffset[part_idx] = 0;
698 frag_info.fragmentationLength[part_idx] = pkt->data.frame.sz;
asaperssona9455ab2015-07-31 06:10:09 -0700699 frag_info.fragmentationPlType[part_idx] = 0;
700 frag_info.fragmentationTimeDiff[part_idx] = 0;
philipelcfc319b2015-11-10 07:17:23 -0800701
702 vpx_svc_layer_id_t layer_id = {0};
703 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
704 if (is_flexible_mode_ && codec_.mode == kScreensharing)
705 spatial_layer_->LayerFrameEncoded(
706 static_cast<unsigned int>(encoded_image_._length),
707 layer_id.spatial_layer_id);
708
asaperssona9455ab2015-07-31 06:10:09 -0700709 // End of frame.
710 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800711 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700712 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200713 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000714 }
asapersson86956de2016-01-26 01:05:20 -0800715 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
716
717 CodecSpecificInfo codec_specific;
asaperssona9455ab2015-07-31 06:10:09 -0700718 PopulateCodecSpecific(&codec_specific, *pkt, input_image_->timestamp());
719
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000720 if (encoded_image_._length > 0) {
721 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
asaperssona9455ab2015-07-31 06:10:09 -0700722 encoded_image_._timeStamp = input_image_->timestamp();
723 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
Perba7dc722016-04-19 15:01:23 +0200724 encoded_image_.rotation_ = input_image_->rotation();
ilnik00d802b2017-04-11 10:34:31 -0700725 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
726 ? VideoContentType::SCREENSHARE
727 : VideoContentType::UNSPECIFIED;
Sergey Silkin956b3062018-02-01 10:43:49 +0100728 encoded_image_._encodedHeight =
729 pkt->data.frame.height[layer_id.spatial_layer_id];
730 encoded_image_._encodedWidth =
731 pkt->data.frame.width[layer_id.spatial_layer_id];
sprangba050a62017-08-18 02:51:12 -0700732 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
asapersson5265fed2016-04-18 02:58:47 -0700733 int qp = -1;
734 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
735 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700736
sergeyu2cb155a2016-11-04 11:39:29 -0700737 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific,
738 &frag_info);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000739 }
740 return WEBRTC_VIDEO_CODEC_OK;
741}
742
philipelcfc319b2015-11-10 07:17:23 -0800743vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
744 const SuperFrameRefSettings& settings) {
745 static const vpx_enc_frame_flags_t kAllFlags =
746 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
747 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
748 vpx_svc_ref_frame_config sf_conf = {};
749 if (settings.is_keyframe) {
750 // Used later on to make sure we don't make any invalid references.
751 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
752 for (int layer = settings.start_layer; layer <= settings.stop_layer;
753 ++layer) {
754 num_ref_pics_[layer] = 0;
755 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
756 // When encoding a keyframe only the alt_fb_idx is used
757 // to specify which layer ends up in which buffer.
758 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
759 }
760 } else {
761 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
762 ++layer_idx) {
763 vpx_enc_frame_flags_t layer_flags = kAllFlags;
764 num_ref_pics_[layer_idx] = 0;
765 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
766 settings.layer[layer_idx].ref_buf2,
767 settings.layer[layer_idx].ref_buf3};
768
769 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
770 if (refs[ref_idx] == -1)
771 continue;
772
773 RTC_DCHECK_GE(refs[ref_idx], 0);
774 RTC_DCHECK_LE(refs[ref_idx], 7);
775 // Easier to remove flags from all flags rather than having to
776 // build the flags from 0.
777 switch (num_ref_pics_[layer_idx]) {
778 case 0: {
779 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
780 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
781 break;
782 }
783 case 1: {
784 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
785 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
786 break;
787 }
788 case 2: {
789 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
790 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
791 break;
792 }
793 }
794 // Make sure we don't reference a buffer that hasn't been
795 // used at all or hasn't been used since a keyframe.
796 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
797
798 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
799 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
800 num_ref_pics_[layer_idx]++;
801 }
802
803 bool upd_buf_same_as_a_ref = false;
804 if (settings.layer[layer_idx].upd_buf != -1) {
805 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
806 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
807 switch (ref_idx) {
808 case 0: {
809 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
810 break;
811 }
812 case 1: {
813 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
814 break;
815 }
816 case 2: {
817 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
818 break;
819 }
820 }
821 upd_buf_same_as_a_ref = true;
822 break;
823 }
824 }
825 if (!upd_buf_same_as_a_ref) {
826 // If we have three references and a buffer is specified to be
827 // updated, then that buffer must be the same as one of the
828 // three references.
829 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
830
831 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
832 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
833 }
834
835 int updated_buffer = settings.layer[layer_idx].upd_buf;
836 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
837 sf_conf.frame_flags[layer_idx] = layer_flags;
838 }
839 }
840 }
841 ++frames_encoded_;
842 return sf_conf;
843}
844
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000845int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000846 return WEBRTC_VIDEO_CODEC_OK;
847}
848
849int VP9EncoderImpl::RegisterEncodeCompleteCallback(
850 EncodedImageCallback* callback) {
851 encoded_complete_callback_ = callback;
852 return WEBRTC_VIDEO_CODEC_OK;
853}
854
Peter Boströmb7d9a972015-12-18 16:01:11 +0100855const char* VP9EncoderImpl::ImplementationName() const {
856 return "libvpx";
857}
858
Peter Boström12996152016-05-14 02:03:18 +0200859bool VP9Decoder::IsSupported() {
860 return true;
861}
862
Magnus Jedvert46a27652017-11-13 14:10:02 +0100863std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
864 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000865}
866
867VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700868 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000869 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700870 decoder_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000871 key_frame_required_(true) {
872 memset(&codec_, 0, sizeof(codec_));
873}
874
875VP9DecoderImpl::~VP9DecoderImpl() {
876 inited_ = true; // in order to do the actual release
877 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200878 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
879 if (num_buffers_in_use > 0) {
880 // The frame buffers are reference counted and frames are exposed after
881 // decoding. There may be valid usage cases where previous frames are still
882 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100883 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
884 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200885 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000886}
887
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000888int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
sprang3958ed82017-08-17 08:12:10 -0700889 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000890 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
891 }
892 int ret_val = Release();
893 if (ret_val < 0) {
894 return ret_val;
895 }
sprang3958ed82017-08-17 08:12:10 -0700896 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000897 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000898 }
philipelcce46fc2015-12-21 03:04:49 -0800899 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000900 // Setting number of threads to a constant value (1)
901 cfg.threads = 1;
902 cfg.h = cfg.w = 0; // set after decode
903 vpx_codec_flags_t flags = 0;
904 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
905 return WEBRTC_VIDEO_CODEC_MEMORY;
906 }
907 if (&codec_ != inst) {
908 // Save VideoCodec instance for later; mainly for duplicating the decoder.
909 codec_ = *inst;
910 }
Henrik Boström9695d852015-05-06 10:42:15 +0200911
912 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
913 return WEBRTC_VIDEO_CODEC_MEMORY;
914 }
915
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000916 inited_ = true;
917 // Always start with a complete key frame.
918 key_frame_required_ = true;
919 return WEBRTC_VIDEO_CODEC_OK;
920}
921
922int VP9DecoderImpl::Decode(const EncodedImage& input_image,
923 bool missing_frames,
924 const RTPFragmentationHeader* fragmentation,
925 const CodecSpecificInfo* codec_specific_info,
926 int64_t /*render_time_ms*/) {
927 if (!inited_) {
928 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
929 }
sprang3958ed82017-08-17 08:12:10 -0700930 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000931 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
932 }
933 // Always start with a complete key frame.
934 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200935 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000936 return WEBRTC_VIDEO_CODEC_ERROR;
937 // We have a key frame - is it complete?
938 if (input_image._completeFrame) {
939 key_frame_required_ = false;
940 } else {
941 return WEBRTC_VIDEO_CODEC_ERROR;
942 }
943 }
sprang3958ed82017-08-17 08:12:10 -0700944 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000945 vpx_image_t* img;
946 uint8_t* buffer = input_image._buffer;
947 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700948 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000949 }
Henrik Boström9695d852015-05-06 10:42:15 +0200950 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
951 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800952 if (vpx_codec_decode(decoder_, buffer,
953 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000954 VPX_DL_REALTIME)) {
955 return WEBRTC_VIDEO_CODEC_ERROR;
956 }
Henrik Boström9695d852015-05-06 10:42:15 +0200957 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
958 // It may be released by libvpx during future vpx_codec_decode or
959 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000960 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800961 int qp;
962 vpx_codec_err_t vpx_ret =
963 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
964 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
965 int ret =
966 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000967 if (ret != 0) {
968 return ret;
969 }
970 return WEBRTC_VIDEO_CODEC_OK;
971}
972
asapersson1490f7a2016-09-23 02:09:46 -0700973int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
974 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800975 int64_t ntp_time_ms,
976 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700977 if (img == nullptr) {
978 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000979 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
980 }
Henrik Boström9695d852015-05-06 10:42:15 +0200981
982 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800983 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200984 // vpx_codec_decode calls or vpx_codec_destroy).
985 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
986 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700987 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200988 // using a WrappedI420Buffer.
989 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
990 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800991 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
992 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
993 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
994 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200995 // WrappedI420Buffer's mechanism for allowing the release of its frame
996 // buffer is through a callback function. This is where we should
997 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800998 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200999
nisseca6d5d12016-06-17 05:03:04 -07001000 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1001 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001002 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001003
Oskar Sundbom6bd39022017-11-16 10:54:49 +01001004 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001005 return WEBRTC_VIDEO_CODEC_OK;
1006}
1007
1008int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1009 DecodedImageCallback* callback) {
1010 decode_complete_callback_ = callback;
1011 return WEBRTC_VIDEO_CODEC_OK;
1012}
1013
1014int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001015 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1016
sprang3958ed82017-08-17 08:12:10 -07001017 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001018 if (inited_) {
1019 // When a codec is destroyed libvpx will release any buffers of
1020 // |frame_buffer_pool_| it is currently using.
1021 if (vpx_codec_destroy(decoder_)) {
1022 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1023 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001024 }
1025 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001026 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001027 }
Henrik Boström9695d852015-05-06 10:42:15 +02001028 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1029 // still referenced externally are deleted once fully released, not returning
1030 // to the pool.
1031 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001032 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001033 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001034}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001035
1036const char* VP9DecoderImpl::ImplementationName() const {
1037 return "libvpx";
1038}
1039
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001040} // namespace webrtc