FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
libvpxenc.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2010, Google, Inc.
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20 
21 /**
22  * @file
23  * VP8 encoder support via libvpx
24  */
25 
26 #define VPX_DISABLE_CTRL_TYPECHECKS 1
27 #define VPX_CODEC_DISABLE_COMPAT 1
28 #include <vpx/vpx_encoder.h>
29 #include <vpx/vp8cx.h>
30 
31 #include "avcodec.h"
32 #include "internal.h"
33 #include "libavutil/avassert.h"
34 #include "libvpx.h"
35 #include "libavutil/base64.h"
36 #include "libavutil/common.h"
37 #include "libavutil/intreadwrite.h"
38 #include "libavutil/mathematics.h"
39 #include "libavutil/opt.h"
40 
41 /**
42  * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
43  * One encoded frame returned from the library.
44  */
45 struct FrameListData {
46  void *buf; /**< compressed data buffer */
47  size_t sz; /**< length of compressed data */
48  void *buf_alpha;
49  size_t sz_alpha;
50  int64_t pts; /**< time stamp to show frame
51  (in timebase units) */
52  unsigned long duration; /**< duration to show frame
53  (in timebase units) */
54  uint32_t flags; /**< flags for this frame */
55  uint64_t sse[4];
56  int have_sse; /**< true if we have pending sse[] */
57  uint64_t frame_number;
59 };
60 
61 typedef struct VP8EncoderContext {
62  AVClass *class;
63  struct vpx_codec_ctx encoder;
64  struct vpx_image rawimg;
65  struct vpx_codec_ctx encoder_alpha;
66  struct vpx_image rawimg_alpha;
68  struct vpx_fixed_buf twopass_stats;
69  int deadline; //i.e., RT/GOOD/BEST
70  uint64_t sse[4];
71  int have_sse; /**< true if we have pending sse[] */
72  uint64_t frame_number;
74 
75  int cpu_used;
76  /**
77  * VP8 specific flags, see VP8F_* below.
78  */
79  int flags;
80 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
81 #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
82 
84 
87  int arnr_type;
88 
91  int crf;
96 
97  // VP9-only
98  int lossless;
102  int aq_mode;
103 } VP8Context;
104 
105 /** String mappings for enum vp8e_enc_control_id */
106 static const char *const ctlidstr[] = {
107  [VP8E_UPD_ENTROPY] = "VP8E_UPD_ENTROPY",
108  [VP8E_UPD_REFERENCE] = "VP8E_UPD_REFERENCE",
109  [VP8E_USE_REFERENCE] = "VP8E_USE_REFERENCE",
110  [VP8E_SET_ROI_MAP] = "VP8E_SET_ROI_MAP",
111  [VP8E_SET_ACTIVEMAP] = "VP8E_SET_ACTIVEMAP",
112  [VP8E_SET_SCALEMODE] = "VP8E_SET_SCALEMODE",
113  [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
114  [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
115  [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
116  [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
117  [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
118  [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
119  [VP8E_GET_LAST_QUANTIZER] = "VP8E_GET_LAST_QUANTIZER",
120  [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
121  [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
122  [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
123  [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
124  [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
125 #if CONFIG_LIBVPX_VP9_ENCODER
126  [VP9E_SET_LOSSLESS] = "VP9E_SET_LOSSLESS",
127  [VP9E_SET_TILE_COLUMNS] = "VP9E_SET_TILE_COLUMNS",
128  [VP9E_SET_TILE_ROWS] = "VP9E_SET_TILE_ROWS",
129  [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
130  [VP9E_SET_AQ_MODE] = "VP9E_SET_AQ_MODE",
131 #if VPX_ENCODER_ABI_VERSION > 8
132  [VP9E_SET_COLOR_SPACE] = "VP9E_SET_COLOR_SPACE",
133 #endif
134 #endif
135 };
136 
137 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
138 {
139  VP8Context *ctx = avctx->priv_data;
140  const char *error = vpx_codec_error(&ctx->encoder);
141  const char *detail = vpx_codec_error_detail(&ctx->encoder);
142 
143  av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
144  if (detail)
145  av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
146 }
147 
149  const struct vpx_codec_enc_cfg *cfg)
150 {
151  int width = -30;
152  int level = AV_LOG_DEBUG;
153 
154  av_log(avctx, level, "vpx_codec_enc_cfg\n");
155  av_log(avctx, level, "generic settings\n"
156  " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
157 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
158  " %*s%u\n %*s%u\n"
159 #endif
160  " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
161  width, "g_usage:", cfg->g_usage,
162  width, "g_threads:", cfg->g_threads,
163  width, "g_profile:", cfg->g_profile,
164  width, "g_w:", cfg->g_w,
165  width, "g_h:", cfg->g_h,
166 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
167  width, "g_bit_depth:", cfg->g_bit_depth,
168  width, "g_input_bit_depth:", cfg->g_input_bit_depth,
169 #endif
170  width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
171  width, "g_error_resilient:", cfg->g_error_resilient,
172  width, "g_pass:", cfg->g_pass,
173  width, "g_lag_in_frames:", cfg->g_lag_in_frames);
174  av_log(avctx, level, "rate control settings\n"
175  " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
176  " %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
177  width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
178  width, "rc_resize_allowed:", cfg->rc_resize_allowed,
179  width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
180  width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
181  width, "rc_end_usage:", cfg->rc_end_usage,
182  width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
183  width, "rc_target_bitrate:", cfg->rc_target_bitrate);
184  av_log(avctx, level, "quantizer settings\n"
185  " %*s%u\n %*s%u\n",
186  width, "rc_min_quantizer:", cfg->rc_min_quantizer,
187  width, "rc_max_quantizer:", cfg->rc_max_quantizer);
188  av_log(avctx, level, "bitrate tolerance\n"
189  " %*s%u\n %*s%u\n",
190  width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
191  width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
192  av_log(avctx, level, "decoder buffer model\n"
193  " %*s%u\n %*s%u\n %*s%u\n",
194  width, "rc_buf_sz:", cfg->rc_buf_sz,
195  width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
196  width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
197  av_log(avctx, level, "2 pass rate control settings\n"
198  " %*s%u\n %*s%u\n %*s%u\n",
199  width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
200  width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
201  width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
202  av_log(avctx, level, "keyframing settings\n"
203  " %*s%d\n %*s%u\n %*s%u\n",
204  width, "kf_mode:", cfg->kf_mode,
205  width, "kf_min_dist:", cfg->kf_min_dist,
206  width, "kf_max_dist:", cfg->kf_max_dist);
207  av_log(avctx, level, "\n");
208 }
209 
210 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
211 {
212  struct FrameListData **p = list;
213 
214  while (*p)
215  p = &(*p)->next;
216  *p = cx_frame;
217  cx_frame->next = NULL;
218 }
219 
220 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
221 {
222  av_freep(&cx_frame->buf);
223  if (cx_frame->buf_alpha)
224  av_freep(&cx_frame->buf_alpha);
225  av_freep(&cx_frame);
226 }
227 
228 static av_cold void free_frame_list(struct FrameListData *list)
229 {
230  struct FrameListData *p = list;
231 
232  while (p) {
233  list = list->next;
234  free_coded_frame(p);
235  p = list;
236  }
237 }
238 
240  enum vp8e_enc_control_id id, int val)
241 {
242  VP8Context *ctx = avctx->priv_data;
243  char buf[80];
244  int width = -30;
245  int res;
246 
247  snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
248  av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
249 
250  res = vpx_codec_control(&ctx->encoder, id, val);
251  if (res != VPX_CODEC_OK) {
252  snprintf(buf, sizeof(buf), "Failed to set %s codec control",
253  ctlidstr[id]);
254  log_encoder_error(avctx, buf);
255  }
256 
257  return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
258 }
259 
260 static av_cold int vp8_free(AVCodecContext *avctx)
261 {
262  VP8Context *ctx = avctx->priv_data;
263 
264  vpx_codec_destroy(&ctx->encoder);
265  if (ctx->is_alpha)
266  vpx_codec_destroy(&ctx->encoder_alpha);
267  av_freep(&ctx->twopass_stats.buf);
268  av_freep(&avctx->stats_out);
270  return 0;
271 }
272 
273 #if CONFIG_LIBVPX_VP9_ENCODER
274 static int set_pix_fmt(AVCodecContext *avctx, vpx_codec_caps_t codec_caps,
275  struct vpx_codec_enc_cfg *enccfg, vpx_codec_flags_t *flags,
276  vpx_img_fmt_t *img_fmt)
277 {
278 #ifdef VPX_IMG_FMT_HIGHBITDEPTH
279  enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
280 #endif
281  switch (avctx->pix_fmt) {
282  case AV_PIX_FMT_YUV420P:
283  enccfg->g_profile = 0;
284  *img_fmt = VPX_IMG_FMT_I420;
285  return 0;
286  case AV_PIX_FMT_YUV422P:
287  enccfg->g_profile = 1;
288  *img_fmt = VPX_IMG_FMT_I422;
289  return 0;
290 #if VPX_IMAGE_ABI_VERSION >= 3
291  case AV_PIX_FMT_YUV440P:
292  enccfg->g_profile = 1;
293  *img_fmt = VPX_IMG_FMT_I440;
294  return 0;
295 #endif
296  case AV_PIX_FMT_YUV444P:
297  enccfg->g_profile = 1;
298  *img_fmt = VPX_IMG_FMT_I444;
299  return 0;
300 #ifdef VPX_IMG_FMT_HIGHBITDEPTH
303  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
304  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
305  avctx->pix_fmt == AV_PIX_FMT_YUV420P10LE ? 10 : 12;
306  enccfg->g_profile = 2;
307  *img_fmt = VPX_IMG_FMT_I42016;
308  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
309  return 0;
310  }
311  break;
314  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
315  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
316  avctx->pix_fmt == AV_PIX_FMT_YUV422P10LE ? 10 : 12;
317  enccfg->g_profile = 3;
318  *img_fmt = VPX_IMG_FMT_I42216;
319  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
320  return 0;
321  }
322  break;
323 #if VPX_IMAGE_ABI_VERSION >= 3
326  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
327  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
328  avctx->pix_fmt == AV_PIX_FMT_YUV440P10LE ? 10 : 12;
329  enccfg->g_profile = 3;
330  *img_fmt = VPX_IMG_FMT_I44016;
331  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
332  return 0;
333  }
334  break;
335 #endif
338  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
339  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
340  avctx->pix_fmt == AV_PIX_FMT_YUV444P10LE ? 10 : 12;
341  enccfg->g_profile = 3;
342  *img_fmt = VPX_IMG_FMT_I44416;
343  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
344  return 0;
345  }
346  break;
347 #endif
348  default:
349  break;
350  }
351  av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
352  return AVERROR_INVALIDDATA;
353 }
354 
355 #if VPX_ENCODER_ABI_VERSION > 8
356 static void set_colorspace(AVCodecContext *avctx)
357 {
358  enum vpx_color_space vpx_cs;
359 
360  switch (avctx->colorspace) {
361  case AVCOL_SPC_RGB: vpx_cs = VPX_CS_SRGB; break;
362  case AVCOL_SPC_BT709: vpx_cs = VPX_CS_BT_709; break;
363  case AVCOL_SPC_UNSPECIFIED: vpx_cs = VPX_CS_UNKNOWN; break;
364  case AVCOL_SPC_RESERVED: vpx_cs = VPX_CS_RESERVED; break;
365  case AVCOL_SPC_BT470BG: vpx_cs = VPX_CS_BT_601; break;
366  case AVCOL_SPC_SMPTE170M: vpx_cs = VPX_CS_SMPTE_170; break;
367  case AVCOL_SPC_SMPTE240M: vpx_cs = VPX_CS_SMPTE_240; break;
368  case AVCOL_SPC_BT2020_NCL: vpx_cs = VPX_CS_BT_2020; break;
369  default:
370  av_log(avctx, AV_LOG_WARNING, "Unsupported colorspace (%d)\n",
371  avctx->colorspace);
372  return;
373  }
374  codecctl_int(avctx, VP9E_SET_COLOR_SPACE, vpx_cs);
375 }
376 #endif
377 #endif
378 
379 static av_cold int vpx_init(AVCodecContext *avctx,
380  const struct vpx_codec_iface *iface)
381 {
382  VP8Context *ctx = avctx->priv_data;
383  struct vpx_codec_enc_cfg enccfg = { 0 };
384  struct vpx_codec_enc_cfg enccfg_alpha;
385  vpx_codec_flags_t flags = (avctx->flags & AV_CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
386  int res;
387  vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
388 #if CONFIG_LIBVPX_VP9_ENCODER
389  vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
390 #endif
391 
392  av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
393  av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
394 
395  if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
396  ctx->is_alpha = 1;
397 
398  if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
399  av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
400  vpx_codec_err_to_string(res));
401  return AVERROR(EINVAL);
402  }
403 
404 #if CONFIG_LIBVPX_VP9_ENCODER
405  if (avctx->codec_id == AV_CODEC_ID_VP9) {
406  if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
407  return AVERROR(EINVAL);
408  }
409 #endif
410 
411  if(!avctx->bit_rate)
412  if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
413  av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
414  return AVERROR(EINVAL);
415  }
416 
417  dump_enc_cfg(avctx, &enccfg);
418 
419  enccfg.g_w = avctx->width;
420  enccfg.g_h = avctx->height;
421  enccfg.g_timebase.num = avctx->time_base.num;
422  enccfg.g_timebase.den = avctx->time_base.den;
423  enccfg.g_threads = avctx->thread_count;
424  enccfg.g_lag_in_frames= ctx->lag_in_frames;
425 
426  if (avctx->flags & AV_CODEC_FLAG_PASS1)
427  enccfg.g_pass = VPX_RC_FIRST_PASS;
428  else if (avctx->flags & AV_CODEC_FLAG_PASS2)
429  enccfg.g_pass = VPX_RC_LAST_PASS;
430  else
431  enccfg.g_pass = VPX_RC_ONE_PASS;
432 
433  if (avctx->rc_min_rate == avctx->rc_max_rate &&
434  avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
435  enccfg.rc_end_usage = VPX_CBR;
436  } else if (ctx->crf >= 0) {
437  enccfg.rc_end_usage = VPX_CQ;
438 #if CONFIG_LIBVPX_VP9_ENCODER
439  if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
440  enccfg.rc_end_usage = VPX_Q;
441 #endif
442  }
443 
444  if (avctx->bit_rate) {
445  enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
447 #if CONFIG_LIBVPX_VP9_ENCODER
448  } else if (enccfg.rc_end_usage == VPX_Q) {
449 #endif
450  } else {
451  if (enccfg.rc_end_usage == VPX_CQ) {
452  enccfg.rc_target_bitrate = 1000000;
453  } else {
454  avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
455  av_log(avctx, AV_LOG_WARNING,
456  "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
457  enccfg.rc_target_bitrate);
458  }
459  }
460 
461  if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
462  enccfg.rc_min_quantizer =
463  enccfg.rc_max_quantizer = 0;
464  } else {
465  if (avctx->qmin >= 0)
466  enccfg.rc_min_quantizer = avctx->qmin;
467  if (avctx->qmax >= 0)
468  enccfg.rc_max_quantizer = avctx->qmax;
469  }
470 
471  if (enccfg.rc_end_usage == VPX_CQ
472 #if CONFIG_LIBVPX_VP9_ENCODER
473  || enccfg.rc_end_usage == VPX_Q
474 #endif
475  ) {
476  if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
477  av_log(avctx, AV_LOG_ERROR,
478  "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
479  ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
480  return AVERROR(EINVAL);
481  }
482  }
483 
484  enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
485 
486  //0-100 (0 => CBR, 100 => VBR)
487  enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
488  if (avctx->bit_rate)
489  enccfg.rc_2pass_vbr_minsection_pct =
490  avctx->rc_min_rate * 100LL / avctx->bit_rate;
491  if (avctx->rc_max_rate)
492  enccfg.rc_2pass_vbr_maxsection_pct =
493  avctx->rc_max_rate * 100LL / avctx->bit_rate;
494 
495  if (avctx->rc_buffer_size)
496  enccfg.rc_buf_sz =
497  avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
498  if (avctx->rc_initial_buffer_occupancy)
499  enccfg.rc_buf_initial_sz =
500  avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
501  enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
502 #if FF_API_MPV_OPT
504  if (avctx->rc_buffer_aggressivity != 1.0) {
505  av_log(avctx, AV_LOG_WARNING, "The rc_buffer_aggressivity option is "
506  "deprecated, use the undershoot-pct private option instead.\n");
507  enccfg.rc_undershoot_pct = round(avctx->rc_buffer_aggressivity * 100);
508  }
510 #endif
511  if (ctx->rc_undershoot_pct >= 0)
512  enccfg.rc_undershoot_pct = ctx->rc_undershoot_pct;
513  if (ctx->rc_overshoot_pct >= 0)
514  enccfg.rc_overshoot_pct = ctx->rc_overshoot_pct;
515 
516  //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
517  if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
518  enccfg.kf_min_dist = avctx->keyint_min;
519  if (avctx->gop_size >= 0)
520  enccfg.kf_max_dist = avctx->gop_size;
521 
522  if (enccfg.g_pass == VPX_RC_FIRST_PASS)
523  enccfg.g_lag_in_frames = 0;
524  else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
525  int decode_size, ret;
526 
527  if (!avctx->stats_in) {
528  av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
529  return AVERROR_INVALIDDATA;
530  }
531 
532  ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
533  ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
534  if (ret < 0) {
535  av_log(avctx, AV_LOG_ERROR,
536  "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
537  ctx->twopass_stats.sz);
538  ctx->twopass_stats.sz = 0;
539  return ret;
540  }
541  decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
542  ctx->twopass_stats.sz);
543  if (decode_size < 0) {
544  av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
545  return AVERROR_INVALIDDATA;
546  }
547 
548  ctx->twopass_stats.sz = decode_size;
549  enccfg.rc_twopass_stats_in = ctx->twopass_stats;
550  }
551 
552  /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
553  complexity playback on low powered devices at the expense of encode
554  quality. */
555  if (avctx->profile != FF_PROFILE_UNKNOWN)
556  enccfg.g_profile = avctx->profile;
557 
558  enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
559 
560  dump_enc_cfg(avctx, &enccfg);
561  /* Construct Encoder Context */
562  res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
563  if (res != VPX_CODEC_OK) {
564  log_encoder_error(avctx, "Failed to initialize encoder");
565  return AVERROR(EINVAL);
566  }
567 
568  if (ctx->is_alpha) {
569  enccfg_alpha = enccfg;
570  res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
571  if (res != VPX_CODEC_OK) {
572  log_encoder_error(avctx, "Failed to initialize alpha encoder");
573  return AVERROR(EINVAL);
574  }
575  }
576 
577  //codec control failures are currently treated only as warnings
578  av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
579  codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
580  if (ctx->flags & VP8F_AUTO_ALT_REF)
581  ctx->auto_alt_ref = 1;
582  if (ctx->auto_alt_ref >= 0)
583  codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
584  if (ctx->arnr_max_frames >= 0)
585  codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
586  if (ctx->arnr_strength >= 0)
587  codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
588  if (ctx->arnr_type >= 0)
589  codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
590 
591  if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) {
592  codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
593  codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
594  }
595 #if FF_API_MPV_OPT
597  if (avctx->mb_threshold) {
598  av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
599  "use the static-thresh private option instead.\n");
600  ctx->static_thresh = avctx->mb_threshold;
601  }
603 #endif
604  codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
605  if (ctx->crf >= 0)
606  codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
607  if (ctx->max_intra_rate >= 0)
608  codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
609 
610 #if CONFIG_LIBVPX_VP9_ENCODER
611  if (avctx->codec_id == AV_CODEC_ID_VP9) {
612  if (ctx->lossless >= 0)
613  codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
614  if (ctx->tile_columns >= 0)
615  codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
616  if (ctx->tile_rows >= 0)
617  codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
618  if (ctx->frame_parallel >= 0)
619  codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
620  if (ctx->aq_mode >= 0)
621  codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
622 #if VPX_ENCODER_ABI_VERSION > 8
623  set_colorspace(avctx);
624 #endif
625  }
626 #endif
627 
628  av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
629 
630  //provide dummy value to initialize wrapper, values will be updated each _encode()
631  vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
632  (unsigned char*)1);
633 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
634  if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
635  ctx->rawimg.bit_depth = enccfg.g_bit_depth;
636 #endif
637 
638  if (ctx->is_alpha)
639  vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
640  (unsigned char*)1);
641 
642  return 0;
643 }
644 
645 static inline void cx_pktcpy(struct FrameListData *dst,
646  const struct vpx_codec_cx_pkt *src,
647  const struct vpx_codec_cx_pkt *src_alpha,
648  VP8Context *ctx)
649 {
650  dst->pts = src->data.frame.pts;
651  dst->duration = src->data.frame.duration;
652  dst->flags = src->data.frame.flags;
653  dst->sz = src->data.frame.sz;
654  dst->buf = src->data.frame.buf;
655  dst->have_sse = 0;
656  /* For alt-ref frame, don't store PSNR or increment frame_number */
657  if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
658  dst->frame_number = ++ctx->frame_number;
659  dst->have_sse = ctx->have_sse;
660  if (ctx->have_sse) {
661  /* associate last-seen SSE to the frame. */
662  /* Transfers ownership from ctx to dst. */
663  /* WARNING! This makes the assumption that PSNR_PKT comes
664  just before the frame it refers to! */
665  memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
666  ctx->have_sse = 0;
667  }
668  } else {
669  dst->frame_number = -1; /* sanity marker */
670  }
671  if (src_alpha) {
672  dst->buf_alpha = src_alpha->data.frame.buf;
673  dst->sz_alpha = src_alpha->data.frame.sz;
674  } else {
675  dst->buf_alpha = NULL;
676  dst->sz_alpha = 0;
677  }
678 }
679 
680 /**
681  * Store coded frame information in format suitable for return from encode2().
682  *
683  * Write information from @a cx_frame to @a pkt
684  * @return packet data size on success
685  * @return a negative AVERROR on error
686  */
687 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
688  AVPacket *pkt)
689 {
690  int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
691  uint8_t *side_data;
692  if (ret >= 0) {
693  int pict_type;
694  memcpy(pkt->data, cx_frame->buf, pkt->size);
695  pkt->pts = pkt->dts = cx_frame->pts;
696 #if FF_API_CODED_FRAME
698  avctx->coded_frame->pts = cx_frame->pts;
699  avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
701 #endif
702 
703  if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
704  pict_type = AV_PICTURE_TYPE_I;
705 #if FF_API_CODED_FRAME
707  avctx->coded_frame->pict_type = pict_type;
709 #endif
710  pkt->flags |= AV_PKT_FLAG_KEY;
711  } else {
712  pict_type = AV_PICTURE_TYPE_P;
713 #if FF_API_CODED_FRAME
715  avctx->coded_frame->pict_type = pict_type;
717 #endif
718  }
719 
720  ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
721  cx_frame->have_sse ? 3 : 0, pict_type);
722 
723  if (cx_frame->have_sse) {
724  int i;
725  /* Beware of the Y/U/V/all order! */
726 #if FF_API_CODED_FRAME
728  avctx->coded_frame->error[0] = cx_frame->sse[1];
729  avctx->coded_frame->error[1] = cx_frame->sse[2];
730  avctx->coded_frame->error[2] = cx_frame->sse[3];
731  avctx->coded_frame->error[3] = 0; // alpha
733 #endif
734  for (i = 0; i < 3; ++i) {
735  avctx->error[i] += cx_frame->sse[i + 1];
736  }
737  cx_frame->have_sse = 0;
738  }
739  if (cx_frame->sz_alpha > 0) {
740  side_data = av_packet_new_side_data(pkt,
742  cx_frame->sz_alpha + 8);
743  if(!side_data) {
744  av_free_packet(pkt);
745  av_free(pkt);
746  return AVERROR(ENOMEM);
747  }
748  AV_WB64(side_data, 1);
749  memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
750  }
751  } else {
752  return ret;
753  }
754  return pkt->size;
755 }
756 
757 /**
758  * Queue multiple output frames from the encoder, returning the front-most.
759  * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
760  * the frame queue. Return the head frame if available.
761  * @return Stored frame size
762  * @return AVERROR(EINVAL) on output size error
763  * @return AVERROR(ENOMEM) on coded frame queue data allocation error
764  */
765 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
766 {
767  VP8Context *ctx = avctx->priv_data;
768  const struct vpx_codec_cx_pkt *pkt;
769  const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
770  const void *iter = NULL;
771  const void *iter_alpha = NULL;
772  int size = 0;
773 
774  if (ctx->coded_frame_list) {
775  struct FrameListData *cx_frame = ctx->coded_frame_list;
776  /* return the leading frame if we've already begun queueing */
777  size = storeframe(avctx, cx_frame, pkt_out);
778  if (size < 0)
779  return size;
780  ctx->coded_frame_list = cx_frame->next;
781  free_coded_frame(cx_frame);
782  }
783 
784  /* consume all available output from the encoder before returning. buffers
785  are only good through the next vpx_codec call */
786  while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
787  (!ctx->is_alpha ||
788  (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
789  switch (pkt->kind) {
790  case VPX_CODEC_CX_FRAME_PKT:
791  if (!size) {
792  struct FrameListData cx_frame;
793 
794  /* avoid storing the frame when the list is empty and we haven't yet
795  provided a frame for output */
797  cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
798  size = storeframe(avctx, &cx_frame, pkt_out);
799  if (size < 0)
800  return size;
801  } else {
802  struct FrameListData *cx_frame =
803  av_malloc(sizeof(struct FrameListData));
804 
805  if (!cx_frame) {
806  av_log(avctx, AV_LOG_ERROR,
807  "Frame queue element alloc failed\n");
808  return AVERROR(ENOMEM);
809  }
810  cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
811  cx_frame->buf = av_malloc(cx_frame->sz);
812 
813  if (!cx_frame->buf) {
814  av_log(avctx, AV_LOG_ERROR,
815  "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
816  cx_frame->sz);
817  av_freep(&cx_frame);
818  return AVERROR(ENOMEM);
819  }
820  memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
821  if (ctx->is_alpha) {
822  cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
823  if (!cx_frame->buf_alpha) {
824  av_log(avctx, AV_LOG_ERROR,
825  "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
826  cx_frame->sz_alpha);
827  av_free(cx_frame);
828  return AVERROR(ENOMEM);
829  }
830  memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
831  }
832  coded_frame_add(&ctx->coded_frame_list, cx_frame);
833  }
834  break;
835  case VPX_CODEC_STATS_PKT: {
836  struct vpx_fixed_buf *stats = &ctx->twopass_stats;
837  int err;
838  if ((err = av_reallocp(&stats->buf,
839  stats->sz +
840  pkt->data.twopass_stats.sz)) < 0) {
841  stats->sz = 0;
842  av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
843  return err;
844  }
845  memcpy((uint8_t*)stats->buf + stats->sz,
846  pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
847  stats->sz += pkt->data.twopass_stats.sz;
848  break;
849  }
850  case VPX_CODEC_PSNR_PKT:
851  av_assert0(!ctx->have_sse);
852  ctx->sse[0] = pkt->data.psnr.sse[0];
853  ctx->sse[1] = pkt->data.psnr.sse[1];
854  ctx->sse[2] = pkt->data.psnr.sse[2];
855  ctx->sse[3] = pkt->data.psnr.sse[3];
856  ctx->have_sse = 1;
857  break;
858  case VPX_CODEC_CUSTOM_PKT:
859  //ignore unsupported/unrecognized packet types
860  break;
861  }
862  }
863 
864  return size;
865 }
866 
867 static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
868  const AVFrame *frame, int *got_packet)
869 {
870  VP8Context *ctx = avctx->priv_data;
871  struct vpx_image *rawimg = NULL;
872  struct vpx_image *rawimg_alpha = NULL;
873  int64_t timestamp = 0;
874  int res, coded_size;
875  vpx_enc_frame_flags_t flags = 0;
876 
877  if (frame) {
878  rawimg = &ctx->rawimg;
879  rawimg->planes[VPX_PLANE_Y] = frame->data[0];
880  rawimg->planes[VPX_PLANE_U] = frame->data[1];
881  rawimg->planes[VPX_PLANE_V] = frame->data[2];
882  rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
883  rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
884  rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
885  if (ctx->is_alpha) {
886  uint8_t *u_plane, *v_plane;
887  rawimg_alpha = &ctx->rawimg_alpha;
888  rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
889  u_plane = av_malloc(frame->linesize[1] * frame->height);
890  v_plane = av_malloc(frame->linesize[2] * frame->height);
891  if (!u_plane || !v_plane) {
892  av_free(u_plane);
893  av_free(v_plane);
894  return AVERROR(ENOMEM);
895  }
896  memset(u_plane, 0x80, frame->linesize[1] * frame->height);
897  rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
898  memset(v_plane, 0x80, frame->linesize[2] * frame->height);
899  rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
900  rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
901  rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
902  rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
903  }
904  timestamp = frame->pts;
905  if (frame->pict_type == AV_PICTURE_TYPE_I)
906  flags |= VPX_EFLAG_FORCE_KF;
907  }
908 
909  res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
910  avctx->ticks_per_frame, flags, ctx->deadline);
911  if (res != VPX_CODEC_OK) {
912  log_encoder_error(avctx, "Error encoding frame");
913  return AVERROR_INVALIDDATA;
914  }
915 
916  if (ctx->is_alpha) {
917  res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
918  avctx->ticks_per_frame, flags, ctx->deadline);
919  if (res != VPX_CODEC_OK) {
920  log_encoder_error(avctx, "Error encoding alpha frame");
921  return AVERROR_INVALIDDATA;
922  }
923  }
924 
925  coded_size = queue_frames(avctx, pkt);
926 
927  if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
928  unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
929 
930  avctx->stats_out = av_malloc(b64_size);
931  if (!avctx->stats_out) {
932  av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
933  b64_size);
934  return AVERROR(ENOMEM);
935  }
936  av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
937  ctx->twopass_stats.sz);
938  }
939 
940  if (rawimg_alpha) {
941  av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
942  av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
943  }
944 
945  *got_packet = !!coded_size;
946  return 0;
947 }
948 
949 #define OFFSET(x) offsetof(VP8Context, x)
950 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
951 
952 #ifndef VPX_ERROR_RESILIENT_DEFAULT
953 #define VPX_ERROR_RESILIENT_DEFAULT 1
954 #define VPX_ERROR_RESILIENT_PARTITIONS 2
955 #endif
956 
957 #define COMMON_OPTIONS \
958  { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
959  { "auto-alt-ref", "Enable use of alternate reference " \
960  "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE}, \
961  { "lag-in-frames", "Number of frames to look ahead for " \
962  "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
963  { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
964  { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
965  { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
966  { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
967  { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
968  { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
969  { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
970  { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
971  { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
972  { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
973  { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
974  { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
975  { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
976  { "partitions", "The frame partitions are independently decodable " \
977  "by the bool decoder, meaning that partitions can be decoded even " \
978  "though earlier partitions have been lost. Note that intra predicition" \
979  " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
980  { "crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
981  { "static-thresh", "A change threshold on blocks below which they will be skipped by the encoder", OFFSET(static_thresh), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, VE }, \
982  { "undershoot-pct", "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
983  { "overshoot-pct", "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
984 
985 #define LEGACY_OPTIONS \
986  {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
987  {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
988  {"vp8flags", "", offsetof(VP8Context, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
989  {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
990  {"altref", "enable use of alternate reference frames (VP8/2-pass only)", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_AUTO_ALT_REF}, INT_MIN, INT_MAX, VE, "flags"}, \
991  {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
992  {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
993  {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
994  {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VP8Context, lag_in_frames), AV_OPT_TYPE_INT, {.i64 = 25}, 0, 25, VE}, \
995 
996 #if CONFIG_LIBVPX_VP8_ENCODER
997 static const AVOption vp8_options[] = {
1000  { NULL }
1001 };
1002 #endif
1003 
1004 #if CONFIG_LIBVPX_VP9_ENCODER
1005 static const AVOption vp9_options[] = {
1007  { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
1008  { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1009  { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1010  { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
1011  { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
1012  { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
1013  { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
1014  { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
1015  { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
1017  { NULL }
1018 };
1019 #endif
1020 
1021 #undef COMMON_OPTIONS
1022 #undef LEGACY_OPTIONS
1023 
1024 static const AVCodecDefault defaults[] = {
1025  { "qmin", "-1" },
1026  { "qmax", "-1" },
1027  { "g", "-1" },
1028  { "keyint_min", "-1" },
1029  { NULL },
1030 };
1031 
1032 #if CONFIG_LIBVPX_VP8_ENCODER
1033 static av_cold int vp8_init(AVCodecContext *avctx)
1034 {
1035  return vpx_init(avctx, vpx_codec_vp8_cx());
1036 }
1037 
1038 static const AVClass class_vp8 = {
1039  .class_name = "libvpx-vp8 encoder",
1040  .item_name = av_default_item_name,
1041  .option = vp8_options,
1042  .version = LIBAVUTIL_VERSION_INT,
1043 };
1044 
1045 AVCodec ff_libvpx_vp8_encoder = {
1046  .name = "libvpx",
1047  .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
1048  .type = AVMEDIA_TYPE_VIDEO,
1049  .id = AV_CODEC_ID_VP8,
1050  .priv_data_size = sizeof(VP8Context),
1051  .init = vp8_init,
1052  .encode2 = vp8_encode,
1053  .close = vp8_free,
1056  .priv_class = &class_vp8,
1057  .defaults = defaults,
1058 };
1059 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
1060 
1061 #if CONFIG_LIBVPX_VP9_ENCODER
1062 static av_cold int vp9_init(AVCodecContext *avctx)
1063 {
1064  return vpx_init(avctx, vpx_codec_vp9_cx());
1065 }
1066 
1067 static const AVClass class_vp9 = {
1068  .class_name = "libvpx-vp9 encoder",
1069  .item_name = av_default_item_name,
1070  .option = vp9_options,
1071  .version = LIBAVUTIL_VERSION_INT,
1072 };
1073 
1074 static const AVProfile profiles[] = {
1075  { FF_PROFILE_VP9_0, "Profile 0" },
1076  { FF_PROFILE_VP9_1, "Profile 1" },
1077  { FF_PROFILE_VP9_2, "Profile 2" },
1078  { FF_PROFILE_VP9_3, "Profile 3" },
1079  { FF_PROFILE_UNKNOWN },
1080 };
1081 
1082 AVCodec ff_libvpx_vp9_encoder = {
1083  .name = "libvpx-vp9",
1084  .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
1085  .type = AVMEDIA_TYPE_VIDEO,
1086  .id = AV_CODEC_ID_VP9,
1087  .priv_data_size = sizeof(VP8Context),
1088  .init = vp9_init,
1089  .encode2 = vp8_encode,
1090  .close = vp8_free,
1092  .profiles = NULL_IF_CONFIG_SMALL(profiles),
1093  .priv_class = &class_vp9,
1094  .defaults = defaults,
1095  .init_static_data = ff_vp9_init_static,
1096 };
1097 #endif /* CONFIG_LIBVPX_VP9_ENCODER */
uint64_t sse[4]
Definition: libvpxenc.c:55
also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / SMPTE RP177 Annex B
Definition: pixfmt.h:519
int cpu_used
Definition: libvpxenc.c:75
struct vpx_image rawimg_alpha
Definition: libvpxenc.c:66
#define NULL
Definition: coverity.c:32
const char const char void * val
Definition: avisynth_c.h:634
planar YUV 4:4:0,20bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian
Definition: pixfmt.h:319
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:59
int lag_in_frames
Definition: libvpxenc.c:89
void av_free_packet(AVPacket *pkt)
Free a packet.
Definition: avpacket.c:280
This structure describes decoded (raw) audio or video data.
Definition: frame.h:171
AVOption.
Definition: opt.h:255
int ff_side_data_set_encoder_stats(AVPacket *pkt, int quality, int64_t *error, int error_count, int pict_type)
Definition: avpacket.c:606
planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
Definition: pixfmt.h:171
struct vpx_codec_ctx encoder
Definition: libvpxenc.c:63
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: avcodec.h:2941
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd)
Rescale a 64-bit integer with specified rounding.
Definition: mathematics.c:63
#define OFFSET(x)
Definition: libvpxenc.c:949
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:68
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
#define LIBAVUTIL_VERSION_INT
Definition: version.h:62
static av_cold int init(AVCodecContext *avctx)
Definition: avrndec.c:35
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601 ...
Definition: pixfmt.h:523
int rc_initial_buffer_occupancy
Number of bits which should be loaded into the rc buffer before decoding starts.
Definition: avcodec.h:2643
int tile_columns
Definition: libvpxenc.c:99
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:1424
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above ...
Definition: pixfmt.h:524
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1722
size_t sz
length of compressed data
Definition: libvpxenc.c:47
static int sse(MpegEncContext *s, uint8_t *src1, uint8_t *src2, int w, int h, int stride)
char * stats_in
pass2 encoding statistics input buffer Concatenated stuff from stats_out of pass1 should be placed he...
Definition: avcodec.h:2779
int arnr_max_frames
Definition: libvpxenc.c:85
static AVPacket pkt
#define AV_CODEC_CAP_AUTO_THREADS
Codec supports avctx->thread_count == 0 (auto).
Definition: avcodec.h:932
struct vpx_codec_ctx encoder_alpha
Definition: libvpxenc.c:65
int profile
profile
Definition: avcodec.h:3115
int max_intra_rate
Definition: libvpxenc.c:93
AVCodec.
Definition: avcodec.h:3472
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB)
Definition: pixfmt.h:518
int error_resilient
Definition: libvpxenc.c:90
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented...
Definition: avcodec.h:1631
#define VP8F_AUTO_ALT_REF
Enable automatic alternate reference frame generation.
Definition: libvpxenc.c:81
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:72
#define AV_WB64(p, v)
Definition: intreadwrite.h:433
#define AV_CODEC_CAP_DELAY
Encoder or decoder requires flushing with NULL input at the end in order to give the complete and cor...
Definition: avcodec.h:882
int auto_alt_ref
Definition: libvpxenc.c:83
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:37
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:103
attribute_deprecated float rc_buffer_aggressivity
Definition: avcodec.h:2618
uint8_t
#define av_cold
Definition: attributes.h:74
static av_cold int codecctl_int(AVCodecContext *avctx, enum vp8e_enc_control_id id, int val)
Definition: libvpxenc.c:239
#define av_malloc(s)
int lossless
Definition: libvpxenc.c:98
int64_t pts
time stamp to show frame (in timebase units)
Definition: libvpxenc.c:50
AVOptions.
static void coded_frame_add(void *list, struct FrameListData *cx_frame)
Definition: libvpxenc.c:210
planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
Definition: pixfmt.h:292
#define FF_PROFILE_UNKNOWN
Definition: avcodec.h:3116
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:257
static AVFrame * frame
uint8_t * data
Definition: avcodec.h:1423
int av_reallocp(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:187
int frame_parallel
Definition: libvpxenc.c:101
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:192
ptrdiff_t size
Definition: opengl_enc.c:101
char * stats_out
pass1 encoding statistics output buffer
Definition: avcodec.h:2771
#define av_log(a,...)
#define LEGACY_OPTIONS
Definition: libvpxenc.c:985
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1469
planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
Definition: pixfmt.h:177
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
struct vpx_image rawimg
Definition: libvpxenc.c:64
static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame, AVPacket *pkt)
Store coded frame information in format suitable for return from encode2().
Definition: libvpxenc.c:687
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
int frame_skip_threshold
frame skip threshold
Definition: avcodec.h:2685
#define COMMON_OPTIONS
Definition: libvpxenc.c:957
int qmax
maximum quantizer
Definition: avcodec.h:2554
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:175
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
planar YUV 4:2:2, 20bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
Definition: pixfmt.h:173
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:1597
Round to nearest and halfway cases away from zero.
Definition: mathematics.h:75
int rc_max_rate
maximum bitrate
Definition: avcodec.h:2604
simple assert() macros that are a bit more flexible than ISO C assert().
const char * name
Name of the codec implementation.
Definition: avcodec.h:3479
static av_always_inline av_const double round(double x)
Definition: libm.h:162
char * av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size)
Encode data to base64 and null-terminate.
Definition: base64.c:138
Libavcodec external API header.
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:1429
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition: pixfmt.h:67
int rc_buffer_size
decoder bitstream buffer size
Definition: avcodec.h:2581
static void cx_pktcpy(struct FrameListData *dst, const struct vpx_codec_cx_pkt *src, const struct vpx_codec_cx_pkt *src_alpha, VP8Context *ctx)
Definition: libvpxenc.c:645
static av_cold void dump_enc_cfg(AVCodecContext *avctx, const struct vpx_codec_enc_cfg *cfg)
Definition: libvpxenc.c:148
int bit_rate
the average bitrate
Definition: avcodec.h:1567
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:242
#define AV_BASE64_SIZE(x)
Calculate the output size needed to base64-encode x bytes to a null-terminated string.
Definition: base64.h:61
int width
picture width / height.
Definition: avcodec.h:1681
ITU-R BT2020 non-constant luminance system.
Definition: pixfmt.h:527
int static_thresh
Definition: libvpxenc.c:92
#define AV_CODEC_FLAG_PSNR
error[?] variables will be set during encoding.
Definition: avcodec.h:767
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:751
uint64_t sse[4]
Definition: libvpxenc.c:70
static av_cold int vp8_free(AVCodecContext *avctx)
Definition: libvpxenc.c:260
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1640
planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
Definition: pixfmt.h:284
static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
Definition: libvpxenc.c:137
attribute_deprecated int mb_threshold
Definition: avcodec.h:2099
int arnr_strength
Definition: libvpxenc.c:86
int thread_count
thread count is used to decide how many independent tasks should be passed to execute() ...
Definition: avcodec.h:3033
struct FrameListData * next
Definition: libvpxenc.c:58
#define av_log2
Definition: intmath.h:100
#define VP8F_ERROR_RESILIENT
Enable measures appropriate for streaming over lossy links.
Definition: libvpxenc.c:80
static av_cold int vpx_init(AVCodecContext *avctx, const struct vpx_codec_iface *iface)
Definition: libvpxenc.c:379
int flags
VP8 specific flags, see VP8F_* below.
Definition: libvpxenc.c:79
static const AVCodecDefault defaults[]
Definition: libvpxenc.c:1024
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: frame.h:351
#define VE
Definition: libvpxenc.c:950
static const AVProfile profiles[]
AVS_Value src
Definition: avisynth_c.h:482
enum AVCodecID codec_id
Definition: avcodec.h:1519
av_cold void ff_vp9_init_static(AVCodec *codec)
Definition: libvpx.c:61
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:199
static av_cold int vp9_init(AVFormatContext *ctx, int st_index, PayloadContext *data)
Definition: rtpdec_vp9.c:34
main external API structure.
Definition: avcodec.h:1502
static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
Queue multiple output frames from the encoder, returning the front-most.
Definition: libvpxenc.c:765
int qmin
minimum quantizer
Definition: avcodec.h:2547
planar YUV 4:4:0,24bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian
Definition: pixfmt.h:321
void * buf
Definition: avisynth_c.h:553
Data found in BlockAdditional element of matroska container.
Definition: avcodec.h:1349
int deadline
Definition: libvpxenc.c:69
Describe the class of an AVClass context structure.
Definition: log.h:67
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:2230
int arnr_type
Definition: libvpxenc.c:87
uint32_t flags
flags for this frame
Definition: libvpxenc.c:54
#define snprintf
Definition: snprintf.h:34
int ff_alloc_packet2(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int64_t min_size)
Check AVPacket size and/or allocate data.
Definition: utils.c:1782
static av_cold void free_coded_frame(struct FrameListData *cx_frame)
Definition: libvpxenc.c:220
uint64_t frame_number
Definition: libvpxenc.c:57
float qcompress
amount of qscale change between easy & hard scenes (0.0-1.0)
Definition: avcodec.h:2539
static int set_pix_fmt(AVCodecContext *avctx, struct vpx_image *img)
Definition: libvpxdec.c:63
static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet)
Definition: libvpxenc.c:867
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:209
void * buf
compressed data buffer
Definition: libvpxenc.c:46
int rc_undershoot_pct
Definition: libvpxenc.c:94
size_t sz_alpha
Definition: libvpxenc.c:49
int have_sse
true if we have pending sse[]
Definition: libvpxenc.c:56
#define SIZE_SPECIFIER
Definition: internal.h:250
static int flags
Definition: cpu.c:47
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:182
uint8_t level
Definition: svq3.c:150
int noise_reduction
noise reduction strength
Definition: avcodec.h:2086
uint8_t is_alpha
Definition: libvpxenc.c:67
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition: avcodec.h:1707
static const char *const ctlidstr[]
String mappings for enum vp8e_enc_control_id.
Definition: libvpxenc.c:106
struct vpx_fixed_buf twopass_stats
Definition: libvpxenc.c:68
#define FF_PROFILE_VP9_1
Definition: avcodec.h:3190
static av_cold int vp8_init(AVFormatContext *s, int st_index, PayloadContext *vp8)
Definition: rtpdec_vp8.c:263
#define FF_PROFILE_VP9_3
Definition: avcodec.h:3192
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:63
planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
Definition: pixfmt.h:288
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:79
common internal api header.
int rc_overshoot_pct
Definition: libvpxenc.c:95
common internal and external API header
#define FF_PROFILE_VP9_0
Definition: avcodec.h:3189
AVProfile.
Definition: avcodec.h:3460
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:3024
int den
denominator
Definition: rational.h:45
static av_cold void free_frame_list(struct FrameListData *list)
Definition: libvpxenc.c:228
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition: avcodec.h:755
void * buf_alpha
Definition: libvpxenc.c:48
int slices
Number of slices.
Definition: avcodec.h:2253
void * priv_data
Definition: avcodec.h:1544
#define av_free(p)
#define FF_PROFILE_VP9_2
Definition: avcodec.h:3191
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:80
Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
Definition: libvpxenc.c:45
int tile_rows
Definition: libvpxenc.c:100
int key_frame
1 -> keyframe, 0-> not
Definition: frame.h:237
unsigned long duration
duration to show frame (in timebase units)
Definition: libvpxenc.c:52
int av_base64_decode(uint8_t *out, const char *in_str, int out_size)
Decode a base64-encoded string.
Definition: base64.c:79
int have_sse
true if we have pending sse[]
Definition: libvpxenc.c:71
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:1422
int height
Definition: frame.h:220
#define av_freep(p)
planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
Definition: pixfmt.h:101
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:299
int rc_min_rate
minimum bitrate
Definition: avcodec.h:2611
AVPixelFormat
Pixel format.
Definition: pixfmt.h:61
This structure stores compressed data.
Definition: avcodec.h:1400
struct FrameListData * coded_frame_list
Definition: libvpxenc.c:73
int aq_mode
Definition: libvpxenc.c:102
uint64_t frame_number
Definition: libvpxenc.c:72
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:1416
Predicted.
Definition: avutil.h:267
int keyint_min
minimum GOP size
Definition: avcodec.h:2171
static int width