blob: 0cbc34e37286bf390a53845c3f874ab39e4b3fd5 [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"
Emircan Uysaler800787f2018-07-16 10:01:49 -070024#include "api/video/color_space.h"
Emircan Uysaler0823eec2018-07-13 17:10:00 -070025#include "api/video/i010_buffer.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020026#include "common_video/include/video_frame_buffer.h"
27#include "common_video/libyuv/include/webrtc_libyuv.h"
Sergey Silkind902d582018-05-18 17:31:19 +020028#include "modules/rtp_rtcp/include/rtp_rtcp_defines.h"
Sergey Silkin86684962018-03-28 19:32:37 +020029#include "modules/video_coding/codecs/vp9/svc_rate_allocator.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020030#include "rtc_base/checks.h"
31#include "rtc_base/keep_ref_until_done.h"
32#include "rtc_base/logging.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020033#include "rtc_base/timeutils.h"
34#include "rtc_base/trace_event.h"
marpan@webrtc.org5b883172014-11-01 06:10:48 +000035
36namespace webrtc {
37
Sergey Silkind902d582018-05-18 17:31:19 +020038namespace {
39const float kMaxScreenSharingFramerateFps = 5.0f;
Sergey Silkind902d582018-05-18 17:31:19 +020040
Marco6e89b252015-07-07 14:40:38 -070041// Only positive speeds, range for real-time coding currently is: 5 - 8.
42// Lower means slower/better quality, higher means fastest/lower quality.
43int GetCpuSpeed(int width, int height) {
Alex Glaznevfecb7c32016-03-31 14:23:27 -070044#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || defined(ANDROID)
Marco002f0d02015-12-17 09:49:31 -080045 return 8;
46#else
Marco6e89b252015-07-07 14:40:38 -070047 // For smaller resolutions, use lower speed setting (get some coding gain at
48 // the cost of increased encoding complexity).
49 if (width * height <= 352 * 288)
50 return 5;
51 else
52 return 7;
Marco002f0d02015-12-17 09:49:31 -080053#endif
Marco6e89b252015-07-07 14:40:38 -070054}
Emircan Uysaler715cc232018-07-23 17:50:43 -070055// Helper class for extracting VP9 colorspace.
56ColorSpace ExtractVP9ColorSpace(vpx_color_space_t space_t,
57 vpx_color_range_t range_t,
58 unsigned int bit_depth) {
59 ColorSpace::PrimaryID primaries = ColorSpace::PrimaryID::kInvalid;
60 ColorSpace::TransferID transfer = ColorSpace::TransferID::kInvalid;
61 ColorSpace::MatrixID matrix = ColorSpace::MatrixID::kInvalid;
62 switch (space_t) {
63 case VPX_CS_BT_601:
64 case VPX_CS_SMPTE_170:
65 primaries = ColorSpace::PrimaryID::kSMPTE170M;
66 transfer = ColorSpace::TransferID::kSMPTE170M;
67 matrix = ColorSpace::MatrixID::kSMPTE170M;
68 break;
69 case VPX_CS_SMPTE_240:
70 primaries = ColorSpace::PrimaryID::kSMPTE240M;
71 transfer = ColorSpace::TransferID::kSMPTE240M;
72 matrix = ColorSpace::MatrixID::kSMPTE240M;
73 break;
74 case VPX_CS_BT_709:
75 primaries = ColorSpace::PrimaryID::kBT709;
76 transfer = ColorSpace::TransferID::kBT709;
77 matrix = ColorSpace::MatrixID::kBT709;
78 break;
79 case VPX_CS_BT_2020:
80 primaries = ColorSpace::PrimaryID::kBT2020;
81 switch (bit_depth) {
82 case 8:
83 transfer = ColorSpace::TransferID::kBT709;
84 break;
85 case 10:
86 transfer = ColorSpace::TransferID::kBT2020_10;
87 break;
88 default:
89 RTC_NOTREACHED();
90 break;
91 }
92 matrix = ColorSpace::MatrixID::kBT2020_NCL;
93 break;
94 case VPX_CS_SRGB:
95 primaries = ColorSpace::PrimaryID::kBT709;
96 transfer = ColorSpace::TransferID::kIEC61966_2_1;
97 matrix = ColorSpace::MatrixID::kBT709;
98 break;
99 default:
100 break;
101 }
102
103 ColorSpace::RangeID range = ColorSpace::RangeID::kInvalid;
104 switch (range_t) {
105 case VPX_CR_STUDIO_RANGE:
106 range = ColorSpace::RangeID::kLimited;
107 break;
108 case VPX_CR_FULL_RANGE:
109 range = ColorSpace::RangeID::kFull;
110 break;
111 default:
112 break;
113 }
114 return ColorSpace(primaries, transfer, matrix, range);
115}
116} // namespace
Marco6e89b252015-07-07 14:40:38 -0700117
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700118std::vector<SdpVideoFormat> SupportedVP9Codecs() {
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700119 // TODO(emircan): Add Profile 2 support after fixing browser_tests.
120 std::vector<SdpVideoFormat> supported_formats{SdpVideoFormat(
121 cricket::kVp9CodecName,
122 {{kVP9FmtpProfileId, VP9ProfileToString(VP9Profile::kProfile0)}})};
123 return supported_formats;
Peter Boström12996152016-05-14 02:03:18 +0200124}
125
Magnus Jedvert46a27652017-11-13 14:10:02 +0100126std::unique_ptr<VP9Encoder> VP9Encoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200127 return absl::make_unique<VP9EncoderImpl>(cricket::VideoCodec());
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700128}
129
130std::unique_ptr<VP9Encoder> VP9Encoder::Create(
131 const cricket::VideoCodec& codec) {
Karl Wiberg918f50c2018-07-05 11:40:33 +0200132 return absl::make_unique<VP9EncoderImpl>(codec);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000133}
134
asaperssona9455ab2015-07-31 06:10:09 -0700135void VP9EncoderImpl::EncoderOutputCodedPacketCallback(vpx_codec_cx_pkt* pkt,
136 void* user_data) {
philipelcce46fc2015-12-21 03:04:49 -0800137 VP9EncoderImpl* enc = static_cast<VP9EncoderImpl*>(user_data);
asaperssona9455ab2015-07-31 06:10:09 -0700138 enc->GetEncodedLayerFrame(pkt);
139}
140
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700141VP9EncoderImpl::VP9EncoderImpl(const cricket::VideoCodec& codec)
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000142 : encoded_image_(),
sprang3958ed82017-08-17 08:12:10 -0700143 encoded_complete_callback_(nullptr),
Emircan Uysaler98badbc2018-06-28 10:59:02 -0700144 profile_(
145 ParseSdpForVP9Profile(codec.params).value_or(VP9Profile::kProfile0)),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000146 inited_(false),
147 timestamp_(0),
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000148 cpu_speed_(3),
149 rc_max_intra_target_(0),
sprang3958ed82017-08-17 08:12:10 -0700150 encoder_(nullptr),
151 config_(nullptr),
152 raw_(nullptr),
153 input_image_(nullptr),
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200154 force_key_frame_(true),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200155 pics_since_key_(0),
asaperssona9455ab2015-07-31 06:10:09 -0700156 num_temporal_layers_(0),
philipelcfc319b2015-11-10 07:17:23 -0800157 num_spatial_layers_(0),
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200158 is_svc_(false),
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200159 inter_layer_pred_(InterLayerPredMode::kOn),
Sergey Silkind902d582018-05-18 17:31:19 +0200160 output_framerate_(1000.0, 1000.0),
161 last_encoded_frame_rtp_timestamp_(0),
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200162 is_flexible_mode_(false) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000163 memset(&codec_, 0, sizeof(codec_));
johannkoenig8225c402017-01-26 13:23:44 -0800164 memset(&svc_params_, 0, sizeof(vpx_svc_extra_cfg_t));
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000165}
166
167VP9EncoderImpl::~VP9EncoderImpl() {
168 Release();
169}
170
171int VP9EncoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100172 int ret_val = WEBRTC_VIDEO_CODEC_OK;
173
sprang3958ed82017-08-17 08:12:10 -0700174 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800175 delete[] encoded_image_._buffer;
sprang3958ed82017-08-17 08:12:10 -0700176 encoded_image_._buffer = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000177 }
sprang3958ed82017-08-17 08:12:10 -0700178 if (encoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +0100179 if (inited_) {
180 if (vpx_codec_destroy(encoder_)) {
181 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
182 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000183 }
184 delete encoder_;
sprang3958ed82017-08-17 08:12:10 -0700185 encoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000186 }
sprang3958ed82017-08-17 08:12:10 -0700187 if (config_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000188 delete config_;
sprang3958ed82017-08-17 08:12:10 -0700189 config_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000190 }
sprang3958ed82017-08-17 08:12:10 -0700191 if (raw_ != nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000192 vpx_img_free(raw_);
sprang3958ed82017-08-17 08:12:10 -0700193 raw_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000194 }
195 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +0100196 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000197}
198
sprangce4aef12015-11-02 07:23:20 -0800199bool VP9EncoderImpl::ExplicitlyConfiguredSpatialLayers() const {
200 // We check target_bitrate_bps of the 0th layer to see if the spatial layers
201 // (i.e. bitrates) were explicitly configured.
Sergey Silkin13e74342018-03-02 12:28:00 +0100202 return num_spatial_layers_ > 1 && codec_.spatialLayers[0].targetBitrate > 0;
sprangce4aef12015-11-02 07:23:20 -0800203}
204
Erik Språng566124a2018-04-23 12:32:22 +0200205bool VP9EncoderImpl::SetSvcRates(
206 const VideoBitrateAllocation& bitrate_allocation) {
asaperssona9455ab2015-07-31 06:10:09 -0700207 uint8_t i = 0;
208
Sergey Silkin86684962018-03-28 19:32:37 +0200209 config_->rc_target_bitrate = bitrate_allocation.get_sum_kbps();
Sergey Silkin86684962018-03-28 19:32:37 +0200210
“Michael23c5a992018-06-21 11:07:21 -0500211 num_active_spatial_layers_ = 0;
212 for (i = 0; i < num_spatial_layers_; ++i)
213 num_active_spatial_layers_ += bitrate_allocation.IsSpatialLayerUsed(i);
214 RTC_DCHECK_GT(num_active_spatial_layers_, 0);
215 RTC_DCHECK_LE(num_active_spatial_layers_, num_spatial_layers_);
216
sprangce4aef12015-11-02 07:23:20 -0800217 if (ExplicitlyConfiguredSpatialLayers()) {
Sergey Silkin86684962018-03-28 19:32:37 +0200218 for (size_t sl_idx = 0; sl_idx < num_spatial_layers_; ++sl_idx) {
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200219 const bool was_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
Sergey Silkin86684962018-03-28 19:32:37 +0200220 config_->ss_target_bitrate[sl_idx] =
221 bitrate_allocation.GetSpatialLayerSum(sl_idx) / 1000;
222
223 for (size_t tl_idx = 0; tl_idx < num_temporal_layers_; ++tl_idx) {
224 config_->layer_target_bitrate[sl_idx * num_temporal_layers_ + tl_idx] =
225 bitrate_allocation.GetTemporalLayerSum(sl_idx, tl_idx) / 1000;
226 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200227
228 const bool is_layer_enabled = (config_->ss_target_bitrate[sl_idx] > 0);
229 if (is_layer_enabled && !was_layer_enabled) {
230 if (inter_layer_pred_ == InterLayerPredMode::kOff ||
231 inter_layer_pred_ == InterLayerPredMode::kOnKeyPic) {
232 // TODO(wemb:1526): remove key frame request when issue is fixed.
233 force_key_frame_ = true;
234 }
235 }
sprangce4aef12015-11-02 07:23:20 -0800236 }
237 } else {
238 float rate_ratio[VPX_MAX_LAYERS] = {0};
239 float total = 0;
“Michael67c8bcf2018-06-27 04:24:13 -0500240 for (i = 0; i < num_spatial_layers_; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800241 if (svc_params_.scaling_factor_num[i] <= 0 ||
242 svc_params_.scaling_factor_den[i] <= 0) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100243 RTC_LOG(LS_ERROR) << "Scaling factors not specified!";
sprangce4aef12015-11-02 07:23:20 -0800244 return false;
245 }
Yves Gerey665174f2018-06-19 15:03:05 +0200246 rate_ratio[i] = static_cast<float>(svc_params_.scaling_factor_num[i]) /
247 svc_params_.scaling_factor_den[i];
sprangce4aef12015-11-02 07:23:20 -0800248 total += rate_ratio[i];
249 }
250
“Michael67c8bcf2018-06-27 04:24:13 -0500251 for (i = 0; i < num_spatial_layers_; ++i) {
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200252 RTC_CHECK_GT(total, 0);
sprangce4aef12015-11-02 07:23:20 -0800253 config_->ss_target_bitrate[i] = static_cast<unsigned int>(
254 config_->rc_target_bitrate * rate_ratio[i] / total);
255 if (num_temporal_layers_ == 1) {
256 config_->layer_target_bitrate[i] = config_->ss_target_bitrate[i];
257 } else if (num_temporal_layers_ == 2) {
258 config_->layer_target_bitrate[i * num_temporal_layers_] =
259 config_->ss_target_bitrate[i] * 2 / 3;
260 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
261 config_->ss_target_bitrate[i];
262 } else if (num_temporal_layers_ == 3) {
263 config_->layer_target_bitrate[i * num_temporal_layers_] =
264 config_->ss_target_bitrate[i] / 2;
265 config_->layer_target_bitrate[i * num_temporal_layers_ + 1] =
266 config_->layer_target_bitrate[i * num_temporal_layers_] +
267 (config_->ss_target_bitrate[i] / 4);
268 config_->layer_target_bitrate[i * num_temporal_layers_ + 2] =
269 config_->ss_target_bitrate[i];
270 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100271 RTC_LOG(LS_ERROR) << "Unsupported number of temporal layers: "
272 << num_temporal_layers_;
sprangce4aef12015-11-02 07:23:20 -0800273 return false;
274 }
asaperssona9455ab2015-07-31 06:10:09 -0700275 }
276 }
asaperssona9455ab2015-07-31 06:10:09 -0700277 return true;
278}
279
Erik Språng08127a92016-11-16 16:41:30 +0100280int VP9EncoderImpl::SetRateAllocation(
Erik Språng566124a2018-04-23 12:32:22 +0200281 const VideoBitrateAllocation& bitrate_allocation,
Erik Språng08127a92016-11-16 16:41:30 +0100282 uint32_t frame_rate) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000283 if (!inited_) {
284 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
285 }
286 if (encoder_->err) {
287 return WEBRTC_VIDEO_CODEC_ERROR;
288 }
Erik Språng08127a92016-11-16 16:41:30 +0100289 if (frame_rate < 1) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000290 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
291 }
292 // Update bit rate
Erik Språng08127a92016-11-16 16:41:30 +0100293 if (codec_.maxBitrate > 0 &&
294 bitrate_allocation.get_sum_kbps() > codec_.maxBitrate) {
295 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000296 }
Erik Språng08127a92016-11-16 16:41:30 +0100297
Erik Språng08127a92016-11-16 16:41:30 +0100298 codec_.maxFramerate = frame_rate;
asaperssona9455ab2015-07-31 06:10:09 -0700299
Sergey Silkin86684962018-03-28 19:32:37 +0200300 if (!SetSvcRates(bitrate_allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700301 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
302 }
303
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000304 // Update encoder context
305 if (vpx_codec_enc_config_set(encoder_, config_)) {
306 return WEBRTC_VIDEO_CODEC_ERROR;
307 }
308 return WEBRTC_VIDEO_CODEC_OK;
309}
310
311int VP9EncoderImpl::InitEncode(const VideoCodec* inst,
312 int number_of_cores,
pkasting@chromium.org4591fbd2014-11-20 22:28:14 +0000313 size_t /*max_payload_size*/) {
sprang3958ed82017-08-17 08:12:10 -0700314 if (inst == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000315 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
316 }
317 if (inst->maxFramerate < 1) {
318 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
319 }
320 // Allow zero to represent an unspecified maxBitRate
321 if (inst->maxBitrate > 0 && inst->startBitrate > inst->maxBitrate) {
322 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
323 }
324 if (inst->width < 1 || inst->height < 1) {
325 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
326 }
327 if (number_of_cores < 1) {
328 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
329 }
hta257dc392016-10-25 09:05:06 -0700330 if (inst->VP9().numberOfTemporalLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700331 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
332 }
ilnik2a8c2f52017-02-15 02:23:28 -0800333 // libvpx probably does not support more than 3 spatial layers.
334 if (inst->VP9().numberOfSpatialLayers > 3) {
asaperssona9455ab2015-07-31 06:10:09 -0700335 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
336 }
philipelcfc319b2015-11-10 07:17:23 -0800337
asapersson86956de2016-01-26 01:05:20 -0800338 int ret_val = Release();
339 if (ret_val < 0) {
340 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000341 }
sprang3958ed82017-08-17 08:12:10 -0700342 if (encoder_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000343 encoder_ = new vpx_codec_ctx_t;
344 }
sprang3958ed82017-08-17 08:12:10 -0700345 if (config_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000346 config_ = new vpx_codec_enc_cfg_t;
347 }
348 timestamp_ = 0;
349 if (&codec_ != inst) {
350 codec_ = *inst;
351 }
asaperssona9455ab2015-07-31 06:10:09 -0700352
hta257dc392016-10-25 09:05:06 -0700353 num_spatial_layers_ = inst->VP9().numberOfSpatialLayers;
Niels Möller65fb4042018-04-25 14:46:06 +0200354 RTC_DCHECK_GT(num_spatial_layers_, 0);
hta257dc392016-10-25 09:05:06 -0700355 num_temporal_layers_ = inst->VP9().numberOfTemporalLayers;
asaperssona9455ab2015-07-31 06:10:09 -0700356 if (num_temporal_layers_ == 0)
357 num_temporal_layers_ = 1;
358
Sergey Silkind902d582018-05-18 17:31:19 +0200359 // Init framerate controller.
360 output_framerate_.Reset();
Niels Möllere3cf3d02018-06-13 11:52:16 +0200361 if (codec_.mode == VideoCodecMode::kScreensharing) {
Sergey Silkind902d582018-05-18 17:31:19 +0200362 target_framerate_fps_ = kMaxScreenSharingFramerateFps;
363 } else {
364 target_framerate_fps_.reset();
365 }
366
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200367 is_svc_ = (num_spatial_layers_ > 1 || num_temporal_layers_ > 1);
368 // Flexible mode requires SVC to be enabled since libvpx API only allows
369 // to get reference list in SVC mode.
370 RTC_DCHECK(!inst->VP9().flexibleMode || is_svc_);
371
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000372 // Allocate memory for encoded image
sprang3958ed82017-08-17 08:12:10 -0700373 if (encoded_image_._buffer != nullptr) {
philipelcce46fc2015-12-21 03:04:49 -0800374 delete[] encoded_image_._buffer;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000375 }
nisseeb44b392017-04-28 07:18:05 -0700376 encoded_image_._size =
377 CalcBufferSize(VideoType::kI420, codec_.width, codec_.height);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000378 encoded_image_._buffer = new uint8_t[encoded_image_._size];
379 encoded_image_._completeFrame = true;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000380 // Populate encoder configuration with default values.
381 if (vpx_codec_enc_config_default(vpx_codec_vp9_cx(), config_, 0)) {
382 return WEBRTC_VIDEO_CODEC_ERROR;
383 }
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700384
385 vpx_img_fmt img_fmt = VPX_IMG_FMT_NONE;
386 unsigned int bits_for_storage = 8;
387 switch (profile_) {
388 case VP9Profile::kProfile0:
389 img_fmt = VPX_IMG_FMT_I420;
390 bits_for_storage = 8;
391 config_->g_bit_depth = VPX_BITS_8;
392 config_->g_profile = 0;
393 config_->g_input_bit_depth = 8;
394 break;
395 case VP9Profile::kProfile2:
396 img_fmt = VPX_IMG_FMT_I42016;
397 bits_for_storage = 16;
398 config_->g_bit_depth = VPX_BITS_10;
399 config_->g_profile = 2;
400 config_->g_input_bit_depth = 10;
401 break;
402 }
403
404 // Creating a wrapper to the image - setting image data to nullptr. Actual
405 // pointer will be set in encode. Setting align to 1, as it is meaningless
406 // (actual memory is not allocated).
407 raw_ =
408 vpx_img_wrap(nullptr, img_fmt, codec_.width, codec_.height, 1, nullptr);
409 raw_->bit_depth = bits_for_storage;
410
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000411 config_->g_w = codec_.width;
412 config_->g_h = codec_.height;
413 config_->rc_target_bitrate = inst->startBitrate; // in kbit/s
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200414 config_->g_error_resilient = is_svc_ ? VPX_ERROR_RESILIENT_DEFAULT : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000415 // Setting the time base of the codec.
416 config_->g_timebase.num = 1;
417 config_->g_timebase.den = 90000;
418 config_->g_lag_in_frames = 0; // 0- no frame lagging
419 config_->g_threads = 1;
420 // Rate control settings.
hta257dc392016-10-25 09:05:06 -0700421 config_->rc_dropframe_thresh = inst->VP9().frameDroppingOn ? 30 : 0;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000422 config_->rc_end_usage = VPX_CBR;
423 config_->g_pass = VPX_RC_ONE_PASS;
424 config_->rc_min_quantizer = 2;
marpan@webrtc.orgdc8a9da2015-01-27 23:08:24 +0000425 config_->rc_max_quantizer = 52;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000426 config_->rc_undershoot_pct = 50;
427 config_->rc_overshoot_pct = 50;
428 config_->rc_buf_initial_sz = 500;
429 config_->rc_buf_optimal_sz = 600;
430 config_->rc_buf_sz = 1000;
431 // Set the maximum target size of any key-frame.
432 rc_max_intra_target_ = MaxIntraTarget(config_->rc_buf_optimal_sz);
hta257dc392016-10-25 09:05:06 -0700433 if (inst->VP9().keyFrameInterval > 0) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000434 config_->kf_mode = VPX_KF_AUTO;
hta257dc392016-10-25 09:05:06 -0700435 config_->kf_max_dist = inst->VP9().keyFrameInterval;
Åsa Perssonff24c042015-12-04 10:58:08 +0100436 // Needs to be set (in svc mode) to get correct periodic key frame interval
437 // (will have no effect in non-svc).
438 config_->kf_min_dist = config_->kf_max_dist;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000439 } else {
440 config_->kf_mode = VPX_KF_DISABLED;
441 }
hta257dc392016-10-25 09:05:06 -0700442 config_->rc_resize_allowed = inst->VP9().automaticResizeOn ? 1 : 0;
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000443 // Determine number of threads based on the image size and #cores.
philipelcce46fc2015-12-21 03:04:49 -0800444 config_->g_threads =
445 NumberOfThreads(config_->g_w, config_->g_h, number_of_cores);
asaperssona9455ab2015-07-31 06:10:09 -0700446
Marco6e89b252015-07-07 14:40:38 -0700447 cpu_speed_ = GetCpuSpeed(config_->g_w, config_->g_h);
asaperssona9455ab2015-07-31 06:10:09 -0700448
449 // TODO(asapersson): Check configuration of temporal switch up and increase
450 // pattern length.
hta257dc392016-10-25 09:05:06 -0700451 is_flexible_mode_ = inst->VP9().flexibleMode;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200452
453 // TODO(ssilkin): Only non-flexible mode is supported for now.
454 RTC_DCHECK(!is_flexible_mode_);
455
456 if (num_temporal_layers_ == 1) {
asaperssona9455ab2015-07-31 06:10:09 -0700457 gof_.SetGofInfoVP9(kTemporalStructureMode1);
458 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_NOLAYERING;
459 config_->ts_number_layers = 1;
460 config_->ts_rate_decimator[0] = 1;
461 config_->ts_periodicity = 1;
462 config_->ts_layer_id[0] = 0;
463 } else if (num_temporal_layers_ == 2) {
464 gof_.SetGofInfoVP9(kTemporalStructureMode2);
465 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0101;
466 config_->ts_number_layers = 2;
467 config_->ts_rate_decimator[0] = 2;
468 config_->ts_rate_decimator[1] = 1;
469 config_->ts_periodicity = 2;
470 config_->ts_layer_id[0] = 0;
471 config_->ts_layer_id[1] = 1;
472 } else if (num_temporal_layers_ == 3) {
473 gof_.SetGofInfoVP9(kTemporalStructureMode3);
474 config_->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_0212;
475 config_->ts_number_layers = 3;
476 config_->ts_rate_decimator[0] = 4;
477 config_->ts_rate_decimator[1] = 2;
478 config_->ts_rate_decimator[2] = 1;
479 config_->ts_periodicity = 4;
480 config_->ts_layer_id[0] = 0;
481 config_->ts_layer_id[1] = 2;
482 config_->ts_layer_id[2] = 1;
483 config_->ts_layer_id[3] = 2;
484 } else {
485 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
486 }
487
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200488 inter_layer_pred_ = inst->VP9().interLayerPred;
489
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200490 ref_buf_.clear();
491
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000492 return InitAndSetControlSettings(inst);
493}
494
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000495int VP9EncoderImpl::NumberOfThreads(int width,
496 int height,
497 int number_of_cores) {
498 // Keep the number of encoder threads equal to the possible number of column
499 // tiles, which is (1, 2, 4, 8). See comments below for VP9E_SET_TILE_COLUMNS.
500 if (width * height >= 1280 * 720 && number_of_cores > 4) {
501 return 4;
jianj23173a32017-07-12 16:11:09 -0700502 } else if (width * height >= 640 * 360 && number_of_cores > 2) {
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000503 return 2;
504 } else {
Yves Gerey665174f2018-06-19 15:03:05 +0200505// Use 2 threads for low res on ARM.
Jerome Jiang831af372017-12-05 10:44:35 -0800506#if defined(WEBRTC_ARCH_ARM) || defined(WEBRTC_ARCH_ARM64) || \
507 defined(WEBRTC_ANDROID)
508 if (width * height >= 320 * 180 && number_of_cores > 2) {
509 return 2;
510 }
511#endif
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000512 // 1 thread less than VGA.
513 return 1;
514 }
515}
516
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000517int VP9EncoderImpl::InitAndSetControlSettings(const VideoCodec* inst) {
Åsa Perssonff24c042015-12-04 10:58:08 +0100518 // Set QP-min/max per spatial and temporal layer.
519 int tot_num_layers = num_spatial_layers_ * num_temporal_layers_;
520 for (int i = 0; i < tot_num_layers; ++i) {
johannkoenig8225c402017-01-26 13:23:44 -0800521 svc_params_.max_quantizers[i] = config_->rc_max_quantizer;
522 svc_params_.min_quantizers[i] = config_->rc_min_quantizer;
Åsa Perssonff24c042015-12-04 10:58:08 +0100523 }
asaperssona9455ab2015-07-31 06:10:09 -0700524 config_->ss_number_layers = num_spatial_layers_;
sprangce4aef12015-11-02 07:23:20 -0800525 if (ExplicitlyConfiguredSpatialLayers()) {
526 for (int i = 0; i < num_spatial_layers_; ++i) {
527 const auto& layer = codec_.spatialLayers[i];
Rasmus Brandt58cd3852018-06-26 13:41:16 +0200528 RTC_CHECK_GT(layer.width, 0);
Sergey Silkin13e74342018-03-02 12:28:00 +0100529 const int scale_factor = codec_.width / layer.width;
530 RTC_DCHECK_GT(scale_factor, 0);
531
532 // Ensure scaler factor is integer.
533 if (scale_factor * layer.width != codec_.width) {
534 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
535 }
536
537 // Ensure scale factor is the same in both dimensions.
538 if (scale_factor * layer.height != codec_.height) {
539 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
540 }
541
542 // Ensure scale factor is power of two.
543 const bool is_pow_of_two = (scale_factor & (scale_factor - 1)) == 0;
544 if (!is_pow_of_two) {
545 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
546 }
547
548 svc_params_.scaling_factor_num[i] = 1;
549 svc_params_.scaling_factor_den[i] = scale_factor;
sprangce4aef12015-11-02 07:23:20 -0800550 }
551 } else {
552 int scaling_factor_num = 256;
553 for (int i = num_spatial_layers_ - 1; i >= 0; --i) {
sprangce4aef12015-11-02 07:23:20 -0800554 // 1:2 scaling in each dimension.
johannkoenig8225c402017-01-26 13:23:44 -0800555 svc_params_.scaling_factor_num[i] = scaling_factor_num;
556 svc_params_.scaling_factor_den[i] = 256;
sprangce4aef12015-11-02 07:23:20 -0800557 }
asaperssona9455ab2015-07-31 06:10:09 -0700558 }
559
Sergey Silkin86684962018-03-28 19:32:37 +0200560 SvcRateAllocator init_allocator(codec_);
Erik Språng566124a2018-04-23 12:32:22 +0200561 VideoBitrateAllocation allocation = init_allocator.GetAllocation(
Sergey Silkin86684962018-03-28 19:32:37 +0200562 inst->startBitrate * 1000, inst->maxFramerate);
563 if (!SetSvcRates(allocation)) {
asaperssona9455ab2015-07-31 06:10:09 -0700564 return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
565 }
566
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700567 const vpx_codec_err_t rv = vpx_codec_enc_init(
568 encoder_, vpx_codec_vp9_cx(), config_,
569 config_->g_bit_depth == VPX_BITS_8 ? 0 : VPX_CODEC_USE_HIGHBITDEPTH);
570 if (rv != VPX_CODEC_OK) {
571 RTC_LOG(LS_ERROR) << "Init error: " << vpx_codec_err_to_string(rv);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000572 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
573 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000574 vpx_codec_control(encoder_, VP8E_SET_CPUUSED, cpu_speed_);
575 vpx_codec_control(encoder_, VP8E_SET_MAX_INTRA_BITRATE_PCT,
576 rc_max_intra_target_);
577 vpx_codec_control(encoder_, VP9E_SET_AQ_MODE,
hta257dc392016-10-25 09:05:06 -0700578 inst->VP9().adaptiveQpMode ? 3 : 0);
asaperssona9455ab2015-07-31 06:10:09 -0700579
jianj822e5932017-07-12 16:09:58 -0700580 vpx_codec_control(encoder_, VP9E_SET_FRAME_PARALLEL_DECODING, 0);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200581
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200582 if (is_svc_) {
583 vpx_codec_control(encoder_, VP9E_SET_SVC, 1);
584 vpx_codec_control(encoder_, VP9E_SET_SVC_PARAMETERS, &svc_params_);
asaperssona9455ab2015-07-31 06:10:09 -0700585 }
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200586
587 if (num_spatial_layers_ > 1) {
588 switch (inter_layer_pred_) {
589 case InterLayerPredMode::kOn:
590 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 0);
591 break;
592 case InterLayerPredMode::kOff:
593 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 1);
594 break;
595 case InterLayerPredMode::kOnKeyPic:
596 vpx_codec_control(encoder_, VP9E_SET_SVC_INTER_LAYER_PRED, 2);
597 break;
598 default:
599 RTC_NOTREACHED();
600 }
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200601
Sergey Silkinee203362018-05-30 11:34:08 +0200602 // Configure encoder to drop entire superframe whenever it needs to drop
603 // a layer. This mode is prefered over per-layer dropping which causes
604 // quality flickering and is not compatible with RTP non-flexible mode.
605 vpx_svc_frame_drop_t svc_drop_frame;
606 memset(&svc_drop_frame, 0, sizeof(svc_drop_frame));
607 svc_drop_frame.framedrop_mode = FULL_SUPERFRAME_DROP;
Sergey Silkind45b3452018-05-31 16:00:24 +0200608 svc_drop_frame.max_consec_drop = std::numeric_limits<int>::max();
Sergey Silkinee203362018-05-30 11:34:08 +0200609 for (size_t i = 0; i < num_spatial_layers_; ++i) {
610 svc_drop_frame.framedrop_thresh[i] = config_->rc_dropframe_thresh;
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200611 }
Sergey Silkinee203362018-05-30 11:34:08 +0200612 vpx_codec_control(encoder_, VP9E_SET_SVC_FRAME_DROP_LAYER, &svc_drop_frame);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200613 }
614
asaperssona9455ab2015-07-31 06:10:09 -0700615 // Register callback for getting each spatial layer.
616 vpx_codec_priv_output_cx_pkt_cb_pair_t cbp = {
philipelcce46fc2015-12-21 03:04:49 -0800617 VP9EncoderImpl::EncoderOutputCodedPacketCallback,
618 reinterpret_cast<void*>(this)};
619 vpx_codec_control(encoder_, VP9E_REGISTER_CX_CALLBACK,
620 reinterpret_cast<void*>(&cbp));
asaperssona9455ab2015-07-31 06:10:09 -0700621
marpan@webrtc.org38d11b82015-01-26 15:21:36 +0000622 // Control function to set the number of column tiles in encoding a frame, in
623 // log2 unit: e.g., 0 = 1 tile column, 1 = 2 tile columns, 2 = 4 tile columns.
624 // The number tile columns will be capped by the encoder based on image size
625 // (minimum width of tile column is 256 pixels, maximum is 4096).
626 vpx_codec_control(encoder_, VP9E_SET_TILE_COLUMNS, (config_->g_threads >> 1));
jianjcb5d1152017-03-28 23:56:08 -0700627
628 // Turn on row-based multithreading.
629 vpx_codec_control(encoder_, VP9E_SET_ROW_MT, 1);
jianj6bf57e32017-06-05 13:43:49 -0700630
Alex Glaznevfecb7c32016-03-31 14:23:27 -0700631#if !defined(WEBRTC_ARCH_ARM) && !defined(WEBRTC_ARCH_ARM64) && \
Yves Gerey665174f2018-06-19 15:03:05 +0200632 !defined(ANDROID)
jianj6bf57e32017-06-05 13:43:49 -0700633 // Do not enable the denoiser on ARM since optimization is pending.
634 // Denoiser is on by default on other platforms.
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000635 vpx_codec_control(encoder_, VP9E_SET_NOISE_SENSITIVITY,
hta257dc392016-10-25 09:05:06 -0700636 inst->VP9().denoisingOn ? 1 : 0);
marpan@webrtc.org16a87b92015-03-05 22:19:00 +0000637#endif
jianj6bf57e32017-06-05 13:43:49 -0700638
Niels Möllere3cf3d02018-06-13 11:52:16 +0200639 if (codec_.mode == VideoCodecMode::kScreensharing) {
ivica242d6382015-09-04 06:13:23 -0700640 // Adjust internal parameters to screen content.
641 vpx_codec_control(encoder_, VP9E_SET_TUNE_CONTENT, 1);
ivica242d6382015-09-04 06:13:23 -0700642 }
Marco2520e722015-09-16 14:05:00 -0700643 // Enable encoder skip of static/low content blocks.
644 vpx_codec_control(encoder_, VP8E_SET_STATIC_THRESHOLD, 1);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000645 inited_ = true;
646 return WEBRTC_VIDEO_CODEC_OK;
647}
648
649uint32_t VP9EncoderImpl::MaxIntraTarget(uint32_t optimal_buffer_size) {
650 // Set max to the optimal buffer level (normalized by target BR),
651 // and scaled by a scale_par.
652 // Max target size = scale_par * optimal_buffer_size * targetBR[Kbps].
653 // This value is presented in percentage of perFrameBw:
654 // perFrameBw = targetBR[Kbps] * 1000 / framerate.
655 // The target in % is as follows:
656 float scale_par = 0.5;
657 uint32_t target_pct =
658 optimal_buffer_size * scale_par * codec_.maxFramerate / 10;
659 // Don't go below 3 times the per frame bandwidth.
660 const uint32_t min_intra_size = 300;
philipelcce46fc2015-12-21 03:04:49 -0800661 return (target_pct < min_intra_size) ? min_intra_size : target_pct;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000662}
663
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -0700664int VP9EncoderImpl::Encode(const VideoFrame& input_image,
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000665 const CodecSpecificInfo* codec_specific_info,
pbos22993e12015-10-19 02:39:06 -0700666 const std::vector<FrameType>* frame_types) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000667 if (!inited_) {
668 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
669 }
sprang3958ed82017-08-17 08:12:10 -0700670 if (encoded_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000671 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
672 }
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200673
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000674 // We only support one stream at the moment.
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200675 if (frame_types && !frame_types->empty()) {
676 if ((*frame_types)[0] == kVideoFrameKey) {
677 force_key_frame_ = true;
678 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000679 }
Sergey Silkind902d582018-05-18 17:31:19 +0200680
Niels Möllere3cf3d02018-06-13 11:52:16 +0200681 if (VideoCodecMode::kScreensharing == codec_.mode && !force_key_frame_) {
Sergey Silkind902d582018-05-18 17:31:19 +0200682 if (DropFrame(input_image.timestamp())) {
683 return WEBRTC_VIDEO_CODEC_OK;
684 }
685 }
686
kwiberg352444f2016-11-28 15:58:53 -0800687 RTC_DCHECK_EQ(input_image.width(), raw_->d_w);
688 RTC_DCHECK_EQ(input_image.height(), raw_->d_h);
asaperssona9455ab2015-07-31 06:10:09 -0700689
690 // Set input image for use in the callback.
691 // This was necessary since you need some information from input_image.
692 // You can save only the necessary information (such as timestamp) instead of
693 // doing this.
694 input_image_ = &input_image;
695
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700696 // Keep reference to buffer until encode completes.
697 rtc::scoped_refptr<I420BufferInterface> i420_buffer;
698 rtc::scoped_refptr<I010BufferInterface> i010_buffer;
699 switch (profile_) {
700 case VP9Profile::kProfile0: {
701 i420_buffer = input_image.video_frame_buffer()->ToI420();
702 // Image in vpx_image_t format.
703 // Input image is const. VPX's raw image is not defined as const.
704 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(i420_buffer->DataY());
705 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(i420_buffer->DataU());
706 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(i420_buffer->DataV());
707 raw_->stride[VPX_PLANE_Y] = i420_buffer->StrideY();
708 raw_->stride[VPX_PLANE_U] = i420_buffer->StrideU();
709 raw_->stride[VPX_PLANE_V] = i420_buffer->StrideV();
710 break;
711 }
712 case VP9Profile::kProfile2: {
713 // We can inject kI010 frames directly for encode. All other formats
714 // should be converted to it.
715 switch (input_image.video_frame_buffer()->type()) {
716 case VideoFrameBuffer::Type::kI010: {
717 i010_buffer = input_image.video_frame_buffer()->GetI010();
718 break;
719 }
720 default: {
721 i010_buffer =
722 I010Buffer::Copy(*input_image.video_frame_buffer()->ToI420());
723 }
724 }
725 raw_->planes[VPX_PLANE_Y] = const_cast<uint8_t*>(
726 reinterpret_cast<const uint8_t*>(i010_buffer->DataY()));
727 raw_->planes[VPX_PLANE_U] = const_cast<uint8_t*>(
728 reinterpret_cast<const uint8_t*>(i010_buffer->DataU()));
729 raw_->planes[VPX_PLANE_V] = const_cast<uint8_t*>(
730 reinterpret_cast<const uint8_t*>(i010_buffer->DataV()));
731 raw_->stride[VPX_PLANE_Y] = i010_buffer->StrideY() * 2;
732 raw_->stride[VPX_PLANE_U] = i010_buffer->StrideU() * 2;
733 raw_->stride[VPX_PLANE_V] = i010_buffer->StrideV() * 2;
734 break;
735 }
736 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000737
philipelcfc319b2015-11-10 07:17:23 -0800738 vpx_enc_frame_flags_t flags = 0;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200739 if (force_key_frame_) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000740 flags = VPX_EFLAG_FORCE_KF;
741 }
philipelcfc319b2015-11-10 07:17:23 -0800742
sprang3958ed82017-08-17 08:12:10 -0700743 RTC_CHECK_GT(codec_.maxFramerate, 0);
Sergey Silkind902d582018-05-18 17:31:19 +0200744 uint32_t duration =
745 90000 / target_framerate_fps_.value_or(codec_.maxFramerate);
Emircan Uysaler0823eec2018-07-13 17:10:00 -0700746 const vpx_codec_err_t rv = vpx_codec_encode(encoder_, raw_, timestamp_,
747 duration, flags, VPX_DL_REALTIME);
748 if (rv != VPX_CODEC_OK) {
749 RTC_LOG(LS_ERROR) << "Encoding error: " << vpx_codec_err_to_string(rv)
750 << "\n"
751 << "Details: " << vpx_codec_error(encoder_) << "\n"
752 << vpx_codec_error_detail(encoder_);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000753 return WEBRTC_VIDEO_CODEC_ERROR;
754 }
755 timestamp_ += duration;
asaperssona9455ab2015-07-31 06:10:09 -0700756
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200757 const bool end_of_picture = true;
758 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200759
asaperssona9455ab2015-07-31 06:10:09 -0700760 return WEBRTC_VIDEO_CODEC_OK;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000761}
762
763void VP9EncoderImpl::PopulateCodecSpecific(CodecSpecificInfo* codec_specific,
philipelcce46fc2015-12-21 03:04:49 -0800764 const vpx_codec_cx_pkt& pkt,
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200765 uint32_t timestamp,
766 bool first_frame_in_picture) {
sprang3958ed82017-08-17 08:12:10 -0700767 RTC_CHECK(codec_specific != nullptr);
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000768 codec_specific->codecType = kVideoCodecVP9;
perkj275afc52016-09-01 00:21:16 -0700769 codec_specific->codec_name = ImplementationName();
philipelcce46fc2015-12-21 03:04:49 -0800770 CodecSpecificInfoVP9* vp9_info = &(codec_specific->codecSpecific.VP9);
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200771
772 vp9_info->first_frame_in_picture = first_frame_in_picture;
hta257dc392016-10-25 09:05:06 -0700773 vp9_info->flexible_mode = codec_.VP9()->flexibleMode;
774 vp9_info->ss_data_available =
775 ((pkt.data.frame.flags & VPX_FRAME_IS_KEY) && !codec_.VP9()->flexibleMode)
776 ? true
777 : false;
asaperssona9455ab2015-07-31 06:10:09 -0700778
779 vpx_svc_layer_id_t layer_id = {0};
780 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
781
sprang3958ed82017-08-17 08:12:10 -0700782 RTC_CHECK_GT(num_temporal_layers_, 0);
“Michael23c5a992018-06-21 11:07:21 -0500783 RTC_CHECK_GT(num_active_spatial_layers_, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700784 if (num_temporal_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700785 RTC_CHECK_EQ(layer_id.temporal_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700786 vp9_info->temporal_idx = kNoTemporalIdx;
787 } else {
788 vp9_info->temporal_idx = layer_id.temporal_layer_id;
789 }
“Michael23c5a992018-06-21 11:07:21 -0500790 if (num_active_spatial_layers_ == 1) {
sprang3958ed82017-08-17 08:12:10 -0700791 RTC_CHECK_EQ(layer_id.spatial_layer_id, 0);
asaperssona9455ab2015-07-31 06:10:09 -0700792 vp9_info->spatial_idx = kNoSpatialIdx;
793 } else {
794 vp9_info->spatial_idx = layer_id.spatial_layer_id;
795 }
796 if (layer_id.spatial_layer_id != 0) {
797 vp9_info->ss_data_available = false;
798 }
799
asaperssona9455ab2015-07-31 06:10:09 -0700800 // TODO(asapersson): this info has to be obtained from the encoder.
asaperssoncb50c962015-11-18 01:58:55 -0800801 vp9_info->temporal_up_switch = false;
asaperssona9455ab2015-07-31 06:10:09 -0700802
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200803 if (pkt.data.frame.flags & VPX_FRAME_IS_KEY) {
804 pics_since_key_ = 0;
805 } else if (first_frame_in_picture) {
806 ++pics_since_key_;
asaperssona9455ab2015-07-31 06:10:09 -0700807 }
808
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200809 const bool is_key_pic = (pics_since_key_ == 0);
810 const bool is_inter_layer_pred_allowed =
811 (inter_layer_pred_ == InterLayerPredMode::kOn ||
812 (inter_layer_pred_ == InterLayerPredMode::kOnKeyPic && is_key_pic));
813
814 // Always set inter_layer_predicted to true on high layer frame if inter-layer
815 // prediction (ILP) is allowed even if encoder didn't actually use it.
816 // Setting inter_layer_predicted to false would allow receiver to decode high
817 // layer frame without decoding low layer frame. If that would happen (e.g.
818 // if low layer frame is lost) then receiver won't be able to decode next high
819 // layer frame which uses ILP.
820 vp9_info->inter_layer_predicted =
821 first_frame_in_picture ? false : is_inter_layer_pred_allowed;
822
823 const bool is_last_layer =
“Michael23c5a992018-06-21 11:07:21 -0500824 (layer_id.spatial_layer_id + 1 == num_active_spatial_layers_);
Sergey Silkin6a8f30e2018-04-26 11:03:49 +0200825 vp9_info->non_ref_for_inter_layer_pred =
826 is_last_layer ? true : !is_inter_layer_pred_allowed;
asapersson00ac85e2015-11-11 05:30:48 -0800827
ivica7f6a6fc2015-09-08 02:40:29 -0700828 // Always populate this, so that the packetizer can properly set the marker
829 // bit.
“Michael23c5a992018-06-21 11:07:21 -0500830 vp9_info->num_spatial_layers = num_active_spatial_layers_;
philipelcfc319b2015-11-10 07:17:23 -0800831
Sergey Silkinbe71a1e2018-05-17 16:46:43 +0200832 RTC_DCHECK(!vp9_info->flexible_mode);
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200833
834 vp9_info->num_ref_pics = 0;
835 if (vp9_info->flexible_mode) {
836 vp9_info->gof_idx = kNoGofIdx;
837 FillReferenceIndices(pkt, pics_since_key_, vp9_info->inter_layer_predicted,
838 vp9_info);
839 } else {
840 vp9_info->gof_idx =
841 static_cast<uint8_t>(pics_since_key_ % gof_.num_frames_in_gof);
842 vp9_info->temporal_up_switch = gof_.temporal_up_switch[vp9_info->gof_idx];
843 vp9_info->num_ref_pics = gof_.num_ref_pics[vp9_info->gof_idx];
844 }
845
846 vp9_info->inter_pic_predicted = (!is_key_pic && vp9_info->num_ref_pics > 0);
847
asaperssona9455ab2015-07-31 06:10:09 -0700848 if (vp9_info->ss_data_available) {
asaperssona9455ab2015-07-31 06:10:09 -0700849 vp9_info->spatial_layer_resolution_present = true;
“Michael23c5a992018-06-21 11:07:21 -0500850 for (size_t i = 0; i < num_active_spatial_layers_; ++i) {
Yves Gerey665174f2018-06-19 15:03:05 +0200851 vp9_info->width[i] = codec_.width * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800852 svc_params_.scaling_factor_den[i];
Yves Gerey665174f2018-06-19 15:03:05 +0200853 vp9_info->height[i] = codec_.height * svc_params_.scaling_factor_num[i] /
johannkoenig8225c402017-01-26 13:23:44 -0800854 svc_params_.scaling_factor_den[i];
asaperssona9455ab2015-07-31 06:10:09 -0700855 }
856 if (!vp9_info->flexible_mode) {
857 vp9_info->gof.CopyGofInfoVP9(gof_);
858 }
859 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000860}
861
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +0200862void VP9EncoderImpl::FillReferenceIndices(const vpx_codec_cx_pkt& pkt,
863 const size_t pic_num,
864 const bool inter_layer_predicted,
865 CodecSpecificInfoVP9* vp9_info) {
866 vpx_svc_layer_id_t layer_id = {0};
867 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
868
869 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
870 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
871
872 std::vector<RefFrameBuffer> ref_buf_list;
873 if (enc_layer_conf.reference_last[layer_id.spatial_layer_id]) {
874 const size_t fb_idx = enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id];
875 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
876 ref_buf_list.push_back(ref_buf_.at(fb_idx));
877 }
878
879 if (enc_layer_conf.reference_alt_ref[layer_id.spatial_layer_id]) {
880 const size_t fb_idx = enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id];
881 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
882 ref_buf_list.push_back(ref_buf_.at(fb_idx));
883 }
884
885 if (enc_layer_conf.reference_golden[layer_id.spatial_layer_id]) {
886 const size_t fb_idx = enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id];
887 RTC_DCHECK(ref_buf_.find(fb_idx) != ref_buf_.end());
888 ref_buf_list.push_back(ref_buf_.at(fb_idx));
889 }
890
891 size_t max_ref_temporal_layer_id = 0;
892
893 vp9_info->num_ref_pics = 0;
894 for (const RefFrameBuffer& ref_buf : ref_buf_list) {
895 RTC_DCHECK_LE(ref_buf.pic_num, pic_num);
896 if (ref_buf.pic_num < pic_num) {
897 if (inter_layer_pred_ != InterLayerPredMode::kOn) {
898 // RTP spec limits temporal prediction to the same spatial layer.
899 // It is safe to ignore this requirement if inter-layer prediction is
900 // enabled for all frames when all base frames are relayed to receiver.
901 RTC_DCHECK_EQ(ref_buf.spatial_layer_id, layer_id.spatial_layer_id);
902 }
903 RTC_DCHECK_LE(ref_buf.temporal_layer_id, layer_id.temporal_layer_id);
904
905 const size_t p_diff = pic_num - ref_buf.pic_num;
906 RTC_DCHECK_LE(p_diff, 127UL);
907
908 vp9_info->p_diff[vp9_info->num_ref_pics] = static_cast<uint8_t>(p_diff);
909 ++vp9_info->num_ref_pics;
910
911 max_ref_temporal_layer_id =
912 std::max(max_ref_temporal_layer_id, ref_buf.temporal_layer_id);
913 } else {
914 RTC_DCHECK(inter_layer_predicted);
915 // RTP spec only allows to use previous spatial layer for inter-layer
916 // prediction.
917 RTC_DCHECK_EQ(ref_buf.spatial_layer_id + 1, layer_id.spatial_layer_id);
918 }
919 }
920
921 vp9_info->temporal_up_switch =
922 (max_ref_temporal_layer_id <
923 static_cast<size_t>(layer_id.temporal_layer_id));
924}
925
926void VP9EncoderImpl::UpdateReferenceBuffers(const vpx_codec_cx_pkt& pkt,
927 const size_t pic_num) {
928 vpx_svc_layer_id_t layer_id = {0};
929 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
930
931 vpx_svc_ref_frame_config_t enc_layer_conf = {{0}};
932 vpx_codec_control(encoder_, VP9E_GET_SVC_REF_FRAME_CONFIG, &enc_layer_conf);
933
934 const bool is_key_frame =
935 (pkt.data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
936
937 RefFrameBuffer frame_buf(pic_num, layer_id.spatial_layer_id,
938 layer_id.temporal_layer_id);
939
940 if (is_key_frame && layer_id.spatial_layer_id == 0) {
941 // Key frame updates all ref buffers.
942 for (size_t i = 0; i < kNumVp9Buffers; ++i) {
943 ref_buf_[i] = frame_buf;
944 }
945 } else {
946 if (enc_layer_conf.update_last[layer_id.spatial_layer_id]) {
947 ref_buf_[enc_layer_conf.lst_fb_idx[layer_id.spatial_layer_id]] =
948 frame_buf;
949 }
950
951 if (enc_layer_conf.update_alt_ref[layer_id.spatial_layer_id]) {
952 ref_buf_[enc_layer_conf.alt_fb_idx[layer_id.spatial_layer_id]] =
953 frame_buf;
954 }
955
956 if (enc_layer_conf.update_golden[layer_id.spatial_layer_id]) {
957 ref_buf_[enc_layer_conf.gld_fb_idx[layer_id.spatial_layer_id]] =
958 frame_buf;
959 }
960 }
961}
962
asaperssona9455ab2015-07-31 06:10:09 -0700963int VP9EncoderImpl::GetEncodedLayerFrame(const vpx_codec_cx_pkt* pkt) {
asapersson86956de2016-01-26 01:05:20 -0800964 RTC_DCHECK_EQ(pkt->kind, VPX_CODEC_CX_FRAME_PKT);
asaperssona9455ab2015-07-31 06:10:09 -0700965
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200966 if (pkt->data.frame.sz == 0) {
967 // Ignore dropped frame.
968 return WEBRTC_VIDEO_CODEC_OK;
969 }
970
Sergey Silkin07f80cc2018-04-09 13:11:59 +0200971 vpx_svc_layer_id_t layer_id = {0};
972 vpx_codec_control(encoder_, VP9E_GET_SVC_LAYER_ID, &layer_id);
973
974 const bool first_frame_in_picture = encoded_image_._length == 0;
975 // Ensure we don't buffer layers of previous picture (superframe).
976 RTC_DCHECK(first_frame_in_picture || layer_id.spatial_layer_id > 0);
977
Sergey Silkinbc0f0d32018-04-24 21:29:14 +0200978 const bool end_of_picture = false;
979 DeliverBufferedFrame(end_of_picture);
Sergey Silkin2a1f1832018-04-04 11:45:41 +0200980
asaperssond9f641e2016-01-21 01:11:35 -0800981 if (pkt->data.frame.sz > encoded_image_._size) {
982 delete[] encoded_image_._buffer;
983 encoded_image_._size = pkt->data.frame.sz;
984 encoded_image_._buffer = new uint8_t[encoded_image_._size];
985 }
asapersson86956de2016-01-26 01:05:20 -0800986 memcpy(encoded_image_._buffer, pkt->data.frame.buf, pkt->data.frame.sz);
987 encoded_image_._length = pkt->data.frame.sz;
asaperssond9f641e2016-01-21 01:11:35 -0800988
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200989 const bool is_key_frame =
990 (pkt->data.frame.flags & VPX_FRAME_IS_KEY) ? true : false;
991 // Ensure encoder issued key frame on request.
992 RTC_DCHECK(is_key_frame || !force_key_frame_);
993
asaperssona9455ab2015-07-31 06:10:09 -0700994 // Check if encoded frame is a key frame.
asapersson86956de2016-01-26 01:05:20 -0800995 encoded_image_._frameType = kVideoFrameDelta;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200996 if (is_key_frame) {
Peter Boström49e196a2015-10-23 15:58:18 +0200997 encoded_image_._frameType = kVideoFrameKey;
Sergey Silkinbd0954e2018-05-03 14:14:09 +0200998 force_key_frame_ = false;
marpan@webrtc.org5b883172014-11-01 06:10:48 +0000999 }
asapersson86956de2016-01-26 01:05:20 -08001000 RTC_DCHECK_LE(encoded_image_._length, encoded_image_._size);
1001
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001002 memset(&codec_specific_, 0, sizeof(codec_specific_));
Sergey Silkin07f80cc2018-04-09 13:11:59 +02001003 PopulateCodecSpecific(&codec_specific_, *pkt, input_image_->timestamp(),
1004 first_frame_in_picture);
asaperssona9455ab2015-07-31 06:10:09 -07001005
Sergey Silkin4e6cd5e2018-05-28 12:26:36 +02001006 if (is_flexible_mode_) {
1007 UpdateReferenceBuffers(*pkt, pics_since_key_);
1008 }
1009
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001010 TRACE_COUNTER1("webrtc", "EncodedFrameSize", encoded_image_._length);
1011 encoded_image_._timeStamp = input_image_->timestamp();
1012 encoded_image_.capture_time_ms_ = input_image_->render_time_ms();
1013 encoded_image_.rotation_ = input_image_->rotation();
Niels Möllere3cf3d02018-06-13 11:52:16 +02001014 encoded_image_.content_type_ = (codec_.mode == VideoCodecMode::kScreensharing)
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001015 ? VideoContentType::SCREENSHARE
1016 : VideoContentType::UNSPECIFIED;
1017 encoded_image_._encodedHeight =
1018 pkt->data.frame.height[layer_id.spatial_layer_id];
1019 encoded_image_._encodedWidth =
1020 pkt->data.frame.width[layer_id.spatial_layer_id];
Ilya Nikolaevskiyb6c462d2018-06-05 15:21:32 +02001021 encoded_image_.timing_.flags = VideoSendTiming::kInvalid;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001022 int qp = -1;
1023 vpx_codec_control(encoder_, VP8E_GET_LAST_QUANTIZER, &qp);
1024 encoded_image_.qp_ = qp;
ilnik04f4d122017-06-19 07:18:55 -07001025
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001026 return WEBRTC_VIDEO_CODEC_OK;
1027}
1028
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001029void VP9EncoderImpl::DeliverBufferedFrame(bool end_of_picture) {
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001030 if (encoded_image_._length > 0) {
Sergey Silkinbc0f0d32018-04-24 21:29:14 +02001031 codec_specific_.codecSpecific.VP9.end_of_picture = end_of_picture;
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001032
1033 // No data partitioning in VP9, so 1 partition only.
1034 int part_idx = 0;
1035 RTPFragmentationHeader frag_info;
1036 frag_info.VerifyAndAllocateFragmentationHeader(1);
1037 frag_info.fragmentationOffset[part_idx] = 0;
1038 frag_info.fragmentationLength[part_idx] = encoded_image_._length;
1039 frag_info.fragmentationPlType[part_idx] = 0;
1040 frag_info.fragmentationTimeDiff[part_idx] = 0;
1041
1042 encoded_complete_callback_->OnEncodedImage(encoded_image_, &codec_specific_,
1043 &frag_info);
1044 encoded_image_._length = 0;
Sergey Silkind902d582018-05-18 17:31:19 +02001045
1046 if (end_of_picture) {
1047 const uint32_t timestamp_ms =
1048 1000 * encoded_image_._timeStamp / kVideoPayloadTypeFrequency;
1049 output_framerate_.Update(1, timestamp_ms);
1050 last_encoded_frame_rtp_timestamp_ = encoded_image_._timeStamp;
1051 }
Sergey Silkin2a1f1832018-04-04 11:45:41 +02001052 }
1053}
1054
Sergey Silkind902d582018-05-18 17:31:19 +02001055bool VP9EncoderImpl::DropFrame(uint32_t rtp_timestamp) {
1056 if (target_framerate_fps_) {
1057 if (rtp_timestamp < last_encoded_frame_rtp_timestamp_) {
1058 // Timestamp has wrapped around. Reset framerate statistic.
1059 output_framerate_.Reset();
1060 return false;
1061 }
1062
1063 const uint32_t timestamp_ms =
1064 1000 * rtp_timestamp / kVideoPayloadTypeFrequency;
1065 const uint32_t framerate_fps =
1066 output_framerate_.Rate(timestamp_ms).value_or(0);
1067 if (framerate_fps > *target_framerate_fps_) {
1068 return true;
1069 }
1070
1071 // Primarily check if frame interval is too short using frame timestamps,
1072 // as if they are correct they won't be affected by queuing in webrtc.
1073 const uint32_t expected_frame_interval =
1074 kVideoPayloadTypeFrequency / *target_framerate_fps_;
1075
1076 const uint32_t ts_diff = rtp_timestamp - last_encoded_frame_rtp_timestamp_;
1077 if (ts_diff < 85 * expected_frame_interval / 100) {
1078 return true;
1079 }
1080 }
1081
1082 return false;
1083}
1084
pkasting@chromium.org16825b12015-01-12 21:51:21 +00001085int VP9EncoderImpl::SetChannelParameters(uint32_t packet_loss, int64_t rtt) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001086 return WEBRTC_VIDEO_CODEC_OK;
1087}
1088
1089int VP9EncoderImpl::RegisterEncodeCompleteCallback(
1090 EncodedImageCallback* callback) {
1091 encoded_complete_callback_ = callback;
1092 return WEBRTC_VIDEO_CODEC_OK;
1093}
1094
Peter Boströmb7d9a972015-12-18 16:01:11 +01001095const char* VP9EncoderImpl::ImplementationName() const {
1096 return "libvpx";
1097}
1098
Magnus Jedvert46a27652017-11-13 14:10:02 +01001099std::unique_ptr<VP9Decoder> VP9Decoder::Create() {
Karl Wiberg918f50c2018-07-05 11:40:33 +02001100 return absl::make_unique<VP9DecoderImpl>();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001101}
1102
1103VP9DecoderImpl::VP9DecoderImpl()
sprang3958ed82017-08-17 08:12:10 -07001104 : decode_complete_callback_(nullptr),
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001105 inited_(false),
sprang3958ed82017-08-17 08:12:10 -07001106 decoder_(nullptr),
philipel9d7d75b2018-04-04 13:03:01 +02001107 key_frame_required_(true) {}
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001108
1109VP9DecoderImpl::~VP9DecoderImpl() {
1110 inited_ = true; // in order to do the actual release
1111 Release();
Henrik Boström9695d852015-05-06 10:42:15 +02001112 int num_buffers_in_use = frame_buffer_pool_.GetNumBuffersInUse();
1113 if (num_buffers_in_use > 0) {
1114 // The frame buffers are reference counted and frames are exposed after
1115 // decoding. There may be valid usage cases where previous frames are still
1116 // referenced after ~VP9DecoderImpl that is not a leak.
Mirko Bonadei675513b2017-11-09 11:09:25 +01001117 RTC_LOG(LS_INFO) << num_buffers_in_use << " Vp9FrameBuffers are still "
1118 << "referenced during ~VP9DecoderImpl.";
Henrik Boström9695d852015-05-06 10:42:15 +02001119 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001120}
1121
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001122int VP9DecoderImpl::InitDecode(const VideoCodec* inst, int number_of_cores) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001123 int ret_val = Release();
1124 if (ret_val < 0) {
1125 return ret_val;
1126 }
sprang3958ed82017-08-17 08:12:10 -07001127 if (decoder_ == nullptr) {
pbos@webrtc.orge728ee02014-12-17 13:43:55 +00001128 decoder_ = new vpx_codec_ctx_t;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001129 }
philipelcce46fc2015-12-21 03:04:49 -08001130 vpx_codec_dec_cfg_t cfg;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001131 // Setting number of threads to a constant value (1)
1132 cfg.threads = 1;
1133 cfg.h = cfg.w = 0; // set after decode
1134 vpx_codec_flags_t flags = 0;
1135 if (vpx_codec_dec_init(decoder_, vpx_codec_vp9_dx(), &cfg, flags)) {
1136 return WEBRTC_VIDEO_CODEC_MEMORY;
1137 }
Henrik Boström9695d852015-05-06 10:42:15 +02001138
1139 if (!frame_buffer_pool_.InitializeVpxUsePool(decoder_)) {
1140 return WEBRTC_VIDEO_CODEC_MEMORY;
1141 }
1142
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001143 inited_ = true;
1144 // Always start with a complete key frame.
1145 key_frame_required_ = true;
1146 return WEBRTC_VIDEO_CODEC_OK;
1147}
1148
1149int VP9DecoderImpl::Decode(const EncodedImage& input_image,
1150 bool missing_frames,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001151 const CodecSpecificInfo* codec_specific_info,
1152 int64_t /*render_time_ms*/) {
1153 if (!inited_) {
1154 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1155 }
sprang3958ed82017-08-17 08:12:10 -07001156 if (decode_complete_callback_ == nullptr) {
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001157 return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
1158 }
1159 // Always start with a complete key frame.
1160 if (key_frame_required_) {
Peter Boström49e196a2015-10-23 15:58:18 +02001161 if (input_image._frameType != kVideoFrameKey)
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001162 return WEBRTC_VIDEO_CODEC_ERROR;
1163 // We have a key frame - is it complete?
1164 if (input_image._completeFrame) {
1165 key_frame_required_ = false;
1166 } else {
1167 return WEBRTC_VIDEO_CODEC_ERROR;
1168 }
1169 }
sprang3958ed82017-08-17 08:12:10 -07001170 vpx_codec_iter_t iter = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001171 vpx_image_t* img;
1172 uint8_t* buffer = input_image._buffer;
1173 if (input_image._length == 0) {
sprang3958ed82017-08-17 08:12:10 -07001174 buffer = nullptr; // Triggers full frame concealment.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001175 }
Henrik Boström9695d852015-05-06 10:42:15 +02001176 // During decode libvpx may get and release buffers from |frame_buffer_pool_|.
1177 // In practice libvpx keeps a few (~3-4) buffers alive at a time.
philipelcce46fc2015-12-21 03:04:49 -08001178 if (vpx_codec_decode(decoder_, buffer,
1179 static_cast<unsigned int>(input_image._length), 0,
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001180 VPX_DL_REALTIME)) {
1181 return WEBRTC_VIDEO_CODEC_ERROR;
1182 }
Henrik Boström9695d852015-05-06 10:42:15 +02001183 // |img->fb_priv| contains the image data, a reference counted Vp9FrameBuffer.
1184 // It may be released by libvpx during future vpx_codec_decode or
1185 // vpx_codec_destroy calls.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001186 img = vpx_codec_get_frame(decoder_, &iter);
sakal7adadb12017-02-23 02:54:57 -08001187 int qp;
1188 vpx_codec_err_t vpx_ret =
1189 vpx_codec_control(decoder_, VPXD_GET_LAST_QUANTIZER, &qp);
1190 RTC_DCHECK_EQ(vpx_ret, VPX_CODEC_OK);
1191 int ret =
1192 ReturnFrame(img, input_image._timeStamp, input_image.ntp_time_ms_, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001193 if (ret != 0) {
1194 return ret;
1195 }
1196 return WEBRTC_VIDEO_CODEC_OK;
1197}
1198
asapersson1490f7a2016-09-23 02:09:46 -07001199int VP9DecoderImpl::ReturnFrame(const vpx_image_t* img,
1200 uint32_t timestamp,
sakal7adadb12017-02-23 02:54:57 -08001201 int64_t ntp_time_ms,
1202 int qp) {
sprang3958ed82017-08-17 08:12:10 -07001203 if (img == nullptr) {
1204 // Decoder OK and nullptr image => No show frame.
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001205 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1206 }
Henrik Boström9695d852015-05-06 10:42:15 +02001207
1208 // This buffer contains all of |img|'s image data, a reference counted
perkj14f41442015-11-30 22:15:45 -08001209 // Vp9FrameBuffer. (libvpx is done with the buffers after a few
Henrik Boström9695d852015-05-06 10:42:15 +02001210 // vpx_codec_decode calls or vpx_codec_destroy).
1211 Vp9FrameBufferPool::Vp9FrameBuffer* img_buffer =
1212 static_cast<Vp9FrameBufferPool::Vp9FrameBuffer*>(img->fb_priv);
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001213
Miguel Casas-Sanchez47650702015-05-29 17:21:40 -07001214 // The buffer can be used directly by the VideoFrame (without copy) by
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001215 // using a Wrapped*Buffer.
1216 rtc::scoped_refptr<VideoFrameBuffer> img_wrapped_buffer;
1217 switch (img->bit_depth) {
1218 case 8:
1219 img_wrapped_buffer = WrapI420Buffer(
philipelcce46fc2015-12-21 03:04:49 -08001220 img->d_w, img->d_h, img->planes[VPX_PLANE_Y],
1221 img->stride[VPX_PLANE_Y], img->planes[VPX_PLANE_U],
1222 img->stride[VPX_PLANE_U], img->planes[VPX_PLANE_V],
1223 img->stride[VPX_PLANE_V],
Henrik Boström9695d852015-05-06 10:42:15 +02001224 // WrappedI420Buffer's mechanism for allowing the release of its frame
1225 // buffer is through a callback function. This is where we should
1226 // release |img_buffer|.
Emircan Uysaler0823eec2018-07-13 17:10:00 -07001227 rtc::KeepRefUntilDone(img_buffer));
1228 break;
1229 case 10:
1230 img_wrapped_buffer = WrapI010Buffer(
1231 img->d_w, img->d_h,
1232 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_Y]),
1233 img->stride[VPX_PLANE_Y] / 2,
1234 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_U]),
1235 img->stride[VPX_PLANE_U] / 2,
1236 reinterpret_cast<const uint16_t*>(img->planes[VPX_PLANE_V]),
1237 img->stride[VPX_PLANE_V] / 2, rtc::KeepRefUntilDone(img_buffer));
1238 break;
1239 default:
1240 RTC_NOTREACHED();
1241 return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
1242 }
nisseca6d5d12016-06-17 05:03:04 -07001243
Emircan Uysaler715cc232018-07-23 17:50:43 -07001244 VideoFrame decoded_image = VideoFrame::Builder()
1245 .set_video_frame_buffer(img_wrapped_buffer)
1246 .set_timestamp_ms(0)
1247 .set_timestamp_rtp(timestamp)
1248 .set_ntp_time_ms(ntp_time_ms)
1249 .set_rotation(webrtc::kVideoRotation_0)
1250 .set_color_space(ExtractVP9ColorSpace(
1251 img->cs, img->range, img->bit_depth))
1252 .build();
Danil Chapovalov0040b662018-06-18 10:48:16 +02001253 decode_complete_callback_->Decoded(decoded_image, absl::nullopt, qp);
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001254 return WEBRTC_VIDEO_CODEC_OK;
1255}
1256
1257int VP9DecoderImpl::RegisterDecodeCompleteCallback(
1258 DecodedImageCallback* callback) {
1259 decode_complete_callback_ = callback;
1260 return WEBRTC_VIDEO_CODEC_OK;
1261}
1262
1263int VP9DecoderImpl::Release() {
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001264 int ret_val = WEBRTC_VIDEO_CODEC_OK;
1265
sprang3958ed82017-08-17 08:12:10 -07001266 if (decoder_ != nullptr) {
Sergey Silkin90399692018-03-02 14:44:10 +01001267 if (inited_) {
1268 // When a codec is destroyed libvpx will release any buffers of
1269 // |frame_buffer_pool_| it is currently using.
1270 if (vpx_codec_destroy(decoder_)) {
1271 ret_val = WEBRTC_VIDEO_CODEC_MEMORY;
1272 }
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001273 }
1274 delete decoder_;
sprang3958ed82017-08-17 08:12:10 -07001275 decoder_ = nullptr;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001276 }
Henrik Boström9695d852015-05-06 10:42:15 +02001277 // Releases buffers from the pool. Any buffers not in use are deleted. Buffers
1278 // still referenced externally are deleted once fully released, not returning
1279 // to the pool.
1280 frame_buffer_pool_.ClearPool();
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001281 inited_ = false;
Sergey Silkin3e871ea2018-03-02 13:11:04 +01001282 return ret_val;
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001283}
Peter Boströmb7d9a972015-12-18 16:01:11 +01001284
1285const char* VP9DecoderImpl::ImplementationName() const {
1286 return "libvpx";
1287}
1288
marpan@webrtc.org5b883172014-11-01 06:10:48 +00001289} // namespace webrtc