blob: 2877ecee19637121d1c3d4d378adf964ed9ed954 [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
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020014#include <algorithm>
Sergey Silkind45b3452018-05-31 16:00:24 +020015#include <limits>
marpan@webrtc.org5b883172014-11-01 06:10:48 +000016#include <vector>
17
marpan@webrtc.org5b883172014-11-01 06:10:48 +000018#include "vpx/vp8cx.h"
19#include "vpx/vp8dx.h"
Yves Gerey665174f2018-06-19 15:03:05 +020020#include "vpx/vpx_decoder.h"
21#include "vpx/vpx_encoder.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000022
Karl Wiberg918f50c2018-07-05 11:40:33 +020023#include "absl/memory/memory.h"
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"
Sergey Silkind902d582018-05-18 17:31:19 +020026#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020027#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020028#include "rtc_base/checks.h"
29#include "rtc_base/keep_ref_until_done.h"
30#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020031#include "rtc_base/timeutils.h"
32#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000033
34namespace webrtc {
35
Sergey Silkind902d582018-05-18 17:31:19 +020036namespace {
37const float kMaxScreenSharingFramerateFps = 5.0f;
38}
39
Marco6e89b252015-07-07 14:40:38 -070040// Only positive speeds, range for real-time coding currently is: 5 - 8.
41// Lower means slower/better quality, higher means fastest/lower quality.
42int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070043#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080044 return 8;
45#else
Marco6e89b252015-07-07 14:40:38 -070046 // For smaller resolutions, use lower speed setting (get some coding gain at
47 // the cost of increased encoding complexity).
48 if (width * height <= 352 * 288)
49 return 5;
50 else
51 return 7;
Marco002f0d02015-12-17 09:49:31 -080052#endif
Marco6e89b252015-07-07 14:40:38 -070053}
54
Emircan Uysaler98badbc2018-06-28 10:59:02 -070055std::vector<SdpVideoFormat> SupportedVP9Codecs() {
56 return {SdpVideoFormat(
57 cricket::kVp9CodecName,
58 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile0)}})};
Peter Boström12996152016-05-14 02:03:18 +020059}
60
Magnus Jedvert46a27652017-11-13 14:10:02 +010061std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +020062 return absl::make_unique<VP9EncoderImpl>(cricket::VideoCodec());
Emircan Uysaler98badbc2018-06-28 10:59:02 -070063}
64
65std::unique_ptr<VP9Encoder> VP9Encoder::Create(
66 const cricket::VideoCodec& codec) {
Karl Wiberg918f50c2018-07-05 11:40:33 +020067 return absl::make_unique<VP9EncoderImpl>(codec);
marpan@webrtc.org5b883172014-11-01 06:10:48 +000068}
69
asaperssona9455ab2015-07-31 06:10:09 -070070void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
71 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -080072 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -070073 enc->GetEncodedLayerFrame(pkt);
74}
75
Emircan Uysaler98badbc2018-06-28 10:59:02 -070076VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +000077 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -070078 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -070079 profile_(
80 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000081 inited_(false),
82 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +000083 cpu_speed_(3),
84 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -070085 encoder_(nullptr),
86 config_(nullptr),
87 raw_(nullptr),
88 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +020089 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020090 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -070091 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -080092 num_spatial_layers_(0),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +020093 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +020094 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkind902d582018-05-18 17:31:19 +020095 output_framerate_(1000.0, 1000.0),
96 last_encoded_frame_rtp_timestamp_(0),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +020097 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +000098 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -080099 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700100 RTC_DCHECK(VP9Profile::kProfile0 == profile_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000101}
102
103VP9EncoderImpl::~VP9EncoderImpl() {
104 Release();
105}
106
107int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100108 int ret_val = WEBRTC_VIDEO_CODEC_OK;
109
sprang3958ed82017-08-17 08:12:10 -0700110 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800111 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700112 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000113 }
sprang3958ed82017-08-17 08:12:10 -0700114 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100115 if (inited_) {
116 if (vpx_codec_destroy(encoder_)) {
117 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
118 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000119 }
120 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700121 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000122 }
sprang3958ed82017-08-17 08:12:10 -0700123 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000124 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700125 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000126 }
sprang3958ed82017-08-17 08:12:10 -0700127 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000128 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700129 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000130 }
131 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100132 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000133}
134
sprangce4aef12015-11-02 07:23:20 -0800135bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
136 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
137 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100138 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800139}
140
Erik Språng566124a2018-04-23 12:32:22 +0200141bool VP9EncoderImpl::SetSvcRates(
142 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700143 uint8_t i = 0;
144
Sergey Silkin86684962018-03-28 19:32:37 +0200145 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200146
“Michael23c5a992018-06-21 11:07:21 -0500147 num_active_spatial_layers_ = 0;
148 for (i = 0; i < num_spatial_layers_; ++i)
149 num_active_spatial_layers_ += bitrate_allocation.IsSpatialLayerUsed(i);
150 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
151 RTC_DCHECK_LE(num_active_spatial_layers_, num_spatial_layers_);
152
sprangce4aef12015-11-02 07:23:20 -0800153 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200154 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200155 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200156 config_->ss_target_bitrate[sl_idx] =
157 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
158
159 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
160 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
161 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
162 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200163
164 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
165 if (is_layer_enabled && !was_layer_enabled) {
166 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
167 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
168 // TODO(wemb:1526): remove key frame request when issue is fixed.
169 force_key_frame_ = true;
170 }
171 }
sprangce4aef12015-11-02 07:23:20 -0800172 }
173 } else {
174 float rate_ratio[VPX_MAX_LAYERS] = {0};
175 float total = 0;
“Michael67c8bcf2018-06-27 04:24:13 -0500176 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800177 if (svc_params_.scaling_factor_num[i] <= 0 ||
178 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100179 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800180 return false;
181 }
Yves Gerey665174f2018-06-19 15:03:05 +0200182 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
183 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800184 total += rate_ratio[i];
185 }
186
“Michael67c8bcf2018-06-27 04:24:13 -0500187 for (i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200188 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800189 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
190 config_->rc_target_bitrate * rate_ratio[i] / total);
191 if (num_temporal_layers_ == 1) {
192 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
193 } else if (num_temporal_layers_ == 2) {
194 config_->layer_target_bitrate[i * num_temporal_layers_] =
195 config_->ss_target_bitrate[i] * 2 / 3;
196 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
197 config_->ss_target_bitrate[i];
198 } else if (num_temporal_layers_ == 3) {
199 config_->layer_target_bitrate[i * num_temporal_layers_] =
200 config_->ss_target_bitrate[i] / 2;
201 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
202 config_->layer_target_bitrate[i * num_temporal_layers_] +
203 (config_->ss_target_bitrate[i] / 4);
204 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
205 config_->ss_target_bitrate[i];
206 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100207 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
208 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800209 return false;
210 }
asaperssona9455ab2015-07-31 06:10:09 -0700211 }
212 }
asaperssona9455ab2015-07-31 06:10:09 -0700213 return true;
214}
215
Erik Språng08127a92016-11-16 16:41:30 +0100216int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200217 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100218 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000219 if (!inited_) {
220 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
221 }
222 if (encoder_->err) {
223 return WEBRTC_VIDEO_CODEC_ERROR;
224 }
Erik Språng08127a92016-11-16 16:41:30 +0100225 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000226 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
227 }
228 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100229 if (codec_.maxBitrate > 0 &&
230 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
231 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000232 }
Erik Språng08127a92016-11-16 16:41:30 +0100233
Erik Språng08127a92016-11-16 16:41:30 +0100234 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700235
Sergey Silkin86684962018-03-28 19:32:37 +0200236 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700237 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
238 }
239
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000240 // Update encoder context
241 if (vpx_codec_enc_config_set(encoder_, config_)) {
242 return WEBRTC_VIDEO_CODEC_ERROR;
243 }
244 return WEBRTC_VIDEO_CODEC_OK;
245}
246
247int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
248 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000249 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700250 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000251 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
252 }
253 if (inst->maxFramerate < 1) {
254 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
255 }
256 // Allow zero to represent an unspecified maxBitRate
257 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
258 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
259 }
260 if (inst->width < 1 || inst->height < 1) {
261 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
262 }
263 if (number_of_cores < 1) {
264 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
265 }
hta257dc392016-10-25 09:05:06 -0700266 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700267 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
268 }
ilnik2a8c2f52017-02-15 02:23:28 -0800269 // libvpx probably does not support more than 3 spatial layers.
270 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700271 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
272 }
philipelcfc319b2015-11-10 07:17:23 -0800273
asapersson86956de2016-01-26 01:05:20 -0800274 int ret_val = Release();
275 if (ret_val < 0) {
276 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000277 }
sprang3958ed82017-08-17 08:12:10 -0700278 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000279 encoder_ = new vpx_codec_ctx_t;
280 }
sprang3958ed82017-08-17 08:12:10 -0700281 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000282 config_ = new vpx_codec_enc_cfg_t;
283 }
284 timestamp_ = 0;
285 if (&codec_ != inst) {
286 codec_ = *inst;
287 }
asaperssona9455ab2015-07-31 06:10:09 -0700288
hta257dc392016-10-25 09:05:06 -0700289 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200290 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700291 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700292 if (num_temporal_layers_ == 0)
293 num_temporal_layers_ = 1;
294
Sergey Silkind902d582018-05-18 17:31:19 +0200295 // Init framerate controller.
296 output_framerate_.Reset();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200297 if (codec_.mode == VideoCodecMode::kScreensharing) {
Sergey Silkind902d582018-05-18 17:31:19 +0200298 target_framerate_fps_ = kMaxScreenSharingFramerateFps;
299 } else {
300 target_framerate_fps_.reset();
301 }
302
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200303 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
304 // Flexible mode requires SVC to be enabled since libvpx API only allows
305 // to get reference list in SVC mode.
306 RTC_DCHECK(!inst->VP9().flexibleMode || is_svc_);
307
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000308 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700309 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800310 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000311 }
nisseeb44b392017-04-28 07:18:05 -0700312 encoded_image_._size =
313 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000314 encoded_image_._buffer = new uint8_t[encoded_image_._size];
315 encoded_image_._completeFrame = true;
sprang3958ed82017-08-17 08:12:10 -0700316 // Creating a wrapper to the image - setting image data to nullptr. Actual
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000317 // pointer will be set in encode. Setting align to 1, as it is meaningless
318 // (actual memory is not allocated).
sprang3958ed82017-08-17 08:12:10 -0700319 raw_ = vpx_img_wrap(nullptr, VPX_IMG_FMT_I420, codec_.width, codec_.height, 1,
320 nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000321 // Populate encoder configuration with default values.
322 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
323 return WEBRTC_VIDEO_CODEC_ERROR;
324 }
325 config_->g_w = codec_.width;
326 config_->g_h = codec_.height;
327 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200328 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000329 // Setting the time base of the codec.
330 config_->g_timebase.num = 1;
331 config_->g_timebase.den = 90000;
332 config_->g_lag_in_frames = 0; // 0- no frame lagging
333 config_->g_threads = 1;
334 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700335 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000336 config_->rc_end_usage = VPX_CBR;
337 config_->g_pass = VPX_RC_ONE_PASS;
338 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000339 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000340 config_->rc_undershoot_pct = 50;
341 config_->rc_overshoot_pct = 50;
342 config_->rc_buf_initial_sz = 500;
343 config_->rc_buf_optimal_sz = 600;
344 config_->rc_buf_sz = 1000;
345 // Set the maximum target size of any key-frame.
346 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700347 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000348 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700349 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100350 // Needs to be set (in svc mode) to get correct periodic key frame interval
351 // (will have no effect in non-svc).
352 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000353 } else {
354 config_->kf_mode = VPX_KF_DISABLED;
355 }
hta257dc392016-10-25 09:05:06 -0700356 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000357 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800358 config_->g_threads =
359 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700360
Marco6e89b252015-07-07 14:40:38 -0700361 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700362
363 // TODO(asapersson): Check configuration of temporal switch up and increase
364 // pattern length.
hta257dc392016-10-25 09:05:06 -0700365 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200366
367 // TODO(ssilkin): Only non-flexible mode is supported for now.
368 RTC_DCHECK(!is_flexible_mode_);
369
370 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700371 gof_.SetGofInfoVP9(kTemporalStructureMode1);
372 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
373 config_->ts_number_layers = 1;
374 config_->ts_rate_decimator[0] = 1;
375 config_->ts_periodicity = 1;
376 config_->ts_layer_id[0] = 0;
377 } else if (num_temporal_layers_ == 2) {
378 gof_.SetGofInfoVP9(kTemporalStructureMode2);
379 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
380 config_->ts_number_layers = 2;
381 config_->ts_rate_decimator[0] = 2;
382 config_->ts_rate_decimator[1] = 1;
383 config_->ts_periodicity = 2;
384 config_->ts_layer_id[0] = 0;
385 config_->ts_layer_id[1] = 1;
386 } else if (num_temporal_layers_ == 3) {
387 gof_.SetGofInfoVP9(kTemporalStructureMode3);
388 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
389 config_->ts_number_layers = 3;
390 config_->ts_rate_decimator[0] = 4;
391 config_->ts_rate_decimator[1] = 2;
392 config_->ts_rate_decimator[2] = 1;
393 config_->ts_periodicity = 4;
394 config_->ts_layer_id[0] = 0;
395 config_->ts_layer_id[1] = 2;
396 config_->ts_layer_id[2] = 1;
397 config_->ts_layer_id[3] = 2;
398 } else {
399 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
400 }
401
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200402 inter_layer_pred_ = inst->VP9().interLayerPred;
403
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200404 ref_buf_.clear();
405
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000406 return InitAndSetControlSettings(inst);
407}
408
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000409int VP9EncoderImpl::NumberOfThreads(int width,
410 int height,
411 int number_of_cores) {
412 // Keep the number of encoder threads equal to the possible number of column
413 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
414 if (width * height >= 1280 * 720 && number_of_cores > 4) {
415 return 4;
jianj23173a32017-07-12 16:11:09 -0700416 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000417 return 2;
418 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200419// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800420#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
421 defined(WEBRTC_ANDROID)
422 if (width * height >= 320 * 180 && number_of_cores > 2) {
423 return 2;
424 }
425#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000426 // 1 thread less than VGA.
427 return 1;
428 }
429}
430
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000431int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100432 // Set QP-min/max per spatial and temporal layer.
433 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
434 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800435 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
436 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100437 }
asaperssona9455ab2015-07-31 06:10:09 -0700438 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800439 if (ExplicitlyConfiguredSpatialLayers()) {
440 for (int i = 0; i < num_spatial_layers_; ++i) {
441 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200442 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100443 const int scale_factor = codec_.width / layer.width;
444 RTC_DCHECK_GT(scale_factor, 0);
445
446 // Ensure scaler factor is integer.
447 if (scale_factor * layer.width != codec_.width) {
448 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
449 }
450
451 // Ensure scale factor is the same in both dimensions.
452 if (scale_factor * layer.height != codec_.height) {
453 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
454 }
455
456 // Ensure scale factor is power of two.
457 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
458 if (!is_pow_of_two) {
459 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
460 }
461
462 svc_params_.scaling_factor_num[i] = 1;
463 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800464 }
465 } else {
466 int scaling_factor_num = 256;
467 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800468 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800469 svc_params_.scaling_factor_num[i] = scaling_factor_num;
470 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800471 }
asaperssona9455ab2015-07-31 06:10:09 -0700472 }
473
Sergey Silkin86684962018-03-28 19:32:37 +0200474 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200475 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200476 inst->startBitrate * 1000, inst->maxFramerate);
477 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700478 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
479 }
480
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000481 if (vpx_codec_enc_init(encoder_, vpx_codec_vp9_cx(), config_, 0)) {
482 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
483 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000484 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
485 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
486 rc_max_intra_target_);
487 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700488 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700489
jianj822e5932017-07-12 16:09:58 -0700490 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200491
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200492 if (is_svc_) {
493 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
494 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700495 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200496
497 if (num_spatial_layers_ > 1) {
498 switch (inter_layer_pred_) {
499 case InterLayerPredMode::kOn:
500 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
501 break;
502 case InterLayerPredMode::kOff:
503 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
504 break;
505 case InterLayerPredMode::kOnKeyPic:
506 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
507 break;
508 default:
509 RTC_NOTREACHED();
510 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200511
Sergey Silkinee203362018-05-30 11:34:08 +0200512 // Configure encoder to drop entire superframe whenever it needs to drop
513 // a layer. This mode is prefered over per-layer dropping which causes
514 // quality flickering and is not compatible with RTP non-flexible mode.
515 vpx_svc_frame_drop_t svc_drop_frame;
516 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
517 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200518 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200519 for (size_t i = 0; i < num_spatial_layers_; ++i) {
520 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200521 }
Sergey Silkinee203362018-05-30 11:34:08 +0200522 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200523 }
524
asaperssona9455ab2015-07-31 06:10:09 -0700525 // Register callback for getting each spatial layer.
526 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800527 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
528 reinterpret_cast<void*>(this)};
529 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
530 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700531
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000532 // Control function to set the number of column tiles in encoding a frame, in
533 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
534 // The number tile columns will be capped by the encoder based on image size
535 // (minimum width of tile column is 256 pixels, maximum is 4096).
536 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700537
538 // Turn on row-based multithreading.
539 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700540
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700541#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200542 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700543 // Do not enable the denoiser on ARM since optimization is pending.
544 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000545 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700546 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000547#endif
jianj6bf57e32017-06-05 13:43:49 -0700548
Niels Möllere3cf3d02018-06-13 11:52:16 +0200549 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700550 // Adjust internal parameters to screen content.
551 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700552 }
Marco2520e722015-09-16 14:05:00 -0700553 // Enable encoder skip of static/low content blocks.
554 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000555 inited_ = true;
556 return WEBRTC_VIDEO_CODEC_OK;
557}
558
559uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
560 // Set max to the optimal buffer level (normalized by target BR),
561 // and scaled by a scale_par.
562 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
563 // This value is presented in percentage of perFrameBw:
564 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
565 // The target in % is as follows:
566 float scale_par = 0.5;
567 uint32_t target_pct =
568 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
569 // Don't go below 3 times the per frame bandwidth.
570 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800571 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000572}
573
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700574int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000575 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700576 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000577 if (!inited_) {
578 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
579 }
sprang3958ed82017-08-17 08:12:10 -0700580 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000581 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
582 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200583
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000584 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200585 if (frame_types && !frame_types->empty()) {
586 if ((*frame_types)[0] == kVideoFrameKey) {
587 force_key_frame_ = true;
588 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000589 }
Sergey Silkind902d582018-05-18 17:31:19 +0200590
Niels Möllere3cf3d02018-06-13 11:52:16 +0200591 if (VideoCodecMode::kScreensharing == codec_.mode && !force_key_frame_) {
Sergey Silkind902d582018-05-18 17:31:19 +0200592 if (DropFrame(input_image.timestamp())) {
593 return WEBRTC_VIDEO_CODEC_OK;
594 }
595 }
596
kwiberg352444f2016-11-28 15:58:53 -0800597 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
598 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700599
600 // Set input image for use in the callback.
601 // This was necessary since you need some information from input_image.
602 // You can save only the necessary information (such as timestamp) instead of
603 // doing this.
604 input_image_ = &input_image;
605
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000606 rtc::scoped_refptr<I420BufferInterface> i420_buffer =
607 input_image.video_frame_buffer()->ToI420();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000608 // Image in vpx_image_t format.
609 // Input image is const. VPX's raw image is not defined as const.
Magnus Jedvert72dbe2a2017-06-10 17:03:37 +0000610 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
611 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
612 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
613 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
614 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
615 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000616
philipelcfc319b2015-11-10 07:17:23 -0800617 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200618 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000619 flags = VPX_EFLAG_FORCE_KF;
620 }
philipelcfc319b2015-11-10 07:17:23 -0800621
sprang3958ed82017-08-17 08:12:10 -0700622 RTC_CHECK_GT(codec_.maxFramerate, 0);
Sergey Silkind902d582018-05-18 17:31:19 +0200623 uint32_t duration =
624 90000 / target_framerate_fps_.value_or(codec_.maxFramerate);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000625 if (vpx_codec_encode(encoder_, raw_, timestamp_, duration, flags,
626 VPX_DL_REALTIME)) {
627 return WEBRTC_VIDEO_CODEC_ERROR;
628 }
629 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700630
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200631 const bool end_of_picture = true;
632 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200633
asaperssona9455ab2015-07-31 06:10:09 -0700634 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000635}
636
637void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800638 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200639 uint32_t timestamp,
640 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700641 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000642 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700643 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800644 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200645
646 vp9_info->first_frame_in_picture = first_frame_in_picture;
hta257dc392016-10-25 09:05:06 -0700647 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
648 vp9_info->ss_data_available =
649 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
650 ? true
651 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700652
653 vpx_svc_layer_id_t layer_id = {0};
654 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
655
sprang3958ed82017-08-17 08:12:10 -0700656 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500657 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700658 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700659 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700660 vp9_info->temporal_idx = kNoTemporalIdx;
661 } else {
662 vp9_info->temporal_idx = layer_id.temporal_layer_id;
663 }
“Michael23c5a992018-06-21 11:07:21 -0500664 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700665 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700666 vp9_info->spatial_idx = kNoSpatialIdx;
667 } else {
668 vp9_info->spatial_idx = layer_id.spatial_layer_id;
669 }
670 if (layer_id.spatial_layer_id != 0) {
671 vp9_info->ss_data_available = false;
672 }
673
asaperssona9455ab2015-07-31 06:10:09 -0700674 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800675 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700676
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200677 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
678 pics_since_key_ = 0;
679 } else if (first_frame_in_picture) {
680 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700681 }
682
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200683 const bool is_key_pic = (pics_since_key_ == 0);
684 const bool is_inter_layer_pred_allowed =
685 (inter_layer_pred_ == InterLayerPredMode::kOn ||
686 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
687
688 // Always set inter_layer_predicted to true on high layer frame if inter-layer
689 // prediction (ILP) is allowed even if encoder didn't actually use it.
690 // Setting inter_layer_predicted to false would allow receiver to decode high
691 // layer frame without decoding low layer frame. If that would happen (e.g.
692 // if low layer frame is lost) then receiver won't be able to decode next high
693 // layer frame which uses ILP.
694 vp9_info->inter_layer_predicted =
695 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
696
697 const bool is_last_layer =
“Michael23c5a992018-06-21 11:07:21 -0500698 (layer_id.spatial_layer_id + 1 == num_active_spatial_layers_);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200699 vp9_info->non_ref_for_inter_layer_pred =
700 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800701
ivica7f6a6fc2015-09-08 02:40:29 -0700702 // Always populate this, so that the packetizer can properly set the marker
703 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500704 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800705
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200706 RTC_DCHECK(!vp9_info->flexible_mode);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200707
708 vp9_info->num_ref_pics = 0;
709 if (vp9_info->flexible_mode) {
710 vp9_info->gof_idx = kNoGofIdx;
711 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
712 vp9_info);
713 } else {
714 vp9_info->gof_idx =
715 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
716 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
717 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
718 }
719
720 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
721
asaperssona9455ab2015-07-31 06:10:09 -0700722 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700723 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500724 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200725 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800726 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200727 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800728 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700729 }
730 if (!vp9_info->flexible_mode) {
731 vp9_info->gof.CopyGofInfoVP9(gof_);
732 }
733 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000734}
735
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200736void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
737 const size_t pic_num,
738 const bool inter_layer_predicted,
739 CodecSpecificInfoVP9* vp9_info) {
740 vpx_svc_layer_id_t layer_id = {0};
741 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
742
743 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
744 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
745
746 std::vector<RefFrameBuffer> ref_buf_list;
747 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
748 const size_t fb_idx = enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
749 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
750 ref_buf_list.push_back(ref_buf_.at(fb_idx));
751 }
752
753 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
754 const size_t fb_idx = enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
755 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
756 ref_buf_list.push_back(ref_buf_.at(fb_idx));
757 }
758
759 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
760 const size_t fb_idx = enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
761 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
762 ref_buf_list.push_back(ref_buf_.at(fb_idx));
763 }
764
765 size_t max_ref_temporal_layer_id = 0;
766
767 vp9_info->num_ref_pics = 0;
768 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
769 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
770 if (ref_buf.pic_num < pic_num) {
771 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
772 // RTP spec limits temporal prediction to the same spatial layer.
773 // It is safe to ignore this requirement if inter-layer prediction is
774 // enabled for all frames when all base frames are relayed to receiver.
775 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
776 }
777 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
778
779 const size_t p_diff = pic_num - ref_buf.pic_num;
780 RTC_DCHECK_LE(p_diff, 127UL);
781
782 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
783 ++vp9_info->num_ref_pics;
784
785 max_ref_temporal_layer_id =
786 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
787 } else {
788 RTC_DCHECK(inter_layer_predicted);
789 // RTP spec only allows to use previous spatial layer for inter-layer
790 // prediction.
791 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
792 }
793 }
794
795 vp9_info->temporal_up_switch =
796 (max_ref_temporal_layer_id <
797 static_cast<size_t>(layer_id.temporal_layer_id));
798}
799
800void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
801 const size_t pic_num) {
802 vpx_svc_layer_id_t layer_id = {0};
803 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
804
805 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
806 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
807
808 const bool is_key_frame =
809 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
810
811 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
812 layer_id.temporal_layer_id);
813
814 if (is_key_frame && layer_id.spatial_layer_id == 0) {
815 // Key frame updates all ref buffers.
816 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
817 ref_buf_[i] = frame_buf;
818 }
819 } else {
820 if (enc_layer_conf.update_last[layer_id.spatial_layer_id]) {
821 ref_buf_[enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id]] =
822 frame_buf;
823 }
824
825 if (enc_layer_conf.update_alt_ref[layer_id.spatial_layer_id]) {
826 ref_buf_[enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id]] =
827 frame_buf;
828 }
829
830 if (enc_layer_conf.update_golden[layer_id.spatial_layer_id]) {
831 ref_buf_[enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id]] =
832 frame_buf;
833 }
834 }
835}
836
asaperssona9455ab2015-07-31 06:10:09 -0700837int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800838 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700839
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200840 if (pkt->data.frame.sz == 0) {
841 // Ignore dropped frame.
842 return WEBRTC_VIDEO_CODEC_OK;
843 }
844
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200845 vpx_svc_layer_id_t layer_id = {0};
846 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
847
848 const bool first_frame_in_picture = encoded_image_._length == 0;
849 // Ensure we don't buffer layers of previous picture (superframe).
850 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
851
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200852 const bool end_of_picture = false;
853 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200854
asaperssond9f641e2016-01-21 01:11:35 -0800855 if (pkt->data.frame.sz > encoded_image_._size) {
856 delete[] encoded_image_._buffer;
857 encoded_image_._size = pkt->data.frame.sz;
858 encoded_image_._buffer = new uint8_t[encoded_image_._size];
859 }
asapersson86956de2016-01-26 01:05:20 -0800860 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
861 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800862
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200863 const bool is_key_frame =
864 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
865 // Ensure encoder issued key frame on request.
866 RTC_DCHECK(is_key_frame || !force_key_frame_);
867
asaperssona9455ab2015-07-31 06:10:09 -0700868 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800869 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200870 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200871 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200872 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000873 }
asapersson86956de2016-01-26 01:05:20 -0800874 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
875
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200876 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200877 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
878 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -0700879
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200880 if (is_flexible_mode_) {
881 UpdateReferenceBuffers(*pkt, pics_since_key_);
882 }
883
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200884 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
885 encoded_image_._timeStamp = input_image_->timestamp();
886 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
887 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200888 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200889 ? VideoContentType::SCREENSHARE
890 : VideoContentType::UNSPECIFIED;
891 encoded_image_._encodedHeight =
892 pkt->data.frame.height[layer_id.spatial_layer_id];
893 encoded_image_._encodedWidth =
894 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +0200895 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200896 int qp = -1;
897 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
898 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -0700899
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000900 return WEBRTC_VIDEO_CODEC_OK;
901}
902
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200903void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200904 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200905 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200906
907 // No data partitioning in VP9, so 1 partition only.
908 int part_idx = 0;
909 RTPFragmentationHeader frag_info;
910 frag_info.VerifyAndAllocateFragmentationHeader(1);
911 frag_info.fragmentationOffset[part_idx] = 0;
912 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
913 frag_info.fragmentationPlType[part_idx] = 0;
914 frag_info.fragmentationTimeDiff[part_idx] = 0;
915
916 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
917 &frag_info);
918 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +0200919
920 if (end_of_picture) {
921 const uint32_t timestamp_ms =
922 1000 * encoded_image_._timeStamp / kVideoPayloadTypeFrequency;
923 output_framerate_.Update(1, timestamp_ms);
924 last_encoded_frame_rtp_timestamp_ = encoded_image_._timeStamp;
925 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200926 }
927}
928
Sergey Silkind902d582018-05-18 17:31:19 +0200929bool VP9EncoderImpl::DropFrame(uint32_t rtp_timestamp) {
930 if (target_framerate_fps_) {
931 if (rtp_timestamp < last_encoded_frame_rtp_timestamp_) {
932 // Timestamp has wrapped around. Reset framerate statistic.
933 output_framerate_.Reset();
934 return false;
935 }
936
937 const uint32_t timestamp_ms =
938 1000 * rtp_timestamp / kVideoPayloadTypeFrequency;
939 const uint32_t framerate_fps =
940 output_framerate_.Rate(timestamp_ms).value_or(0);
941 if (framerate_fps > *target_framerate_fps_) {
942 return true;
943 }
944
945 // Primarily check if frame interval is too short using frame timestamps,
946 // as if they are correct they won't be affected by queuing in webrtc.
947 const uint32_t expected_frame_interval =
948 kVideoPayloadTypeFrequency / *target_framerate_fps_;
949
950 const uint32_t ts_diff = rtp_timestamp - last_encoded_frame_rtp_timestamp_;
951 if (ts_diff < 85 * expected_frame_interval / 100) {
952 return true;
953 }
954 }
955
956 return false;
957}
958
pkasting@chromium.org16825b12015-01-12 21:51:21 +0000959int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000960 return WEBRTC_VIDEO_CODEC_OK;
961}
962
963int VP9EncoderImpl::RegisterEncodeCompleteCallback(
964 EncodedImageCallback* callback) {
965 encoded_complete_callback_ = callback;
966 return WEBRTC_VIDEO_CODEC_OK;
967}
968
Peter Boströmb7d9a972015-12-18 16:01:11 +0100969const char* VP9EncoderImpl::ImplementationName() const {
970 return "libvpx";
971}
972
Magnus Jedvert46a27652017-11-13 14:10:02 +0100973std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200974 return absl::make_unique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000975}
976
977VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -0700978 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000979 inited_(false),
sprang3958ed82017-08-17 08:12:10 -0700980 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +0200981 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000982
983VP9DecoderImpl::~VP9DecoderImpl() {
984 inited_ = true; // in order to do the actual release
985 Release();
Henrik Boström9695d852015-05-06 10:42:15 +0200986 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
987 if (num_buffers_in_use > 0) {
988 // The frame buffers are reference counted and frames are exposed after
989 // decoding. There may be valid usage cases where previous frames are still
990 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100991 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
992 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +0200993 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000994}
995
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000996int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000997 int ret_val = Release();
998 if (ret_val < 0) {
999 return ret_val;
1000 }
sprang3958ed82017-08-17 08:12:10 -07001001 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001002 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001003 }
philipelcce46fc2015-12-21 03:04:49 -08001004 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001005 // Setting number of threads to a constant value (1)
1006 cfg.threads = 1;
1007 cfg.h = cfg.w = 0; // set after decode
1008 vpx_codec_flags_t flags = 0;
1009 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1010 return WEBRTC_VIDEO_CODEC_MEMORY;
1011 }
Henrik Boström9695d852015-05-06 10:42:15 +02001012
1013 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1014 return WEBRTC_VIDEO_CODEC_MEMORY;
1015 }
1016
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001017 inited_ = true;
1018 // Always start with a complete key frame.
1019 key_frame_required_ = true;
1020 return WEBRTC_VIDEO_CODEC_OK;
1021}
1022
1023int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1024 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001025 const CodecSpecificInfo* codec_specific_info,
1026 int64_t /*render_time_ms*/) {
1027 if (!inited_) {
1028 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1029 }
sprang3958ed82017-08-17 08:12:10 -07001030 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001031 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1032 }
1033 // Always start with a complete key frame.
1034 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001035 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001036 return WEBRTC_VIDEO_CODEC_ERROR;
1037 // We have a key frame - is it complete?
1038 if (input_image._completeFrame) {
1039 key_frame_required_ = false;
1040 } else {
1041 return WEBRTC_VIDEO_CODEC_ERROR;
1042 }
1043 }
sprang3958ed82017-08-17 08:12:10 -07001044 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001045 vpx_image_t* img;
1046 uint8_t* buffer = input_image._buffer;
1047 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001048 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001049 }
Henrik Boström9695d852015-05-06 10:42:15 +02001050 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1051 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001052 if (vpx_codec_decode(decoder_, buffer,
1053 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001054 VPX_DL_REALTIME)) {
1055 return WEBRTC_VIDEO_CODEC_ERROR;
1056 }
Henrik Boström9695d852015-05-06 10:42:15 +02001057 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1058 // It may be released by libvpx during future vpx_codec_decode or
1059 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001060 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001061 int qp;
1062 vpx_codec_err_t vpx_ret =
1063 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1064 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1065 int ret =
1066 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001067 if (ret != 0) {
1068 return ret;
1069 }
1070 return WEBRTC_VIDEO_CODEC_OK;
1071}
1072
asapersson1490f7a2016-09-23 02:09:46 -07001073int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1074 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001075 int64_t ntp_time_ms,
1076 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001077 if (img == nullptr) {
1078 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001079 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1080 }
Henrik Boström9695d852015-05-06 10:42:15 +02001081
1082 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001083 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001084 // vpx_codec_decode calls or vpx_codec_destroy).
1085 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1086 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001087 // The buffer can be used directly by the VideoFrame (without copy) by
Henrik Boström9695d852015-05-06 10:42:15 +02001088 // using a WrappedI420Buffer.
1089 rtc::scoped_refptr<WrappedI420Buffer> img_wrapped_buffer(
1090 new rtc::RefCountedObject<webrtc::WrappedI420Buffer>(
philipelcce46fc2015-12-21 03:04:49 -08001091 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1092 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1093 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1094 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001095 // WrappedI420Buffer's mechanism for allowing the release of its frame
1096 // buffer is through a callback function. This is where we should
1097 // release |img_buffer|.
perkj14f41442015-11-30 22:15:45 -08001098 rtc::KeepRefUntilDone(img_buffer)));
Henrik Boström9695d852015-05-06 10:42:15 +02001099
nisseca6d5d12016-06-17 05:03:04 -07001100 VideoFrame decoded_image(img_wrapped_buffer, timestamp,
1101 0 /* render_time_ms */, webrtc::kVideoRotation_0);
asapersson1490f7a2016-09-23 02:09:46 -07001102 decoded_image.set_ntp_time_ms(ntp_time_ms);
nisseca6d5d12016-06-17 05:03:04 -07001103
Danil Chapovalov0040b662018-06-18 10:48:16 +02001104 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001105 return WEBRTC_VIDEO_CODEC_OK;
1106}
1107
1108int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1109 DecodedImageCallback* callback) {
1110 decode_complete_callback_ = callback;
1111 return WEBRTC_VIDEO_CODEC_OK;
1112}
1113
1114int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001115 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1116
sprang3958ed82017-08-17 08:12:10 -07001117 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001118 if (inited_) {
1119 // When a codec is destroyed libvpx will release any buffers of
1120 // |frame_buffer_pool_| it is currently using.
1121 if (vpx_codec_destroy(decoder_)) {
1122 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1123 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001124 }
1125 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001126 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001127 }
Henrik Boström9695d852015-05-06 10:42:15 +02001128 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1129 // still referenced externally are deleted once fully released, not returning
1130 // to the pool.
1131 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001132 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001133 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001134}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001135
1136const char* VP9DecoderImpl::ImplementationName() const {
1137 return "libvpx";
1138}
1139
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001140} // namespace webrtc