blob: c54fda53b7bb6a7487ed1900c0f53cb489ee59ec [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) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000104 if (vpx_codec_destroy(encoder_)) {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100105 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000106 }
107 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700108 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000109 }
sprang3958ed82017-08-17 08:12:10 -0700110 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000111 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700112 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 }
sprang3958ed82017-08-17 08:12:10 -0700114 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000115 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700116 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000117 }
118 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100119 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000120}
121
sprangce4aef12015-11-02 07:23:20 -0800122bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
123 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
124 // (i.e. bitrates) were explicitly configured.
125 return num_spatial_layers_ > 1 &&
126 codec_.spatialLayers[0].target_bitrate_bps > 0;
127}
128
asaperssona9455ab2015-07-31 06:10:09 -0700129bool VP9EncoderImpl::SetSvcRates() {
asaperssona9455ab2015-07-31 06:10:09 -0700130 uint8_t i = 0;
131
sprangce4aef12015-11-02 07:23:20 -0800132 if (ExplicitlyConfiguredSpatialLayers()) {
133 if (num_temporal_layers_ > 1) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100134 RTC_LOG(LS_ERROR) << "Multiple temporal layers when manually specifying "
135 "spatial layers not implemented yet!";
asaperssona9455ab2015-07-31 06:10:09 -0700136 return false;
137 }
sprangce4aef12015-11-02 07:23:20 -0800138 int total_bitrate_bps = 0;
139 for (i = 0; i < num_spatial_layers_; ++i)
140 total_bitrate_bps += codec_.spatialLayers[i].target_bitrate_bps;
141 // If total bitrate differs now from what has been specified at the
142 // beginning, update the bitrates in the same ratio as before.
143 for (i = 0; i < num_spatial_layers_; ++i) {
144 config_->ss_target_bitrate[i] = config_->layer_target_bitrate[i] =
145 static_cast<int>(static_cast<int64_t>(config_->rc_target_bitrate) *
146 codec_.spatialLayers[i].target_bitrate_bps /
147 total_bitrate_bps);
148 }
149 } else {
150 float rate_ratio[VPX_MAX_LAYERS] = {0};
151 float total = 0;
asaperssona9455ab2015-07-31 06:10:09 -0700152
sprangce4aef12015-11-02 07:23:20 -0800153 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800154 if (svc_params_.scaling_factor_num[i] <= 0 ||
155 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100156 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800157 return false;
158 }
159 rate_ratio[i] =
johannkoenig8225c402017-01-26 13:23:44 -0800160 static_cast<float>(svc_params_.scaling_factor_num[i]) /
161 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800162 total += rate_ratio[i];
163 }
164
165 for (i = 0; i < num_spatial_layers_; ++i) {
166 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
167 config_->rc_target_bitrate * rate_ratio[i] / total);
168 if (num_temporal_layers_ == 1) {
169 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
170 } else if (num_temporal_layers_ == 2) {
171 config_->layer_target_bitrate[i * num_temporal_layers_] =
172 config_->ss_target_bitrate[i] * 2 / 3;
173 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
174 config_->ss_target_bitrate[i];
175 } else if (num_temporal_layers_ == 3) {
176 config_->layer_target_bitrate[i * num_temporal_layers_] =
177 config_->ss_target_bitrate[i] / 2;
178 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
179 config_->layer_target_bitrate[i * num_temporal_layers_] +
180 (config_->ss_target_bitrate[i] / 4);
181 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
182 config_->ss_target_bitrate[i];
183 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100184 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
185 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800186 return false;
187 }
asaperssona9455ab2015-07-31 06:10:09 -0700188 }
189 }
190
191 // For now, temporal layers only supported when having one spatial layer.
192 if (num_spatial_layers_ == 1) {
193 for (i = 0; i < num_temporal_layers_; ++i) {
194 config_->ts_target_bitrate[i] = config_->layer_target_bitrate[i];
195 }
196 }
197
198 return true;
199}
200
Erik Språng08127a92016-11-16 16:41:30 +0100201int VP9EncoderImpl::SetRateAllocation(
202 const BitrateAllocation& bitrate_allocation,
203 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000204 if (!inited_) {
205 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
206 }
207 if (encoder_->err) {
208 return WEBRTC_VIDEO_CODEC_ERROR;
209 }
Erik Språng08127a92016-11-16 16:41:30 +0100210 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000211 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
212 }
213 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100214 if (codec_.maxBitrate > 0 &&
215 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
216 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000217 }
Erik Språng08127a92016-11-16 16:41:30 +0100218
219 // TODO(sprang): Actually use BitrateAllocation layer info.
220 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
221 codec_.maxFramerate = frame_rate;
222 spatial_layer_->ConfigureBitrate(bitrate_allocation.get_sum_kbps(), 0);
asaperssona9455ab2015-07-31 06:10:09 -0700223
224 if (!SetSvcRates()) {
225 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
226 }
227
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000228 // Update encoder context
229 if (vpx_codec_enc_config_set(encoder_, config_)) {
230 return WEBRTC_VIDEO_CODEC_ERROR;
231 }
232 return WEBRTC_VIDEO_CODEC_OK;
233}
234
235int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
236 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000237 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700238 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000239 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
240 }
241 if (inst->maxFramerate < 1) {
242 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
243 }
244 // Allow zero to represent an unspecified maxBitRate
245 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
246 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
247 }
248 if (inst->width < 1 || inst->height < 1) {
249 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
250 }
251 if (number_of_cores < 1) {
252 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
253 }
hta257dc392016-10-25 09:05:06 -0700254 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700255 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
256 }
ilnik2a8c2f52017-02-15 02:23:28 -0800257 // libvpx probably does not support more than 3 spatial layers.
258 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700259 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
260 }
philipelcfc319b2015-11-10 07:17:23 -0800261
asapersson86956de2016-01-26 01:05:20 -0800262 int ret_val = Release();
263 if (ret_val < 0) {
264 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000265 }
sprang3958ed82017-08-17 08:12:10 -0700266 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000267 encoder_ = new vpx_codec_ctx_t;
268 }
sprang3958ed82017-08-17 08:12:10 -0700269 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000270 config_ = new vpx_codec_enc_cfg_t;
271 }
272 timestamp_ = 0;
273 if (&codec_ != inst) {
274 codec_ = *inst;
275 }
asaperssona9455ab2015-07-31 06:10:09 -0700276
hta257dc392016-10-25 09:05:06 -0700277 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
278 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700279 if (num_temporal_layers_ == 0)
280 num_temporal_layers_ = 1;
281
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000282 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700283 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800284 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000285 }
nisseeb44b392017-04-28 07:18:05 -0700286 encoded_image_._size =
287 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000288 encoded_image_._buffer = new uint8_t[encoded_image_._size];
289 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700290 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000291 // pointer will be set in encode. Setting align to 1, as it is meaningless
292 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700293 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
294 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000295 // Populate encoder configuration with default values.
296 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
297 return WEBRTC_VIDEO_CODEC_ERROR;
298 }
299 config_->g_w = codec_.width;
300 config_->g_h = codec_.height;
301 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
asapersson15dcb382017-06-08 02:55:08 -0700302 config_->g_error_resilient = inst->VP9().resilienceOn ? 1 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000303 // Setting the time base of the codec.
304 config_->g_timebase.num = 1;
305 config_->g_timebase.den = 90000;
306 config_->g_lag_in_frames = 0; // 0- no frame lagging
307 config_->g_threads = 1;
308 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700309 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000310 config_->rc_end_usage = VPX_CBR;
311 config_->g_pass = VPX_RC_ONE_PASS;
312 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000313 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000314 config_->rc_undershoot_pct = 50;
315 config_->rc_overshoot_pct = 50;
316 config_->rc_buf_initial_sz = 500;
317 config_->rc_buf_optimal_sz = 600;
318 config_->rc_buf_sz = 1000;
319 // Set the maximum target size of any key-frame.
320 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700321 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000322 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700323 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100324 // Needs to be set (in svc mode) to get correct periodic key frame interval
325 // (will have no effect in non-svc).
326 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000327 } else {
328 config_->kf_mode = VPX_KF_DISABLED;
329 }
hta257dc392016-10-25 09:05:06 -0700330 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000331 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800332 config_->g_threads =
333 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700334
Marco6e89b252015-07-07 14:40:38 -0700335 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700336
337 // TODO(asapersson): Check configuration of temporal switch up and increase
338 // pattern length.
hta257dc392016-10-25 09:05:06 -0700339 is_flexible_mode_ = inst->VP9().flexibleMode;
philipelcfc319b2015-11-10 07:17:23 -0800340 if (is_flexible_mode_) {
341 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS;
342 config_->ts_number_layers = num_temporal_layers_;
343 if (codec_.mode == kScreensharing)
344 spatial_layer_->ConfigureBitrate(inst->startBitrate, 0);
345 } else if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700346 gof_.SetGofInfoVP9(kTemporalStructureMode1);
347 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
348 config_->ts_number_layers = 1;
349 config_->ts_rate_decimator[0] = 1;
350 config_->ts_periodicity = 1;
351 config_->ts_layer_id[0] = 0;
352 } else if (num_temporal_layers_ == 2) {
353 gof_.SetGofInfoVP9(kTemporalStructureMode2);
354 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
355 config_->ts_number_layers = 2;
356 config_->ts_rate_decimator[0] = 2;
357 config_->ts_rate_decimator[1] = 1;
358 config_->ts_periodicity = 2;
359 config_->ts_layer_id[0] = 0;
360 config_->ts_layer_id[1] = 1;
361 } else if (num_temporal_layers_ == 3) {
362 gof_.SetGofInfoVP9(kTemporalStructureMode3);
363 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
364 config_->ts_number_layers = 3;
365 config_->ts_rate_decimator[0] = 4;
366 config_->ts_rate_decimator[1] = 2;
367 config_->ts_rate_decimator[2] = 1;
368 config_->ts_periodicity = 4;
369 config_->ts_layer_id[0] = 0;
370 config_->ts_layer_id[1] = 2;
371 config_->ts_layer_id[2] = 1;
372 config_->ts_layer_id[3] = 2;
373 } else {
374 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
375 }
376
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000377 return InitAndSetControlSettings(inst);
378}
379
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000380int VP9EncoderImpl::NumberOfThreads(int width,
381 int height,
382 int number_of_cores) {
383 // Keep the number of encoder threads equal to the possible number of column
384 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
385 if (width * height >= 1280 * 720 && number_of_cores > 4) {
386 return 4;
jianj23173a32017-07-12 16:11:09 -0700387 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000388 return 2;
389 } else {
Jerome Jiang831af372017-12-05 10:44:35 -0800390 // Use 2 threads for low res on ARM.
391#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
392 defined(WEBRTC_ANDROID)
393 if (width * height >= 320 * 180 && number_of_cores > 2) {
394 return 2;
395 }
396#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000397 // 1 thread less than VGA.
398 return 1;
399 }
400}
401
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000402int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100403 // Set QP-min/max per spatial and temporal layer.
404 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
405 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800406 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
407 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100408 }
asaperssona9455ab2015-07-31 06:10:09 -0700409 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800410 if (ExplicitlyConfiguredSpatialLayers()) {
411 for (int i = 0; i < num_spatial_layers_; ++i) {
412 const auto& layer = codec_.spatialLayers[i];
johannkoenig8225c402017-01-26 13:23:44 -0800413 svc_params_.scaling_factor_num[i] = layer.scaling_factor_num;
414 svc_params_.scaling_factor_den[i] = layer.scaling_factor_den;
sprangce4aef12015-11-02 07:23:20 -0800415 }
416 } else {
417 int scaling_factor_num = 256;
418 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800419 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800420 svc_params_.scaling_factor_num[i] = scaling_factor_num;
421 svc_params_.scaling_factor_den[i] = 256;
philipelcfc319b2015-11-10 07:17:23 -0800422 if (codec_.mode != kScreensharing)
423 scaling_factor_num /= 2;
sprangce4aef12015-11-02 07:23:20 -0800424 }
asaperssona9455ab2015-07-31 06:10:09 -0700425 }
426
427 if (!SetSvcRates()) {
428 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
429 }
430
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000431 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
432 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
433 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000434 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
435 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
436 rc_max_intra_target_);
437 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700438 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700439
jianj822e5932017-07-12 16:09:58 -0700440 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700441 vpx_codec_control(
442 encoder_, VP9E_SET_SVC,
443 (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) ? 1 : 0);
444 if (num_temporal_layers_ > 1 || num_spatial_layers_ > 1) {
445 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS,
johannkoenig8225c402017-01-26 13:23:44 -0800446 &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700447 }
448 // Register callback for getting each spatial layer.
449 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800450 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
451 reinterpret_cast<void*>(this)};
452 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
453 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700454
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000455 // Control function to set the number of column tiles in encoding a frame, in
456 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
457 // The number tile columns will be capped by the encoder based on image size
458 // (minimum width of tile column is 256 pixels, maximum is 4096).
459 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700460
461 // Turn on row-based multithreading.
462 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700463
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700464#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
465 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700466 // Do not enable the denoiser on ARM since optimization is pending.
467 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000468 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700469 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000470#endif
jianj6bf57e32017-06-05 13:43:49 -0700471
ivica242d6382015-09-04 06:13:23 -0700472 if (codec_.mode == kScreensharing) {
473 // Adjust internal parameters to screen content.
474 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700475 }
Marco2520e722015-09-16 14:05:00 -0700476 // Enable encoder skip of static/low content blocks.
477 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000478 inited_ = true;
479 return WEBRTC_VIDEO_CODEC_OK;
480}
481
482uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
483 // Set max to the optimal buffer level (normalized by target BR),
484 // and scaled by a scale_par.
485 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
486 // This value is presented in percentage of perFrameBw:
487 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
488 // The target in % is as follows:
489 float scale_par = 0.5;
490 uint32_t target_pct =
491 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
492 // Don't go below 3 times the per frame bandwidth.
493 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800494 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000495}
496
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700497int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000498 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700499 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000500 if (!inited_) {
501 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
502 }
sprang3958ed82017-08-17 08:12:10 -0700503 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000504 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
505 }
Peter Boström49e196a2015-10-23 15:58:18 +0200506 FrameType frame_type = kVideoFrameDelta;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000507 // We only support one stream at the moment.
508 if (frame_types && frame_types->size() > 0) {
509 frame_type = (*frame_types)[0];
510 }
kwiberg352444f2016-11-28 15:58:53 -0800511 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
512 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700513
514 // Set input image for use in the callback.
515 // This was necessary since you need some information from input_image.
516 // You can save only the necessary information (such as timestamp) instead of
517 // doing this.
518 input_image_ = &input_image;
519
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000520 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
521 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000522 // Image in vpx_image_t format.
523 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000524 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
525 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
526 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
527 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
528 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
529 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000530
philipelcfc319b2015-11-10 07:17:23 -0800531 vpx_enc_frame_flags_t flags = 0;
Peter Boström49e196a2015-10-23 15:58:18 +0200532 bool send_keyframe = (frame_type == kVideoFrameKey);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000533 if (send_keyframe) {
534 // Key frame request from caller.
535 flags = VPX_EFLAG_FORCE_KF;
536 }
philipelcfc319b2015-11-10 07:17:23 -0800537
538 if (is_flexible_mode_) {
539 SuperFrameRefSettings settings;
540
541 // These structs are copied when calling vpx_codec_control,
542 // therefore it is ok for them to go out of scope.
543 vpx_svc_ref_frame_config enc_layer_conf;
544 vpx_svc_layer_id layer_id;
545
546 if (codec_.mode == kRealtimeVideo) {
547 // Real time video not yet implemented in flexible mode.
548 RTC_NOTREACHED();
549 } else {
550 settings = spatial_layer_->GetSuperFrameSettings(input_image.timestamp(),
551 send_keyframe);
552 }
553 enc_layer_conf = GenerateRefsAndFlags(settings);
554 layer_id.temporal_layer_id = 0;
555 layer_id.spatial_layer_id = settings.start_layer;
556 vpx_codec_control(encoder_, VP9E_SET_SVC_LAYER_ID, &layer_id);
557 vpx_codec_control(encoder_, VP9E_SET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
558 }
559
sprang3958ed82017-08-17 08:12:10 -0700560 RTC_CHECK_GT(codec_.maxFramerate, 0);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000561 uint32_t duration = 90000 / codec_.maxFramerate;
562 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
563 VPX_DL_REALTIME)) {
564 return WEBRTC_VIDEO_CODEC_ERROR;
565 }
566 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700567
568 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000569}
570
571void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800572 const vpx_codec_cx_pkt& pkt,
573 uint32_t timestamp) {
sprang3958ed82017-08-17 08:12:10 -0700574 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000575 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700576 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800577 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Åsa Perssonff24c042015-12-04 10:58:08 +0100578 // TODO(asapersson): Set correct value.
asaperssona9455ab2015-07-31 06:10:09 -0700579 vp9_info->inter_pic_predicted =
580 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? false : true;
hta257dc392016-10-25 09:05:06 -0700581 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
582 vp9_info->ss_data_available =
583 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
584 ? true
585 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700586
587 vpx_svc_layer_id_t layer_id = {0};
588 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
589
sprang3958ed82017-08-17 08:12:10 -0700590 RTC_CHECK_GT(num_temporal_layers_, 0);
591 RTC_CHECK_GT(num_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700592 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700593 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700594 vp9_info->temporal_idx = kNoTemporalIdx;
595 } else {
596 vp9_info->temporal_idx = layer_id.temporal_layer_id;
597 }
598 if (num_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700599 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700600 vp9_info->spatial_idx = kNoSpatialIdx;
601 } else {
602 vp9_info->spatial_idx = layer_id.spatial_layer_id;
603 }
604 if (layer_id.spatial_layer_id != 0) {
605 vp9_info->ss_data_available = false;
606 }
607
asaperssona9455ab2015-07-31 06:10:09 -0700608 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800609 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700610
philipelcfc319b2015-11-10 07:17:23 -0800611 bool is_first_frame = false;
612 if (is_flexible_mode_) {
613 is_first_frame =
614 layer_id.spatial_layer_id == spatial_layer_->GetStartLayer();
615 } else {
616 is_first_frame = layer_id.spatial_layer_id == 0;
617 }
618
619 if (is_first_frame) {
asaperssona9455ab2015-07-31 06:10:09 -0700620 picture_id_ = (picture_id_ + 1) & 0x7FFF;
621 // TODO(asapersson): this info has to be obtained from the encoder.
622 vp9_info->inter_layer_predicted = false;
asapersson00ac85e2015-11-11 05:30:48 -0800623 ++frames_since_kf_;
asaperssona9455ab2015-07-31 06:10:09 -0700624 } else {
625 // TODO(asapersson): this info has to be obtained from the encoder.
626 vp9_info->inter_layer_predicted = true;
627 }
628
asapersson00ac85e2015-11-11 05:30:48 -0800629 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
630 frames_since_kf_ = 0;
631 }
632
asaperssona9455ab2015-07-31 06:10:09 -0700633 vp9_info->picture_id = picture_id_;
634
635 if (!vp9_info->flexible_mode) {
636 if (layer_id.temporal_layer_id == 0 && layer_id.spatial_layer_id == 0) {
637 tl0_pic_idx_++;
638 }
639 vp9_info->tl0_pic_idx = tl0_pic_idx_;
640 }
641
ivica7f6a6fc2015-09-08 02:40:29 -0700642 // Always populate this, so that the packetizer can properly set the marker
643 // bit.
644 vp9_info->num_spatial_layers = num_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800645
646 vp9_info->num_ref_pics = 0;
647 if (vp9_info->flexible_mode) {
648 vp9_info->gof_idx = kNoGofIdx;
649 vp9_info->num_ref_pics = num_ref_pics_[layer_id.spatial_layer_id];
650 for (int i = 0; i < num_ref_pics_[layer_id.spatial_layer_id]; ++i) {
651 vp9_info->p_diff[i] = p_diff_[layer_id.spatial_layer_id][i];
652 }
653 } else {
654 vp9_info->gof_idx =
655 static_cast<uint8_t>(frames_since_kf_ % gof_.num_frames_in_gof);
asapersson00ac85e2015-11-11 05:30:48 -0800656 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
philipelcfc319b2015-11-10 07:17:23 -0800657 }
philipelcfc319b2015-11-10 07:17:23 -0800658
asaperssona9455ab2015-07-31 06:10:09 -0700659 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700660 vp9_info->spatial_layer_resolution_present = true;
661 for (size_t i = 0; i < vp9_info->num_spatial_layers; ++i) {
662 vp9_info->width[i] = codec_.width *
johannkoenig8225c402017-01-26 13:23:44 -0800663 svc_params_.scaling_factor_num[i] /
664 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700665 vp9_info->height[i] = codec_.height *
johannkoenig8225c402017-01-26 13:23:44 -0800666 svc_params_.scaling_factor_num[i] /
667 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700668 }
669 if (!vp9_info->flexible_mode) {
670 vp9_info->gof.CopyGofInfoVP9(gof_);
671 }
672 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000673}
674
asaperssona9455ab2015-07-31 06:10:09 -0700675int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800676 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700677
asaperssond9f641e2016-01-21 01:11:35 -0800678 if (pkt->data.frame.sz > encoded_image_._size) {
679 delete[] encoded_image_._buffer;
680 encoded_image_._size = pkt->data.frame.sz;
681 encoded_image_._buffer = new uint8_t[encoded_image_._size];
682 }
asapersson86956de2016-01-26 01:05:20 -0800683 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
684 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800685
asapersson86956de2016-01-26 01:05:20 -0800686 // No data partitioning in VP9, so 1 partition only.
687 int part_idx = 0;
688 RTPFragmentationHeader frag_info;
689 frag_info.VerifyAndAllocateFragmentationHeader(1);
690 frag_info.fragmentationOffset[part_idx] = 0;
691 frag_info.fragmentationLength[part_idx] = pkt->data.frame.sz;
asaperssona9455ab2015-07-31 06:10:09 -0700692 frag_info.fragmentationPlType[part_idx] = 0;
693 frag_info.fragmentationTimeDiff[part_idx] = 0;
philipelcfc319b2015-11-10 07:17:23 -0800694
695 vpx_svc_layer_id_t layer_id = {0};
696 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
697 if (is_flexible_mode_ && codec_.mode == kScreensharing)
698 spatial_layer_->LayerFrameEncoded(
699 static_cast<unsigned int>(encoded_image_._length),
700 layer_id.spatial_layer_id);
701
asaperssona9455ab2015-07-31 06:10:09 -0700702 // End of frame.
703 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800704 encoded_image_._frameType = kVideoFrameDelta;
asaperssona9455ab2015-07-31 06:10:09 -0700705 if (pkt->data.frame.flags & VPX_FRAME_IS_KEY) {
Peter Boström49e196a2015-10-23 15:58:18 +0200706 encoded_image_._frameType = kVideoFrameKey;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000707 }
asapersson86956de2016-01-26 01:05:20 -0800708 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
709
710 CodecSpecificInfo codec_specific;
asaperssona9455ab2015-07-31 06:10:09 -0700711 PopulateCodecSpecific(&codec_specific, *pkt, input_image_->timestamp());
712
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000713 if (encoded_image_._length > 0) {
714 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
asaperssona9455ab2015-07-31 06:10:09 -0700715 encoded_image_._timeStamp = input_image_->timestamp();
716 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
Perba7dc722016-04-19 15:01:23 +0200717 encoded_image_.rotation_ = input_image_->rotation();
ilnik00d802b2017-04-11 10:34:31 -0700718 encoded_image_.content_type_ = (codec_.mode == kScreensharing)
719 ? VideoContentType::SCREENSHARE
720 : VideoContentType::UNSPECIFIED;
Sergey Silkin956b3062018-02-01 10:43:49 +0100721 encoded_image_._encodedHeight =
722 pkt->data.frame.height[layer_id.spatial_layer_id];
723 encoded_image_._encodedWidth =
724 pkt->data.frame.width[layer_id.spatial_layer_id];
sprangba050a62017-08-18 02:51:12 -0700725 encoded_image_.timing_.flags = TimingFrameFlags::kInvalid;
asapersson5265fed2016-04-18 02:58:47 -0700726 int qp = -1;
727 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
728 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700729
sergeyu2cb155a2016-11-04 11:39:29 -0700730 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific,
731 &frag_info);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000732 }
733 return WEBRTC_VIDEO_CODEC_OK;
734}
735
philipelcfc319b2015-11-10 07:17:23 -0800736vpx_svc_ref_frame_config VP9EncoderImpl::GenerateRefsAndFlags(
737 const SuperFrameRefSettings& settings) {
738 static const vpx_enc_frame_flags_t kAllFlags =
739 VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_LAST |
740 VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF;
741 vpx_svc_ref_frame_config sf_conf = {};
742 if (settings.is_keyframe) {
743 // Used later on to make sure we don't make any invalid references.
744 memset(buffer_updated_at_frame_, -1, sizeof(buffer_updated_at_frame_));
745 for (int layer = settings.start_layer; layer <= settings.stop_layer;
746 ++layer) {
747 num_ref_pics_[layer] = 0;
748 buffer_updated_at_frame_[settings.layer[layer].upd_buf] = frames_encoded_;
749 // When encoding a keyframe only the alt_fb_idx is used
750 // to specify which layer ends up in which buffer.
751 sf_conf.alt_fb_idx[layer] = settings.layer[layer].upd_buf;
752 }
753 } else {
754 for (int layer_idx = settings.start_layer; layer_idx <= settings.stop_layer;
755 ++layer_idx) {
756 vpx_enc_frame_flags_t layer_flags = kAllFlags;
757 num_ref_pics_[layer_idx] = 0;
758 int8_t refs[3] = {settings.layer[layer_idx].ref_buf1,
759 settings.layer[layer_idx].ref_buf2,
760 settings.layer[layer_idx].ref_buf3};
761
762 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
763 if (refs[ref_idx] == -1)
764 continue;
765
766 RTC_DCHECK_GE(refs[ref_idx], 0);
767 RTC_DCHECK_LE(refs[ref_idx], 7);
768 // Easier to remove flags from all flags rather than having to
769 // build the flags from 0.
770 switch (num_ref_pics_[layer_idx]) {
771 case 0: {
772 sf_conf.lst_fb_idx[layer_idx] = refs[ref_idx];
773 layer_flags &= ~VP8_EFLAG_NO_REF_LAST;
774 break;
775 }
776 case 1: {
777 sf_conf.gld_fb_idx[layer_idx] = refs[ref_idx];
778 layer_flags &= ~VP8_EFLAG_NO_REF_GF;
779 break;
780 }
781 case 2: {
782 sf_conf.alt_fb_idx[layer_idx] = refs[ref_idx];
783 layer_flags &= ~VP8_EFLAG_NO_REF_ARF;
784 break;
785 }
786 }
787 // Make sure we don't reference a buffer that hasn't been
788 // used at all or hasn't been used since a keyframe.
789 RTC_DCHECK_NE(buffer_updated_at_frame_[refs[ref_idx]], -1);
790
791 p_diff_[layer_idx][num_ref_pics_[layer_idx]] =
792 frames_encoded_ - buffer_updated_at_frame_[refs[ref_idx]];
793 num_ref_pics_[layer_idx]++;
794 }
795
796 bool upd_buf_same_as_a_ref = false;
797 if (settings.layer[layer_idx].upd_buf != -1) {
798 for (unsigned int ref_idx = 0; ref_idx < kMaxVp9RefPics; ++ref_idx) {
799 if (settings.layer[layer_idx].upd_buf == refs[ref_idx]) {
800 switch (ref_idx) {
801 case 0: {
802 layer_flags &= ~VP8_EFLAG_NO_UPD_LAST;
803 break;
804 }
805 case 1: {
806 layer_flags &= ~VP8_EFLAG_NO_UPD_GF;
807 break;
808 }
809 case 2: {
810 layer_flags &= ~VP8_EFLAG_NO_UPD_ARF;
811 break;
812 }
813 }
814 upd_buf_same_as_a_ref = true;
815 break;
816 }
817 }
818 if (!upd_buf_same_as_a_ref) {
819 // If we have three references and a buffer is specified to be
820 // updated, then that buffer must be the same as one of the
821 // three references.
822 RTC_CHECK_LT(num_ref_pics_[layer_idx], kMaxVp9RefPics);
823
824 sf_conf.alt_fb_idx[layer_idx] = settings.layer[layer_idx].upd_buf;
825 layer_flags ^= VP8_EFLAG_NO_UPD_ARF;
826 }
827
828 int updated_buffer = settings.layer[layer_idx].upd_buf;
829 buffer_updated_at_frame_[updated_buffer] = frames_encoded_;
830 sf_conf.frame_flags[layer_idx] = layer_flags;
831 }
832 }
833 }
834 ++frames_encoded_;
835 return sf_conf;
836}
837
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000838int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000839 return WEBRTC_VIDEO_CODEC_OK;
840}
841
842int VP9EncoderImpl::RegisterEncodeCompleteCallback(
843 EncodedImageCallback* callback) {
844 encoded_complete_callback_ = callback;
845 return WEBRTC_VIDEO_CODEC_OK;
846}
847
Peter Boströmb7d9a972015-12-18 16:01:11 +0100848const char* VP9EncoderImpl::ImplementationName() const {
849 return "libvpx";
850}
851
Peter Boström12996152016-05-14 02:03:18 +0200852bool VP9Decoder::IsSupported() {
853 return true;
854}
855
Magnus Jedvert46a27652017-11-13 14:10:02 +0100856std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
857 return rtc::MakeUnique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000858}
859
860VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700861 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000862 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700863 decoder_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000864 key_frame_required_(true) {
865 memset(&codec_, 0, sizeof(codec_));
866}
867
868VP9DecoderImpl::~VP9DecoderImpl() {
869 inited_ = true; // in order to do the actual release
870 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200871 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
872 if (num_buffers_in_use > 0) {
873 // The frame buffers are reference counted and frames are exposed after
874 // decoding. There may be valid usage cases where previous frames are still
875 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100876 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
877 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200878 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000879}
880
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000881int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
sprang3958ed82017-08-17 08:12:10 -0700882 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000883 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
884 }
885 int ret_val = Release();
886 if (ret_val < 0) {
887 return ret_val;
888 }
sprang3958ed82017-08-17 08:12:10 -0700889 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +0000890 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000891 }
philipelcce46fc2015-12-21 03:04:49 -0800892 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000893 // Setting number of threads to a constant value (1)
894 cfg.threads = 1;
895 cfg.h = cfg.w = 0; // set after decode
896 vpx_codec_flags_t flags = 0;
897 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
898 return WEBRTC_VIDEO_CODEC_MEMORY;
899 }
900 if (&codec_ != inst) {
901 // Save VideoCodec instance for later; mainly for duplicating the decoder.
902 codec_ = *inst;
903 }
Henrik Boström9695d852015-05-06 10:42:15 +0200904
905 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
906 return WEBRTC_VIDEO_CODEC_MEMORY;
907 }
908
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000909 inited_ = true;
910 // Always start with a complete key frame.
911 key_frame_required_ = true;
912 return WEBRTC_VIDEO_CODEC_OK;
913}
914
915int VP9DecoderImpl::Decode(const EncodedImage& input_image,
916 bool missing_frames,
917 const RTPFragmentationHeader* fragmentation,
918 const CodecSpecificInfo* codec_specific_info,
919 int64_t /*render_time_ms*/) {
920 if (!inited_) {
921 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
922 }
sprang3958ed82017-08-17 08:12:10 -0700923 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000924 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
925 }
926 // Always start with a complete key frame.
927 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +0200928 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000929 return WEBRTC_VIDEO_CODEC_ERROR;
930 // We have a key frame - is it complete?
931 if (input_image._completeFrame) {
932 key_frame_required_ = false;
933 } else {
934 return WEBRTC_VIDEO_CODEC_ERROR;
935 }
936 }
sprang3958ed82017-08-17 08:12:10 -0700937 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000938 vpx_image_t* img;
939 uint8_t* buffer = input_image._buffer;
940 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -0700941 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000942 }
Henrik Boström9695d852015-05-06 10:42:15 +0200943 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
944 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -0800945 if (vpx_codec_decode(decoder_, buffer,
946 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000947 VPX_DL_REALTIME)) {
948 return WEBRTC_VIDEO_CODEC_ERROR;
949 }
Henrik Boström9695d852015-05-06 10:42:15 +0200950 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
951 // It may be released by libvpx during future vpx_codec_decode or
952 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000953 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -0800954 int qp;
955 vpx_codec_err_t vpx_ret =
956 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
957 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
958 int ret =
959 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000960 if (ret != 0) {
961 return ret;
962 }
963 return WEBRTC_VIDEO_CODEC_OK;
964}
965
asapersson1490f7a2016-09-23 02:09:46 -0700966int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
967 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -0800968 int64_t ntp_time_ms,
969 int qp) {
sprang3958ed82017-08-17 08:12:10 -0700970 if (img == nullptr) {
971 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000972 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
973 }
Henrik Boström9695d852015-05-06 10:42:15 +0200974
975 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -0800976 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +0200977 // vpx_codec_decode calls or vpx_codec_destroy).
978 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
979 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700980 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +0200981 // using a WrappedI420Buffer.
982 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
983 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -0800984 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
985 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
986 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
987 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +0200988 // WrappedI420Buffer's mechanism for allowing the release of its frame
989 // buffer is through a callback function. This is where we should
990 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -0800991 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +0200992
nisseca6d5d12016-06-17 05:03:04 -0700993 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
994 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -0700995 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -0700996
Oskar Sundbom6bd39022017-11-16 10:54:49 +0100997 decode_complete_callback_->Decoded(decoded_image, rtc::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000998 return WEBRTC_VIDEO_CODEC_OK;
999}
1000
1001int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1002 DecodedImageCallback* callback) {
1003 decode_complete_callback_ = callback;
1004 return WEBRTC_VIDEO_CODEC_OK;
1005}
1006
1007int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001008 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1009
sprang3958ed82017-08-17 08:12:10 -07001010 if (decoder_ != nullptr) {
Henrik Boström9695d852015-05-06 10:42:15 +02001011 // When a codec is destroyed libvpx will release any buffers of
1012 // |frame_buffer_pool_| it is currently using.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001013 if (vpx_codec_destroy(decoder_)) {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001014 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001015 }
1016 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001017 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001018 }
Henrik Boström9695d852015-05-06 10:42:15 +02001019 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1020 // still referenced externally are deleted once fully released, not returning
1021 // to the pool.
1022 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001023 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001024 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001025}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001026
1027const char* VP9DecoderImpl::ImplementationName() const {
1028 return "libvpx";
1029}
1030
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001031} // namespace webrtc