blob: 2fb6e55affdcf51b5e1015b918c64b34d24c642f [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/random.h"
32#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),
philipelcfc319b2015-11-10 07:17:23 -080077 frames_since_kf_(0),
asaperssona9455ab2015-07-31 06:10:09 -070078 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080079 num_spatial_layers_(0),
Erik Språng08127a92016-11-16 16:41:30 +010080 is_flexible_mode_(false),
philipelcfc319b2015-11-10 07:17:23 -080081 frames_encoded_(0),
82 // Use two spatial when screensharing with flexible mode.
83 spatial_layer_(new ScreenshareLayersVP9(2)) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000084 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080085 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
brandtr080830c2017-05-03 03:25:53 -070086
87 Random random(rtc::TimeMicros());
88 picture_id_ = random.Rand<uint16_t>() & 0x7FFF;
89 tl0_pic_idx_ = random.Rand<uint8_t>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000090}
91
92VP9EncoderImpl::~VP9EncoderImpl() {
93 Release();
94}
95
96int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +010097 int ret_val = WEBRTC_VIDEO_CODEC_OK;
98
sprang3958ed82017-08-17 08:12:10 -070099 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800100 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700101 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000102 }
sprang3958ed82017-08-17 08:12:10 -0700103 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100104 if (inited_) {
105 if (vpx_codec_destroy(encoder_)) {
106 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
107 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000108 }
109 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700110 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000111 }
sprang3958ed82017-08-17 08:12:10 -0700112 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700114 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000115 }
sprang3958ed82017-08-17 08:12:10 -0700116 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000117 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700118 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000119 }
120 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100121 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000122}
123
sprangce4aef12015-11-02 07:23:20 -0800124bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
125 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
126 // (i.e. bitrates) were explicitly configured.
127 return num_spatial_layers_ > 1 &&
128 codec_.spatialLayers[0].target_bitrate_bps > 0;
129}
130
asaperssona9455ab2015-07-31 06:10:09 -0700131bool VP9EncoderImpl::SetSvcRates() {
asaperssona9455ab2015-07-31 06:10:09 -0700132 uint8_t i = 0;
133
sprangce4aef12015-11-02 07:23:20 -0800134 if (ExplicitlyConfiguredSpatialLayers()) {
135 if (num_temporal_layers_ > 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100136 RTC_LOG(LS_ERROR) << "Multiple temporal layers when manually specifying "
137 "spatial layers not implemented yet!";
asaperssona9455ab2015-07-31 06:10:09 -0700138 return false;
139 }
sprangce4aef12015-11-02 07:23:20 -0800140 int total_bitrate_bps = 0;
141 for (i = 0; i < num_spatial_layers_; ++i)
142 total_bitrate_bps += codec_.spatialLayers[i].target_bitrate_bps;
143 // If total bitrate differs now from what has been specified at the
144 // beginning, update the bitrates in the same ratio as before.
145 for (i = 0; i < num_spatial_layers_; ++i) {
146 config_->ss_target_bitrate[i] = config_->layer_target_bitrate[i] =
147 static_cast<int>(static_cast<int64_t>(config_->rc_target_bitrate) *
148 codec_.spatialLayers[i].target_bitrate_bps /
149 total_bitrate_bps);
150 }
151 } else {
152 float rate_ratio[VPX_MAX_LAYERS] = {0};
153 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700154
sprangce4aef12015-11-02 07:23:20 -0800155 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800156 if (svc_params_.scaling_factor_num[i] <= 0 ||
157 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100158 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800159 return false;
160 }
161 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800162 static_cast<float>(svc_params_.scaling_factor_num[i]) /
163 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800164 total += rate_ratio[i];
165 }
166
167 for (i = 0; i < num_spatial_layers_; ++i) {
168 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
169 config_->rc_target_bitrate * rate_ratio[i] / total);
170 if (num_temporal_layers_ == 1) {
171 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
172 } else if (num_temporal_layers_ == 2) {
173 config_->layer_target_bitrate[i * num_temporal_layers_] =
174 config_->ss_target_bitrate[i] * 2 / 3;
175 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
176 config_->ss_target_bitrate[i];
177 } else if (num_temporal_layers_ == 3) {
178 config_->layer_target_bitrate[i * num_temporal_layers_] =
179 config_->ss_target_bitrate[i] / 2;
180 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
181 config_->layer_target_bitrate[i * num_temporal_layers_] +
182 (config_->ss_target_bitrate[i] / 4);
183 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
184 config_->ss_target_bitrate[i];
185 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100186 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
187 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800188 return false;
189 }
asaperssona9455ab2015-07-31 06:10:09 -0700190 }
191 }
192
193 // For now, temporal layers only supported when having one spatial layer.
194 if (num_spatial_layers_ == 1) {
195 for (i = 0; i < num_temporal_layers_; ++i) {
196 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
197 }
198 }
199
200 return true;
201}
202
Erik Språng08127a92016-11-16 16:41:30 +0100203int VP9EncoderImpl::SetRateAllocation(
204 const BitrateAllocation& bitrate_allocation,
205 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000206 if (!inited_) {
207 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
208 }
209 if (encoder_->err) {
210 return WEBRTC_VIDEO_CODEC_ERROR;
211 }
Erik Språng08127a92016-11-16 16:41:30 +0100212 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000213 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
214 }
215 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100216 if (codec_.maxBitrate > 0 &&
217 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
218 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000219 }
Erik Språng08127a92016-11-16 16:41:30 +0100220
221 // TODO(sprang): Actually use BitrateAllocation layer info.
222 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
223 codec_.maxFramerate = frame_rate;
224 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
asaperssona9455ab2015-07-31 06:10:09 -0700225
226 if (!SetSvcRates()) {
227 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
228 }
229
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000230 // Update encoder context
231 if (vpx_codec_enc_config_set(encoder_, config_)) {
232 return WEBRTC_VIDEO_CODEC_ERROR;
233 }
234 return WEBRTC_VIDEO_CODEC_OK;
235}
236
237int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
238 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000239 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700240 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000241 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
242 }
243 if (inst->maxFramerate < 1) {
244 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
245 }
246 // Allow zero to represent an unspecified maxBitRate
247 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
248 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
249 }
250 if (inst->width < 1 || inst->height < 1) {
251 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
252 }
253 if (number_of_cores < 1) {
254 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
255 }
hta257dc392016-10-25 09:05:06 -0700256 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700257 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
258 }
ilnik2a8c2f52017-02-15 02:23:28 -0800259 // libvpx probably does not support more than 3 spatial layers.
260 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700261 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
262 }
philipelcfc319b2015-11-10 07:17:23 -0800263
asapersson86956de2016-01-26 01:05:20 -0800264 int ret_val = Release();
265 if (ret_val < 0) {
266 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000267 }
sprang3958ed82017-08-17 08:12:10 -0700268 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000269 encoder_ = new vpx_codec_ctx_t;
270 }
sprang3958ed82017-08-17 08:12:10 -0700271 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000272 config_ = new vpx_codec_enc_cfg_t;
273 }
274 timestamp_ = 0;
275 if (&codec_ != inst) {
276 codec_ = *inst;
277 }
asaperssona9455ab2015-07-31 06:10:09 -0700278
hta257dc392016-10-25 09:05:06 -0700279 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
280 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700281 if (num_temporal_layers_ == 0)
282 num_temporal_layers_ = 1;
283
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000284 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700285 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800286 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000287 }
nisseeb44b392017-04-28 07:18:05 -0700288 encoded_image_._size =
289 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000290 encoded_image_._buffer = new uint8_t[encoded_image_._size];
291 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700292 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000293 // pointer will be set in encode. Setting align to 1, as it is meaningless
294 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700295 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
296 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000297 // Populate encoder configuration with default values.
298 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
299 return WEBRTC_VIDEO_CODEC_ERROR;
300 }
301 config_->g_w = codec_.width;
302 config_->g_h = codec_.height;
303 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700304 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000305 // Setting the time base of the codec.
306 config_->g_timebase.num = 1;
307 config_->g_timebase.den = 90000;
308 config_->g_lag_in_frames = 0; // 0- no frame lagging
309 config_->g_threads = 1;
310 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700311 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000312 config_->rc_end_usage = VPX_CBR;
313 config_->g_pass = VPX_RC_ONE_PASS;
314 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000315 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000316 config_->rc_undershoot_pct = 50;
317 config_->rc_overshoot_pct = 50;
318 config_->rc_buf_initial_sz = 500;
319 config_->rc_buf_optimal_sz = 600;
320 config_->rc_buf_sz = 1000;
321 // Set the maximum target size of any key-frame.
322 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700323 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000324 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700325 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100326 // Needs to be set (in svc mode) to get correct periodic key frame interval
327 // (will have no effect in non-svc).
328 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000329 } else {
330 config_->kf_mode = VPX_KF_DISABLED;
331 }
hta257dc392016-10-25 09:05:06 -0700332 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000333 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800334 config_->g_threads =
335 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700336
Marco6e89b252015-07-07 14:40:38 -0700337 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700338
339 // TODO(asapersson): Check configuration of temporal switch up and increase
340 // pattern length.
hta257dc392016-10-25 09:05:06 -0700341 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800342 if (is_flexible_mode_) {
343 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
344 config_->ts_number_layers = num_temporal_layers_;
345 if (codec_.mode == kScreensharing)
346 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
347 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700348 gof_.SetGofInfoVP9(kTemporalStructureMode1);
349 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
350 config_->ts_number_layers = 1;
351 config_->ts_rate_decimator[0] = 1;
352 config_->ts_periodicity = 1;
353 config_->ts_layer_id[0] = 0;
354 } else if (num_temporal_layers_ == 2) {
355 gof_.SetGofInfoVP9(kTemporalStructureMode2);
356 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
357 config_->ts_number_layers = 2;
358 config_->ts_rate_decimator[0] = 2;
359 config_->ts_rate_decimator[1] = 1;
360 config_->ts_periodicity = 2;
361 config_->ts_layer_id[0] = 0;
362 config_->ts_layer_id[1] = 1;
363 } else if (num_temporal_layers_ == 3) {
364 gof_.SetGofInfoVP9(kTemporalStructureMode3);
365 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
366 config_->ts_number_layers = 3;
367 config_->ts_rate_decimator[0] = 4;
368 config_->ts_rate_decimator[1] = 2;
369 config_->ts_rate_decimator[2] = 1;
370 config_->ts_periodicity = 4;
371 config_->ts_layer_id[0] = 0;
372 config_->ts_layer_id[1] = 2;
373 config_->ts_layer_id[2] = 1;
374 config_->ts_layer_id[3] = 2;
375 } else {
376 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
377 }
378
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000379 return InitAndSetControlSettings(inst);
380}
381
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000382int VP9EncoderImpl::NumberOfThreads(int width,
383 int height,
384 int number_of_cores) {
385 // Keep the number of encoder threads equal to the possible number of column
386 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
387 if (width * height >= 1280 * 720 && number_of_cores > 4) {
388 return 4;
jianj23173a32017-07-12 16:11:09 -0700389 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000390 return 2;
391 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800392 // Use 2 threads for low res on ARM.
393#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
394 defined(WEBRTC_ANDROID)
395 if (width * height >= 320 * 180 && number_of_cores > 2) {
396 return 2;
397 }
398#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000399 // 1 thread less than VGA.
400 return 1;
401 }
402}
403
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000404int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100405 // Set QP-min/max per spatial and temporal layer.
406 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
407 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800408 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
409 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100410 }
asaperssona9455ab2015-07-31 06:10:09 -0700411 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800412 if (ExplicitlyConfiguredSpatialLayers()) {
413 for (int i = 0; i < num_spatial_layers_; ++i) {
414 const auto& layer = codec_.spatialLayers[i];
johannkoenig8225c402017-01-26 13:23:44 -0800415 svc_params_.scaling_factor_num[i] = layer.scaling_factor_num;
416 svc_params_.scaling_factor_den[i] = layer.scaling_factor_den;
sprangce4aef12015-11-02 07:23:20 -0800417 }
418 } else {
419 int scaling_factor_num = 256;
420 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800421 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800422 svc_params_.scaling_factor_num[i] = scaling_factor_num;
423 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800424 if (codec_.mode != kScreensharing)
425 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800426 }
asaperssona9455ab2015-07-31 06:10:09 -0700427 }
428
429 if (!SetSvcRates()) {
430 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
431 }
432
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000433 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
434 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
435 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000436 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
437 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
438 rc_max_intra_target_);
439 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700440 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700441
jianj822e5932017-07-12 16:09:58 -0700442 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700443 vpx_codec_control(
444 encoder_, VP9E_SET_SVC,
445 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
446 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
447 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800448 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700449 }
450 // Register callback for getting each spatial layer.
451 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800452 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
453 reinterpret_cast<void*>(this)};
454 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
455 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700456
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000457 // Control function to set the number of column tiles in encoding a frame, in
458 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
459 // The number tile columns will be capped by the encoder based on image size
460 // (minimum width of tile column is 256 pixels, maximum is 4096).
461 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700462
463 // Turn on row-based multithreading.
464 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700465
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700466#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
467 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700468 // Do not enable the denoiser on ARM since optimization is pending.
469 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000470 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700471 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000472#endif
jianj6bf57e32017-06-05 13:43:49 -0700473
ivica242d6382015-09-04 06:13:23 -0700474 if (codec_.mode == kScreensharing) {
475 // Adjust internal parameters to screen content.
476 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700477 }
Marco2520e722015-09-16 14:05:00 -0700478 // Enable encoder skip of static/low content blocks.
479 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000480 inited_ = true;
481 return WEBRTC_VIDEO_CODEC_OK;
482}
483
484uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
485 // Set max to the optimal buffer level (normalized by target BR),
486 // and scaled by a scale_par.
487 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
488 // This value is presented in percentage of perFrameBw:
489 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
490 // The target in % is as follows:
491 float scale_par = 0.5;
492 uint32_t target_pct =
493 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
494 // Don't go below 3 times the per frame bandwidth.
495 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800496 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000497}
498
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700499int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000500 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700501 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000502 if (!inited_) {
503 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
504 }
sprang3958ed82017-08-17 08:12:10 -0700505 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000506 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
507 }
Peter Boström49e196a2015-10-23 15:58:18 +0200508 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000509 // We only support one stream at the moment.
510 if (frame_types && frame_types->size() > 0) {
511 frame_type = (*frame_types)[0];
512 }
kwiberg352444f2016-11-28 15:58:53 -0800513 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
514 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700515
516 // Set input image for use in the callback.
517 // This was necessary since you need some information from input_image.
518 // You can save only the necessary information (such as timestamp) instead of
519 // doing this.
520 input_image_ = &input_image;
521
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000522 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
523 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000524 // Image in vpx_image_t format.
525 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000526 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
527 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
528 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
529 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
530 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
531 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000532
philipelcfc319b2015-11-10 07:17:23 -0800533 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200534 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000535 if (send_keyframe) {
536 // Key frame request from caller.
537 flags = VPX_EFLAG_FORCE_KF;
538 }
philipelcfc319b2015-11-10 07:17:23 -0800539
540 if (is_flexible_mode_) {
541 SuperFrameRefSettings settings;
542
543 // These structs are copied when calling vpx_codec_control,
544 // therefore it is ok for them to go out of scope.
545 vpx_svc_ref_frame_config enc_layer_conf;
546 vpx_svc_layer_id layer_id;
547
548 if (codec_.mode == kRealtimeVideo) {
549 // Real time video not yet implemented in flexible mode.
550 RTC_NOTREACHED();
551 } else {
552 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
553 send_keyframe);
554 }
555 enc_layer_conf = GenerateRefsAndFlags(settings);
556 layer_id.temporal_layer_id = 0;
557 layer_id.spatial_layer_id = settings.start_layer;
558 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
559 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
560 }
561
sprang3958ed82017-08-17 08:12:10 -0700562 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000563 uint32_t duration = 90000 / codec_.maxFramerate;
564 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
565 VPX_DL_REALTIME)) {
566 return WEBRTC_VIDEO_CODEC_ERROR;
567 }
568 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700569
570 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000571}
572
573void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800574 const vpx_codec_cx_pkt& pkt,
575 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700576 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000577 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700578 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800579 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Åsa Perssonff24c042015-12-04 10:58:08 +0100580 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700581 vp9_info->inter_pic_predicted =
582 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700583 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
584 vp9_info->ss_data_available =
585 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
586 ? true
587 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700588
589 vpx_svc_layer_id_t layer_id = {0};
590 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
591
sprang3958ed82017-08-17 08:12:10 -0700592 RTC_CHECK_GT(num_temporal_layers_, 0);
593 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700594 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700595 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700596 vp9_info->temporal_idx = kNoTemporalIdx;
597 } else {
598 vp9_info->temporal_idx = layer_id.temporal_layer_id;
599 }
600 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700601 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700602 vp9_info->spatial_idx = kNoSpatialIdx;
603 } else {
604 vp9_info->spatial_idx = layer_id.spatial_layer_id;
605 }
606 if (layer_id.spatial_layer_id != 0) {
607 vp9_info->ss_data_available = false;
608 }
609
asaperssona9455ab2015-07-31 06:10:09 -0700610 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800611 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700612
philipelcfc319b2015-11-10 07:17:23 -0800613 bool is_first_frame = false;
614 if (is_flexible_mode_) {
615 is_first_frame =
616 layer_id.spatial_layer_id == spatial_layer_->GetStartLayer();
617 } else {
618 is_first_frame = layer_id.spatial_layer_id == 0;
619 }
620
621 if (is_first_frame) {
asaperssona9455ab2015-07-31 06:10:09 -0700622 picture_id_ = (picture_id_ + 1) & 0x7FFF;
623 // TODO(asapersson): this info has to be obtained from the encoder.
624 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800625 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700626 } else {
627 // TODO(asapersson): this info has to be obtained from the encoder.
628 vp9_info->inter_layer_predicted = true;
629 }
630
asapersson00ac85e2015-11-11 05:30:48 -0800631 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
632 frames_since_kf_ = 0;
633 }
634
asaperssona9455ab2015-07-31 06:10:09 -0700635 vp9_info->picture_id = picture_id_;
636
637 if (!vp9_info->flexible_mode) {
638 if (layer_id.temporal_layer_id == 0 && layer_id.spatial_layer_id == 0) {
639 tl0_pic_idx_++;
640 }
641 vp9_info->tl0_pic_idx = tl0_pic_idx_;
642 }
643
ivica7f6a6fc2015-09-08 02:40:29 -0700644 // Always populate this, so that the packetizer can properly set the marker
645 // bit.
646 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800647
648 vp9_info->num_ref_pics = 0;
649 if (vp9_info->flexible_mode) {
650 vp9_info->gof_idx = kNoGofIdx;
651 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
652 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
653 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
654 }
655 } else {
656 vp9_info->gof_idx =
657 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800658 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800659 }
philipelcfc319b2015-11-10 07:17:23 -0800660
asaperssona9455ab2015-07-31 06:10:09 -0700661 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700662 vp9_info->spatial_layer_resolution_present = true;
663 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
664 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800665 svc_params_.scaling_factor_num[i] /
666 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700667 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800668 svc_params_.scaling_factor_num[i] /
669 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700670 }
671 if (!vp9_info->flexible_mode) {
672 vp9_info->gof.CopyGofInfoVP9(gof_);
673 }
674 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000675}
676
asaperssona9455ab2015-07-31 06:10:09 -0700677int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800678 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700679
asaperssond9f641e2016-01-21 01:11:35 -0800680 if (pkt->data.frame.sz > encoded_image_._size) {
681 delete[] encoded_image_._buffer;
682 encoded_image_._size = pkt->data.frame.sz;
683 encoded_image_._buffer = new uint8_t[encoded_image_._size];
684 }
asapersson86956de2016-01-26 01:05:20 -0800685 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
686 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800687
asapersson86956de2016-01-26 01:05:20 -0800688 // No data partitioning in VP9, so 1 partition only.
689 int part_idx = 0;
690 RTPFragmentationHeader frag_info;
691 frag_info.VerifyAndAllocateFragmentationHeader(1);
692 frag_info.fragmentationOffset[part_idx] = 0;
693 frag_info.fragmentationLength[part_idx] = pkt->data.frame.sz;
asaperssona9455ab2015-07-31 06:10:09 -0700694 frag_info.fragmentationPlType[part_idx] = 0;
695 frag_info.fragmentationTimeDiff[part_idx] = 0;
philipelcfc319b2015-11-10 07:17:23 -0800696
697 vpx_svc_layer_id_t layer_id = {0};
698 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
699 if (is_flexible_mode_ && codec_.mode == kScreensharing)
700 spatial_layer_->LayerFrameEncoded(
701 static_cast<unsigned int>(encoded_image_._length),
702 layer_id.spatial_layer_id);
703
asaperssona9455ab2015-07-31 06:10:09 -0700704 // End of frame.
705 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800706 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700707 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200708 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000709 }
asapersson86956de2016-01-26 01:05:20 -0800710 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
711
712 CodecSpecificInfo codec_specific;
asaperssona9455ab2015-07-31 06:10:09 -0700713 PopulateCodecSpecific(&codec_specific, *pkt, input_image_->timestamp());
714
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000715 if (encoded_image_._length > 0) {
716 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
asaperssona9455ab2015-07-31 06:10:09 -0700717 encoded_image_._timeStamp = input_image_->timestamp();
718 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
Perba7dc722016-04-19 15:01:23 +0200719 encoded_image_.rotation_ = input_image_->rotation();
ilnik00d802b2017-04-11 10:34:31 -0700720 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
721 ? VideoContentType::SCREENSHARE
722 : VideoContentType::UNSPECIFIED;
Sergey Silkin956b3062018-02-01 10:43:49 +0100723 encoded_image_._encodedHeight =
724 pkt->data.frame.height[layer_id.spatial_layer_id];
725 encoded_image_._encodedWidth =
726 pkt->data.frame.width[layer_id.spatial_layer_id];
sprangba050a62017-08-18 02:51:12 -0700727 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
asapersson5265fed2016-04-18 02:58:47 -0700728 int qp = -1;
729 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
730 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700731
sergeyu2cb155a2016-11-04 11:39:29 -0700732 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific,
733 &frag_info);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000734 }
735 return WEBRTC_VIDEO_CODEC_OK;
736}
737
philipelcfc319b2015-11-10 07:17:23 -0800738vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
739 const SuperFrameRefSettings& settings) {
740 static const vpx_enc_frame_flags_t kAllFlags =
741 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
742 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
743 vpx_svc_ref_frame_config sf_conf = {};
744 if (settings.is_keyframe) {
745 // Used later on to make sure we don't make any invalid references.
746 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
747 for (int layer = settings.start_layer; layer <= settings.stop_layer;
748 ++layer) {
749 num_ref_pics_[layer] = 0;
750 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
751 // When encoding a keyframe only the alt_fb_idx is used
752 // to specify which layer ends up in which buffer.
753 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
754 }
755 } else {
756 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
757 ++layer_idx) {
758 vpx_enc_frame_flags_t layer_flags = kAllFlags;
759 num_ref_pics_[layer_idx] = 0;
760 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
761 settings.layer[layer_idx].ref_buf2,
762 settings.layer[layer_idx].ref_buf3};
763
764 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
765 if (refs[ref_idx] == -1)
766 continue;
767
768 RTC_DCHECK_GE(refs[ref_idx], 0);
769 RTC_DCHECK_LE(refs[ref_idx], 7);
770 // Easier to remove flags from all flags rather than having to
771 // build the flags from 0.
772 switch (num_ref_pics_[layer_idx]) {
773 case 0: {
774 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
775 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
776 break;
777 }
778 case 1: {
779 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
780 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
781 break;
782 }
783 case 2: {
784 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
785 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
786 break;
787 }
788 }
789 // Make sure we don't reference a buffer that hasn't been
790 // used at all or hasn't been used since a keyframe.
791 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
792
793 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
794 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
795 num_ref_pics_[layer_idx]++;
796 }
797
798 bool upd_buf_same_as_a_ref = false;
799 if (settings.layer[layer_idx].upd_buf != -1) {
800 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
801 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
802 switch (ref_idx) {
803 case 0: {
804 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
805 break;
806 }
807 case 1: {
808 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
809 break;
810 }
811 case 2: {
812 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
813 break;
814 }
815 }
816 upd_buf_same_as_a_ref = true;
817 break;
818 }
819 }
820 if (!upd_buf_same_as_a_ref) {
821 // If we have three references and a buffer is specified to be
822 // updated, then that buffer must be the same as one of the
823 // three references.
824 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
825
826 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
827 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
828 }
829
830 int updated_buffer = settings.layer[layer_idx].upd_buf;
831 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
832 sf_conf.frame_flags[layer_idx] = layer_flags;
833 }
834 }
835 }
836 ++frames_encoded_;
837 return sf_conf;
838}
839
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000840int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000841 return WEBRTC_VIDEO_CODEC_OK;
842}
843
844int VP9EncoderImpl::RegisterEncodeCompleteCallback(
845 EncodedImageCallback* callback) {
846 encoded_complete_callback_ = callback;
847 return WEBRTC_VIDEO_CODEC_OK;
848}
849
Peter Boströmb7d9a972015-12-18 16:01:11 +0100850const char* VP9EncoderImpl::ImplementationName() const {
851 return "libvpx";
852}
853
Peter Boström12996152016-05-14 02:03:18 +0200854bool VP9Decoder::IsSupported() {
855 return true;
856}
857
Magnus Jedvert46a27652017-11-13 14:10:02 +0100858std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
859 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000860}
861
862VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700863 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000864 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700865 decoder_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000866 key_frame_required_(true) {
867 memset(&codec_, 0, sizeof(codec_));
868}
869
870VP9DecoderImpl::~VP9DecoderImpl() {
871 inited_ = true; // in order to do the actual release
872 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200873 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
874 if (num_buffers_in_use > 0) {
875 // The frame buffers are reference counted and frames are exposed after
876 // decoding. There may be valid usage cases where previous frames are still
877 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100878 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
879 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200880 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000881}
882
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000883int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
sprang3958ed82017-08-17 08:12:10 -0700884 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000885 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
886 }
887 int ret_val = Release();
888 if (ret_val < 0) {
889 return ret_val;
890 }
sprang3958ed82017-08-17 08:12:10 -0700891 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000892 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000893 }
philipelcce46fc2015-12-21 03:04:49 -0800894 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000895 // Setting number of threads to a constant value (1)
896 cfg.threads = 1;
897 cfg.h = cfg.w = 0; // set after decode
898 vpx_codec_flags_t flags = 0;
899 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
900 return WEBRTC_VIDEO_CODEC_MEMORY;
901 }
902 if (&codec_ != inst) {
903 // Save VideoCodec instance for later; mainly for duplicating the decoder.
904 codec_ = *inst;
905 }
Henrik Boström9695d852015-05-06 10:42:15 +0200906
907 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
908 return WEBRTC_VIDEO_CODEC_MEMORY;
909 }
910
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000911 inited_ = true;
912 // Always start with a complete key frame.
913 key_frame_required_ = true;
914 return WEBRTC_VIDEO_CODEC_OK;
915}
916
917int VP9DecoderImpl::Decode(const EncodedImage& input_image,
918 bool missing_frames,
919 const RTPFragmentationHeader* fragmentation,
920 const CodecSpecificInfo* codec_specific_info,
921 int64_t /*render_time_ms*/) {
922 if (!inited_) {
923 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
924 }
sprang3958ed82017-08-17 08:12:10 -0700925 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000926 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
927 }
928 // Always start with a complete key frame.
929 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200930 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000931 return WEBRTC_VIDEO_CODEC_ERROR;
932 // We have a key frame - is it complete?
933 if (input_image._completeFrame) {
934 key_frame_required_ = false;
935 } else {
936 return WEBRTC_VIDEO_CODEC_ERROR;
937 }
938 }
sprang3958ed82017-08-17 08:12:10 -0700939 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000940 vpx_image_t* img;
941 uint8_t* buffer = input_image._buffer;
942 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700943 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000944 }
Henrik Boström9695d852015-05-06 10:42:15 +0200945 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
946 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800947 if (vpx_codec_decode(decoder_, buffer,
948 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000949 VPX_DL_REALTIME)) {
950 return WEBRTC_VIDEO_CODEC_ERROR;
951 }
Henrik Boström9695d852015-05-06 10:42:15 +0200952 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
953 // It may be released by libvpx during future vpx_codec_decode or
954 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000955 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800956 int qp;
957 vpx_codec_err_t vpx_ret =
958 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
959 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
960 int ret =
961 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000962 if (ret != 0) {
963 return ret;
964 }
965 return WEBRTC_VIDEO_CODEC_OK;
966}
967
asapersson1490f7a2016-09-23 02:09:46 -0700968int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
969 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800970 int64_t ntp_time_ms,
971 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700972 if (img == nullptr) {
973 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000974 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
975 }
Henrik Boström9695d852015-05-06 10:42:15 +0200976
977 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800978 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200979 // vpx_codec_decode calls or vpx_codec_destroy).
980 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
981 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700982 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200983 // using a WrappedI420Buffer.
984 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
985 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800986 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
987 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
988 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
989 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200990 // WrappedI420Buffer's mechanism for allowing the release of its frame
991 // buffer is through a callback function. This is where we should
992 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800993 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200994
nisseca6d5d12016-06-17 05:03:04 -0700995 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
996 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -0700997 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -0700998
Oskar Sundbom6bd39022017-11-16 10:54:49 +0100999 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001000 return WEBRTC_VIDEO_CODEC_OK;
1001}
1002
1003int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1004 DecodedImageCallback* callback) {
1005 decode_complete_callback_ = callback;
1006 return WEBRTC_VIDEO_CODEC_OK;
1007}
1008
1009int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001010 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1011
sprang3958ed82017-08-17 08:12:10 -07001012 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001013 if (inited_) {
1014 // When a codec is destroyed libvpx will release any buffers of
1015 // |frame_buffer_pool_| it is currently using.
1016 if (vpx_codec_destroy(decoder_)) {
1017 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1018 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001019 }
1020 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001021 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001022 }
Henrik Boström9695d852015-05-06 10:42:15 +02001023 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1024 // still referenced externally are deleted once fully released, not returning
1025 // to the pool.
1026 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001027 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001028 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001029}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001030
1031const char* VP9DecoderImpl::ImplementationName() const {
1032 return "libvpx";
1033}
1034
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001035} // namespace webrtc