blob: c68fea778af6b9076234dd1def55453d0ba48d11 [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"
30#include "rtc_base/random.h"
31#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 Jedvert34c8e6b2017-11-13 13:02:16 +000055VP9Encoder* VP9Encoder::Create() {
56 return new 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));
brandtr080830c2017-05-03 03:25:53 -070085
86 Random random(rtc::TimeMicros());
87 picture_id_ = random.Rand<uint16_t>() & 0x7FFF;
88 tl0_pic_idx_ = random.Rand<uint8_t>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +000089}
90
91VP9EncoderImpl::~VP9EncoderImpl() {
92 Release();
93}
94
95int VP9EncoderImpl::Release() {
sprang3958ed82017-08-17 08:12:10 -070096 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -080097 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -070098 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +000099 }
sprang3958ed82017-08-17 08:12:10 -0700100 if (encoder_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000101 if (vpx_codec_destroy(encoder_)) {
102 return WEBRTC_VIDEO_CODEC_MEMORY;
103 }
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;
116 return WEBRTC_VIDEO_CODEC_OK;
117}
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.
122 return num_spatial_layers_ > 1 &&
123 codec_.spatialLayers[0].target_bitrate_bps > 0;
124}
125
asaperssona9455ab2015-07-31 06:10:09 -0700126bool VP9EncoderImpl::SetSvcRates() {
asaperssona9455ab2015-07-31 06:10:09 -0700127 uint8_t i = 0;
128
sprangce4aef12015-11-02 07:23:20 -0800129 if (ExplicitlyConfiguredSpatialLayers()) {
130 if (num_temporal_layers_ > 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100131 RTC_LOG(LS_ERROR) << "Multiple temporal layers when manually specifying "
132 "spatial layers not implemented yet!";
asaperssona9455ab2015-07-31 06:10:09 -0700133 return false;
134 }
sprangce4aef12015-11-02 07:23:20 -0800135 int total_bitrate_bps = 0;
136 for (i = 0; i < num_spatial_layers_; ++i)
137 total_bitrate_bps += codec_.spatialLayers[i].target_bitrate_bps;
138 // If total bitrate differs now from what has been specified at the
139 // beginning, update the bitrates in the same ratio as before.
140 for (i = 0; i < num_spatial_layers_; ++i) {
141 config_->ss_target_bitrate[i] = config_->layer_target_bitrate[i] =
142 static_cast<int>(static_cast<int64_t>(config_->rc_target_bitrate) *
143 codec_.spatialLayers[i].target_bitrate_bps /
144 total_bitrate_bps);
145 }
146 } else {
147 float rate_ratio[VPX_MAX_LAYERS] = {0};
148 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700149
sprangce4aef12015-11-02 07:23:20 -0800150 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800151 if (svc_params_.scaling_factor_num[i] <= 0 ||
152 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100153 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800154 return false;
155 }
156 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800157 static_cast<float>(svc_params_.scaling_factor_num[i]) /
158 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800159 total += rate_ratio[i];
160 }
161
162 for (i = 0; i < num_spatial_layers_; ++i) {
163 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
164 config_->rc_target_bitrate * rate_ratio[i] / total);
165 if (num_temporal_layers_ == 1) {
166 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
167 } else if (num_temporal_layers_ == 2) {
168 config_->layer_target_bitrate[i * num_temporal_layers_] =
169 config_->ss_target_bitrate[i] * 2 / 3;
170 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
171 config_->ss_target_bitrate[i];
172 } else if (num_temporal_layers_ == 3) {
173 config_->layer_target_bitrate[i * num_temporal_layers_] =
174 config_->ss_target_bitrate[i] / 2;
175 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
176 config_->layer_target_bitrate[i * num_temporal_layers_] +
177 (config_->ss_target_bitrate[i] / 4);
178 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
179 config_->ss_target_bitrate[i];
180 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100181 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
182 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800183 return false;
184 }
asaperssona9455ab2015-07-31 06:10:09 -0700185 }
186 }
187
188 // For now, temporal layers only supported when having one spatial layer.
189 if (num_spatial_layers_ == 1) {
190 for (i = 0; i < num_temporal_layers_; ++i) {
191 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
192 }
193 }
194
195 return true;
196}
197
Erik Språng08127a92016-11-16 16:41:30 +0100198int VP9EncoderImpl::SetRateAllocation(
199 const BitrateAllocation& bitrate_allocation,
200 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000201 if (!inited_) {
202 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
203 }
204 if (encoder_->err) {
205 return WEBRTC_VIDEO_CODEC_ERROR;
206 }
Erik Språng08127a92016-11-16 16:41:30 +0100207 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000208 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
209 }
210 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100211 if (codec_.maxBitrate > 0 &&
212 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
213 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000214 }
Erik Språng08127a92016-11-16 16:41:30 +0100215
216 // TODO(sprang): Actually use BitrateAllocation layer info.
217 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
218 codec_.maxFramerate = frame_rate;
219 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
asaperssona9455ab2015-07-31 06:10:09 -0700220
221 if (!SetSvcRates()) {
222 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
223 }
224
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000225 // Update encoder context
226 if (vpx_codec_enc_config_set(encoder_, config_)) {
227 return WEBRTC_VIDEO_CODEC_ERROR;
228 }
229 return WEBRTC_VIDEO_CODEC_OK;
230}
231
232int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
233 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000234 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700235 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000236 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
237 }
238 if (inst->maxFramerate < 1) {
239 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
240 }
241 // Allow zero to represent an unspecified maxBitRate
242 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
243 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
244 }
245 if (inst->width < 1 || inst->height < 1) {
246 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
247 }
248 if (number_of_cores < 1) {
249 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
250 }
hta257dc392016-10-25 09:05:06 -0700251 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700252 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
253 }
ilnik2a8c2f52017-02-15 02:23:28 -0800254 // libvpx probably does not support more than 3 spatial layers.
255 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700256 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
257 }
philipelcfc319b2015-11-10 07:17:23 -0800258
asapersson86956de2016-01-26 01:05:20 -0800259 int ret_val = Release();
260 if (ret_val < 0) {
261 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000262 }
sprang3958ed82017-08-17 08:12:10 -0700263 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000264 encoder_ = new vpx_codec_ctx_t;
265 }
sprang3958ed82017-08-17 08:12:10 -0700266 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000267 config_ = new vpx_codec_enc_cfg_t;
268 }
269 timestamp_ = 0;
270 if (&codec_ != inst) {
271 codec_ = *inst;
272 }
asaperssona9455ab2015-07-31 06:10:09 -0700273
hta257dc392016-10-25 09:05:06 -0700274 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
275 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700276 if (num_temporal_layers_ == 0)
277 num_temporal_layers_ = 1;
278
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000279 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700280 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800281 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000282 }
nisseeb44b392017-04-28 07:18:05 -0700283 encoded_image_._size =
284 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000285 encoded_image_._buffer = new uint8_t[encoded_image_._size];
286 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700287 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000288 // pointer will be set in encode. Setting align to 1, as it is meaningless
289 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700290 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
291 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000292 // Populate encoder configuration with default values.
293 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
294 return WEBRTC_VIDEO_CODEC_ERROR;
295 }
296 config_->g_w = codec_.width;
297 config_->g_h = codec_.height;
298 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700299 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000300 // Setting the time base of the codec.
301 config_->g_timebase.num = 1;
302 config_->g_timebase.den = 90000;
303 config_->g_lag_in_frames = 0; // 0- no frame lagging
304 config_->g_threads = 1;
305 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700306 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000307 config_->rc_end_usage = VPX_CBR;
308 config_->g_pass = VPX_RC_ONE_PASS;
309 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000310 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000311 config_->rc_undershoot_pct = 50;
312 config_->rc_overshoot_pct = 50;
313 config_->rc_buf_initial_sz = 500;
314 config_->rc_buf_optimal_sz = 600;
315 config_->rc_buf_sz = 1000;
316 // Set the maximum target size of any key-frame.
317 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700318 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000319 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700320 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100321 // Needs to be set (in svc mode) to get correct periodic key frame interval
322 // (will have no effect in non-svc).
323 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000324 } else {
325 config_->kf_mode = VPX_KF_DISABLED;
326 }
hta257dc392016-10-25 09:05:06 -0700327 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000328 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800329 config_->g_threads =
330 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700331
Marco6e89b252015-07-07 14:40:38 -0700332 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700333
334 // TODO(asapersson): Check configuration of temporal switch up and increase
335 // pattern length.
hta257dc392016-10-25 09:05:06 -0700336 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800337 if (is_flexible_mode_) {
338 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
339 config_->ts_number_layers = num_temporal_layers_;
340 if (codec_.mode == kScreensharing)
341 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
342 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700343 gof_.SetGofInfoVP9(kTemporalStructureMode1);
344 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
345 config_->ts_number_layers = 1;
346 config_->ts_rate_decimator[0] = 1;
347 config_->ts_periodicity = 1;
348 config_->ts_layer_id[0] = 0;
349 } else if (num_temporal_layers_ == 2) {
350 gof_.SetGofInfoVP9(kTemporalStructureMode2);
351 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
352 config_->ts_number_layers = 2;
353 config_->ts_rate_decimator[0] = 2;
354 config_->ts_rate_decimator[1] = 1;
355 config_->ts_periodicity = 2;
356 config_->ts_layer_id[0] = 0;
357 config_->ts_layer_id[1] = 1;
358 } else if (num_temporal_layers_ == 3) {
359 gof_.SetGofInfoVP9(kTemporalStructureMode3);
360 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
361 config_->ts_number_layers = 3;
362 config_->ts_rate_decimator[0] = 4;
363 config_->ts_rate_decimator[1] = 2;
364 config_->ts_rate_decimator[2] = 1;
365 config_->ts_periodicity = 4;
366 config_->ts_layer_id[0] = 0;
367 config_->ts_layer_id[1] = 2;
368 config_->ts_layer_id[2] = 1;
369 config_->ts_layer_id[3] = 2;
370 } else {
371 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
372 }
373
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000374 return InitAndSetControlSettings(inst);
375}
376
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000377int VP9EncoderImpl::NumberOfThreads(int width,
378 int height,
379 int number_of_cores) {
380 // Keep the number of encoder threads equal to the possible number of column
381 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
382 if (width * height >= 1280 * 720 && number_of_cores > 4) {
383 return 4;
jianj23173a32017-07-12 16:11:09 -0700384 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000385 return 2;
386 } else {
387 // 1 thread less than VGA.
388 return 1;
389 }
390}
391
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000392int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100393 // Set QP-min/max per spatial and temporal layer.
394 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
395 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800396 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
397 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100398 }
asaperssona9455ab2015-07-31 06:10:09 -0700399 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800400 if (ExplicitlyConfiguredSpatialLayers()) {
401 for (int i = 0; i < num_spatial_layers_; ++i) {
402 const auto& layer = codec_.spatialLayers[i];
johannkoenig8225c402017-01-26 13:23:44 -0800403 svc_params_.scaling_factor_num[i] = layer.scaling_factor_num;
404 svc_params_.scaling_factor_den[i] = layer.scaling_factor_den;
sprangce4aef12015-11-02 07:23:20 -0800405 }
406 } else {
407 int scaling_factor_num = 256;
408 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800409 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800410 svc_params_.scaling_factor_num[i] = scaling_factor_num;
411 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800412 if (codec_.mode != kScreensharing)
413 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800414 }
asaperssona9455ab2015-07-31 06:10:09 -0700415 }
416
417 if (!SetSvcRates()) {
418 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
419 }
420
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000421 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
422 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
423 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000424 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
425 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
426 rc_max_intra_target_);
427 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700428 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700429
jianj822e5932017-07-12 16:09:58 -0700430 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700431 vpx_codec_control(
432 encoder_, VP9E_SET_SVC,
433 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
434 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
435 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800436 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700437 }
438 // Register callback for getting each spatial layer.
439 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800440 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
441 reinterpret_cast<void*>(this)};
442 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
443 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700444
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000445 // Control function to set the number of column tiles in encoding a frame, in
446 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
447 // The number tile columns will be capped by the encoder based on image size
448 // (minimum width of tile column is 256 pixels, maximum is 4096).
449 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700450
451 // Turn on row-based multithreading.
452 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700453
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700454#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
455 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700456 // Do not enable the denoiser on ARM since optimization is pending.
457 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000458 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700459 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000460#endif
jianj6bf57e32017-06-05 13:43:49 -0700461
ivica242d6382015-09-04 06:13:23 -0700462 if (codec_.mode == kScreensharing) {
463 // Adjust internal parameters to screen content.
464 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700465 }
Marco2520e722015-09-16 14:05:00 -0700466 // Enable encoder skip of static/low content blocks.
467 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000468 inited_ = true;
469 return WEBRTC_VIDEO_CODEC_OK;
470}
471
472uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
473 // Set max to the optimal buffer level (normalized by target BR),
474 // and scaled by a scale_par.
475 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
476 // This value is presented in percentage of perFrameBw:
477 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
478 // The target in % is as follows:
479 float scale_par = 0.5;
480 uint32_t target_pct =
481 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
482 // Don't go below 3 times the per frame bandwidth.
483 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800484 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000485}
486
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700487int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000488 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700489 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000490 if (!inited_) {
491 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
492 }
sprang3958ed82017-08-17 08:12:10 -0700493 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000494 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
495 }
Peter Boström49e196a2015-10-23 15:58:18 +0200496 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000497 // We only support one stream at the moment.
498 if (frame_types && frame_types->size() > 0) {
499 frame_type = (*frame_types)[0];
500 }
kwiberg352444f2016-11-28 15:58:53 -0800501 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
502 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700503
504 // Set input image for use in the callback.
505 // This was necessary since you need some information from input_image.
506 // You can save only the necessary information (such as timestamp) instead of
507 // doing this.
508 input_image_ = &input_image;
509
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000510 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
511 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000512 // Image in vpx_image_t format.
513 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000514 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
515 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
516 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
517 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
518 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
519 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000520
philipelcfc319b2015-11-10 07:17:23 -0800521 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200522 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000523 if (send_keyframe) {
524 // Key frame request from caller.
525 flags = VPX_EFLAG_FORCE_KF;
526 }
philipelcfc319b2015-11-10 07:17:23 -0800527
528 if (is_flexible_mode_) {
529 SuperFrameRefSettings settings;
530
531 // These structs are copied when calling vpx_codec_control,
532 // therefore it is ok for them to go out of scope.
533 vpx_svc_ref_frame_config enc_layer_conf;
534 vpx_svc_layer_id layer_id;
535
536 if (codec_.mode == kRealtimeVideo) {
537 // Real time video not yet implemented in flexible mode.
538 RTC_NOTREACHED();
539 } else {
540 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
541 send_keyframe);
542 }
543 enc_layer_conf = GenerateRefsAndFlags(settings);
544 layer_id.temporal_layer_id = 0;
545 layer_id.spatial_layer_id = settings.start_layer;
546 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
547 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
548 }
549
sprang3958ed82017-08-17 08:12:10 -0700550 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000551 uint32_t duration = 90000 / codec_.maxFramerate;
552 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
553 VPX_DL_REALTIME)) {
554 return WEBRTC_VIDEO_CODEC_ERROR;
555 }
556 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700557
558 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000559}
560
561void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800562 const vpx_codec_cx_pkt& pkt,
563 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700564 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000565 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700566 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800567 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Åsa Perssonff24c042015-12-04 10:58:08 +0100568 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700569 vp9_info->inter_pic_predicted =
570 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700571 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
572 vp9_info->ss_data_available =
573 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
574 ? true
575 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700576
577 vpx_svc_layer_id_t layer_id = {0};
578 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
579
sprang3958ed82017-08-17 08:12:10 -0700580 RTC_CHECK_GT(num_temporal_layers_, 0);
581 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700582 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700583 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700584 vp9_info->temporal_idx = kNoTemporalIdx;
585 } else {
586 vp9_info->temporal_idx = layer_id.temporal_layer_id;
587 }
588 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700589 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700590 vp9_info->spatial_idx = kNoSpatialIdx;
591 } else {
592 vp9_info->spatial_idx = layer_id.spatial_layer_id;
593 }
594 if (layer_id.spatial_layer_id != 0) {
595 vp9_info->ss_data_available = false;
596 }
597
asaperssona9455ab2015-07-31 06:10:09 -0700598 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800599 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700600
philipelcfc319b2015-11-10 07:17:23 -0800601 bool is_first_frame = false;
602 if (is_flexible_mode_) {
603 is_first_frame =
604 layer_id.spatial_layer_id == spatial_layer_->GetStartLayer();
605 } else {
606 is_first_frame = layer_id.spatial_layer_id == 0;
607 }
608
609 if (is_first_frame) {
asaperssona9455ab2015-07-31 06:10:09 -0700610 picture_id_ = (picture_id_ + 1) & 0x7FFF;
611 // TODO(asapersson): this info has to be obtained from the encoder.
612 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800613 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700614 } else {
615 // TODO(asapersson): this info has to be obtained from the encoder.
616 vp9_info->inter_layer_predicted = true;
617 }
618
asapersson00ac85e2015-11-11 05:30:48 -0800619 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
620 frames_since_kf_ = 0;
621 }
622
asaperssona9455ab2015-07-31 06:10:09 -0700623 vp9_info->picture_id = picture_id_;
624
625 if (!vp9_info->flexible_mode) {
626 if (layer_id.temporal_layer_id == 0 && layer_id.spatial_layer_id == 0) {
627 tl0_pic_idx_++;
628 }
629 vp9_info->tl0_pic_idx = tl0_pic_idx_;
630 }
631
ivica7f6a6fc2015-09-08 02:40:29 -0700632 // Always populate this, so that the packetizer can properly set the marker
633 // bit.
634 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800635
636 vp9_info->num_ref_pics = 0;
637 if (vp9_info->flexible_mode) {
638 vp9_info->gof_idx = kNoGofIdx;
639 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
640 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
641 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
642 }
643 } else {
644 vp9_info->gof_idx =
645 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800646 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800647 }
philipelcfc319b2015-11-10 07:17:23 -0800648
asaperssona9455ab2015-07-31 06:10:09 -0700649 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700650 vp9_info->spatial_layer_resolution_present = true;
651 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
652 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800653 svc_params_.scaling_factor_num[i] /
654 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700655 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800656 svc_params_.scaling_factor_num[i] /
657 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700658 }
659 if (!vp9_info->flexible_mode) {
660 vp9_info->gof.CopyGofInfoVP9(gof_);
661 }
662 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000663}
664
asaperssona9455ab2015-07-31 06:10:09 -0700665int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800666 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700667
asaperssond9f641e2016-01-21 01:11:35 -0800668 if (pkt->data.frame.sz > encoded_image_._size) {
669 delete[] encoded_image_._buffer;
670 encoded_image_._size = pkt->data.frame.sz;
671 encoded_image_._buffer = new uint8_t[encoded_image_._size];
672 }
asapersson86956de2016-01-26 01:05:20 -0800673 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
674 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800675
asapersson86956de2016-01-26 01:05:20 -0800676 // No data partitioning in VP9, so 1 partition only.
677 int part_idx = 0;
678 RTPFragmentationHeader frag_info;
679 frag_info.VerifyAndAllocateFragmentationHeader(1);
680 frag_info.fragmentationOffset[part_idx] = 0;
681 frag_info.fragmentationLength[part_idx] = pkt->data.frame.sz;
asaperssona9455ab2015-07-31 06:10:09 -0700682 frag_info.fragmentationPlType[part_idx] = 0;
683 frag_info.fragmentationTimeDiff[part_idx] = 0;
philipelcfc319b2015-11-10 07:17:23 -0800684
685 vpx_svc_layer_id_t layer_id = {0};
686 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
687 if (is_flexible_mode_ && codec_.mode == kScreensharing)
688 spatial_layer_->LayerFrameEncoded(
689 static_cast<unsigned int>(encoded_image_._length),
690 layer_id.spatial_layer_id);
691
asaperssona9455ab2015-07-31 06:10:09 -0700692 // End of frame.
693 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800694 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700695 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200696 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000697 }
asapersson86956de2016-01-26 01:05:20 -0800698 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
699
700 CodecSpecificInfo codec_specific;
asaperssona9455ab2015-07-31 06:10:09 -0700701 PopulateCodecSpecific(&codec_specific, *pkt, input_image_->timestamp());
702
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000703 if (encoded_image_._length > 0) {
704 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
asaperssona9455ab2015-07-31 06:10:09 -0700705 encoded_image_._timeStamp = input_image_->timestamp();
706 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
Perba7dc722016-04-19 15:01:23 +0200707 encoded_image_.rotation_ = input_image_->rotation();
ilnik00d802b2017-04-11 10:34:31 -0700708 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
709 ? VideoContentType::SCREENSHARE
710 : VideoContentType::UNSPECIFIED;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000711 encoded_image_._encodedHeight = raw_->d_h;
712 encoded_image_._encodedWidth = raw_->d_w;
sprangba050a62017-08-18 02:51:12 -0700713 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
asapersson5265fed2016-04-18 02:58:47 -0700714 int qp = -1;
715 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
716 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700717
sergeyu2cb155a2016-11-04 11:39:29 -0700718 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific,
719 &frag_info);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000720 }
721 return WEBRTC_VIDEO_CODEC_OK;
722}
723
philipelcfc319b2015-11-10 07:17:23 -0800724vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
725 const SuperFrameRefSettings& settings) {
726 static const vpx_enc_frame_flags_t kAllFlags =
727 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
728 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
729 vpx_svc_ref_frame_config sf_conf = {};
730 if (settings.is_keyframe) {
731 // Used later on to make sure we don't make any invalid references.
732 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
733 for (int layer = settings.start_layer; layer <= settings.stop_layer;
734 ++layer) {
735 num_ref_pics_[layer] = 0;
736 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
737 // When encoding a keyframe only the alt_fb_idx is used
738 // to specify which layer ends up in which buffer.
739 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
740 }
741 } else {
742 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
743 ++layer_idx) {
744 vpx_enc_frame_flags_t layer_flags = kAllFlags;
745 num_ref_pics_[layer_idx] = 0;
746 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
747 settings.layer[layer_idx].ref_buf2,
748 settings.layer[layer_idx].ref_buf3};
749
750 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
751 if (refs[ref_idx] == -1)
752 continue;
753
754 RTC_DCHECK_GE(refs[ref_idx], 0);
755 RTC_DCHECK_LE(refs[ref_idx], 7);
756 // Easier to remove flags from all flags rather than having to
757 // build the flags from 0.
758 switch (num_ref_pics_[layer_idx]) {
759 case 0: {
760 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
761 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
762 break;
763 }
764 case 1: {
765 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
766 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
767 break;
768 }
769 case 2: {
770 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
771 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
772 break;
773 }
774 }
775 // Make sure we don't reference a buffer that hasn't been
776 // used at all or hasn't been used since a keyframe.
777 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
778
779 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
780 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
781 num_ref_pics_[layer_idx]++;
782 }
783
784 bool upd_buf_same_as_a_ref = false;
785 if (settings.layer[layer_idx].upd_buf != -1) {
786 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
787 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
788 switch (ref_idx) {
789 case 0: {
790 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
791 break;
792 }
793 case 1: {
794 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
795 break;
796 }
797 case 2: {
798 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
799 break;
800 }
801 }
802 upd_buf_same_as_a_ref = true;
803 break;
804 }
805 }
806 if (!upd_buf_same_as_a_ref) {
807 // If we have three references and a buffer is specified to be
808 // updated, then that buffer must be the same as one of the
809 // three references.
810 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
811
812 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
813 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
814 }
815
816 int updated_buffer = settings.layer[layer_idx].upd_buf;
817 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
818 sf_conf.frame_flags[layer_idx] = layer_flags;
819 }
820 }
821 }
822 ++frames_encoded_;
823 return sf_conf;
824}
825
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000826int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000827 return WEBRTC_VIDEO_CODEC_OK;
828}
829
830int VP9EncoderImpl::RegisterEncodeCompleteCallback(
831 EncodedImageCallback* callback) {
832 encoded_complete_callback_ = callback;
833 return WEBRTC_VIDEO_CODEC_OK;
834}
835
Peter Boströmb7d9a972015-12-18 16:01:11 +0100836const char* VP9EncoderImpl::ImplementationName() const {
837 return "libvpx";
838}
839
Peter Boström12996152016-05-14 02:03:18 +0200840bool VP9Decoder::IsSupported() {
841 return true;
842}
843
Magnus Jedvert34c8e6b2017-11-13 13:02:16 +0000844VP9Decoder* VP9Decoder::Create() {
845 return new VP9DecoderImpl();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000846}
847
848VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700849 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000850 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700851 decoder_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000852 key_frame_required_(true) {
853 memset(&codec_, 0, sizeof(codec_));
854}
855
856VP9DecoderImpl::~VP9DecoderImpl() {
857 inited_ = true; // in order to do the actual release
858 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200859 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
860 if (num_buffers_in_use > 0) {
861 // The frame buffers are reference counted and frames are exposed after
862 // decoding. There may be valid usage cases where previous frames are still
863 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100864 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
865 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200866 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000867}
868
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000869int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
sprang3958ed82017-08-17 08:12:10 -0700870 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000871 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
872 }
873 int ret_val = Release();
874 if (ret_val < 0) {
875 return ret_val;
876 }
sprang3958ed82017-08-17 08:12:10 -0700877 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000878 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000879 }
philipelcce46fc2015-12-21 03:04:49 -0800880 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000881 // Setting number of threads to a constant value (1)
882 cfg.threads = 1;
883 cfg.h = cfg.w = 0; // set after decode
884 vpx_codec_flags_t flags = 0;
885 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
886 return WEBRTC_VIDEO_CODEC_MEMORY;
887 }
888 if (&codec_ != inst) {
889 // Save VideoCodec instance for later; mainly for duplicating the decoder.
890 codec_ = *inst;
891 }
Henrik Boström9695d852015-05-06 10:42:15 +0200892
893 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
894 return WEBRTC_VIDEO_CODEC_MEMORY;
895 }
896
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000897 inited_ = true;
898 // Always start with a complete key frame.
899 key_frame_required_ = true;
900 return WEBRTC_VIDEO_CODEC_OK;
901}
902
903int VP9DecoderImpl::Decode(const EncodedImage& input_image,
904 bool missing_frames,
905 const RTPFragmentationHeader* fragmentation,
906 const CodecSpecificInfo* codec_specific_info,
907 int64_t /*render_time_ms*/) {
908 if (!inited_) {
909 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
910 }
sprang3958ed82017-08-17 08:12:10 -0700911 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000912 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
913 }
914 // Always start with a complete key frame.
915 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200916 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000917 return WEBRTC_VIDEO_CODEC_ERROR;
918 // We have a key frame - is it complete?
919 if (input_image._completeFrame) {
920 key_frame_required_ = false;
921 } else {
922 return WEBRTC_VIDEO_CODEC_ERROR;
923 }
924 }
sprang3958ed82017-08-17 08:12:10 -0700925 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000926 vpx_image_t* img;
927 uint8_t* buffer = input_image._buffer;
928 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700929 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000930 }
Henrik Boström9695d852015-05-06 10:42:15 +0200931 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
932 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800933 if (vpx_codec_decode(decoder_, buffer,
934 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000935 VPX_DL_REALTIME)) {
936 return WEBRTC_VIDEO_CODEC_ERROR;
937 }
Henrik Boström9695d852015-05-06 10:42:15 +0200938 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
939 // It may be released by libvpx during future vpx_codec_decode or
940 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000941 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800942 int qp;
943 vpx_codec_err_t vpx_ret =
944 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
945 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
946 int ret =
947 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000948 if (ret != 0) {
949 return ret;
950 }
951 return WEBRTC_VIDEO_CODEC_OK;
952}
953
asapersson1490f7a2016-09-23 02:09:46 -0700954int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
955 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800956 int64_t ntp_time_ms,
957 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700958 if (img == nullptr) {
959 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000960 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
961 }
Henrik Boström9695d852015-05-06 10:42:15 +0200962
963 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800964 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200965 // vpx_codec_decode calls or vpx_codec_destroy).
966 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
967 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700968 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200969 // using a WrappedI420Buffer.
970 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
971 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800972 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
973 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
974 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
975 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200976 // WrappedI420Buffer's mechanism for allowing the release of its frame
977 // buffer is through a callback function. This is where we should
978 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800979 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200980
nisseca6d5d12016-06-17 05:03:04 -0700981 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
982 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -0700983 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -0700984
sakal7adadb12017-02-23 02:54:57 -0800985 decode_complete_callback_->Decoded(decoded_image, rtc::Optional<int32_t>(),
986 rtc::Optional<uint8_t>(qp));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000987 return WEBRTC_VIDEO_CODEC_OK;
988}
989
990int VP9DecoderImpl::RegisterDecodeCompleteCallback(
991 DecodedImageCallback* callback) {
992 decode_complete_callback_ = callback;
993 return WEBRTC_VIDEO_CODEC_OK;
994}
995
996int VP9DecoderImpl::Release() {
sprang3958ed82017-08-17 08:12:10 -0700997 if (decoder_ != nullptr) {
Henrik Boström9695d852015-05-06 10:42:15 +0200998 // When a codec is destroyed libvpx will release any buffers of
999 // |frame_buffer_pool_| it is currently using.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001000 if (vpx_codec_destroy(decoder_)) {
1001 return WEBRTC_VIDEO_CODEC_MEMORY;
1002 }
1003 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001004 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001005 }
Henrik Boström9695d852015-05-06 10:42:15 +02001006 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1007 // still referenced externally are deleted once fully released, not returning
1008 // to the pool.
1009 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001010 inited_ = false;
1011 return WEBRTC_VIDEO_CODEC_OK;
1012}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001013
1014const char* VP9DecoderImpl::ImplementationName() const {
1015 return "libvpx";
1016}
1017
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001018} // namespace webrtc