FFmpeg  2.8.17
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Modules 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_SET_CPUUSED] = "VP8E_SET_CPUUSED",
108  [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
109  [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
110  [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
111  [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
112  [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
113  [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
114  [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
115  [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
116  [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
117 #if CONFIG_LIBVPX_VP9_ENCODER
118  [VP9E_SET_LOSSLESS] = "VP9E_SET_LOSSLESS",
119  [VP9E_SET_TILE_COLUMNS] = "VP9E_SET_TILE_COLUMNS",
120  [VP9E_SET_TILE_ROWS] = "VP9E_SET_TILE_ROWS",
121  [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
122  [VP9E_SET_AQ_MODE] = "VP9E_SET_AQ_MODE",
123 #if VPX_ENCODER_ABI_VERSION > 8
124  [VP9E_SET_COLOR_SPACE] = "VP9E_SET_COLOR_SPACE",
125 #endif
126 #endif
127 };
128 
129 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
130 {
131  VP8Context *ctx = avctx->priv_data;
132  const char *error = vpx_codec_error(&ctx->encoder);
133  const char *detail = vpx_codec_error_detail(&ctx->encoder);
134 
135  av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
136  if (detail)
137  av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
138 }
139 
141  const struct vpx_codec_enc_cfg *cfg)
142 {
143  int width = -30;
144  int level = AV_LOG_DEBUG;
145 
146  av_log(avctx, level, "vpx_codec_enc_cfg\n");
147  av_log(avctx, level, "generic settings\n"
148  " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
149 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
150  " %*s%u\n %*s%u\n"
151 #endif
152  " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
153  width, "g_usage:", cfg->g_usage,
154  width, "g_threads:", cfg->g_threads,
155  width, "g_profile:", cfg->g_profile,
156  width, "g_w:", cfg->g_w,
157  width, "g_h:", cfg->g_h,
158 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
159  width, "g_bit_depth:", cfg->g_bit_depth,
160  width, "g_input_bit_depth:", cfg->g_input_bit_depth,
161 #endif
162  width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
163  width, "g_error_resilient:", cfg->g_error_resilient,
164  width, "g_pass:", cfg->g_pass,
165  width, "g_lag_in_frames:", cfg->g_lag_in_frames);
166  av_log(avctx, level, "rate control settings\n"
167  " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
168  " %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
169  width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
170  width, "rc_resize_allowed:", cfg->rc_resize_allowed,
171  width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
172  width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
173  width, "rc_end_usage:", cfg->rc_end_usage,
174  width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
175  width, "rc_target_bitrate:", cfg->rc_target_bitrate);
176  av_log(avctx, level, "quantizer settings\n"
177  " %*s%u\n %*s%u\n",
178  width, "rc_min_quantizer:", cfg->rc_min_quantizer,
179  width, "rc_max_quantizer:", cfg->rc_max_quantizer);
180  av_log(avctx, level, "bitrate tolerance\n"
181  " %*s%u\n %*s%u\n",
182  width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
183  width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
184  av_log(avctx, level, "decoder buffer model\n"
185  " %*s%u\n %*s%u\n %*s%u\n",
186  width, "rc_buf_sz:", cfg->rc_buf_sz,
187  width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
188  width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
189  av_log(avctx, level, "2 pass rate control settings\n"
190  " %*s%u\n %*s%u\n %*s%u\n",
191  width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
192  width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
193  width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
194  av_log(avctx, level, "keyframing settings\n"
195  " %*s%d\n %*s%u\n %*s%u\n",
196  width, "kf_mode:", cfg->kf_mode,
197  width, "kf_min_dist:", cfg->kf_min_dist,
198  width, "kf_max_dist:", cfg->kf_max_dist);
199  av_log(avctx, level, "\n");
200 }
201 
202 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
203 {
204  struct FrameListData **p = list;
205 
206  while (*p)
207  p = &(*p)->next;
208  *p = cx_frame;
209  cx_frame->next = NULL;
210 }
211 
212 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
213 {
214  av_freep(&cx_frame->buf);
215  if (cx_frame->buf_alpha)
216  av_freep(&cx_frame->buf_alpha);
217  av_freep(&cx_frame);
218 }
219 
220 static av_cold void free_frame_list(struct FrameListData *list)
221 {
222  struct FrameListData *p = list;
223 
224  while (p) {
225  list = list->next;
226  free_coded_frame(p);
227  p = list;
228  }
229 }
230 
232  enum vp8e_enc_control_id id, int val)
233 {
234  VP8Context *ctx = avctx->priv_data;
235  char buf[80];
236  int width = -30;
237  int res;
238 
239  snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
240  av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
241 
242  res = vpx_codec_control(&ctx->encoder, id, val);
243  if (res != VPX_CODEC_OK) {
244  snprintf(buf, sizeof(buf), "Failed to set %s codec control",
245  ctlidstr[id]);
246  log_encoder_error(avctx, buf);
247  }
248 
249  return res == VPX_CODEC_OK ? 0 : AVERROR(EINVAL);
250 }
251 
252 static av_cold int vp8_free(AVCodecContext *avctx)
253 {
254  VP8Context *ctx = avctx->priv_data;
255 
256  vpx_codec_destroy(&ctx->encoder);
257  if (ctx->is_alpha)
258  vpx_codec_destroy(&ctx->encoder_alpha);
259  av_freep(&ctx->twopass_stats.buf);
260  av_freep(&avctx->stats_out);
262  return 0;
263 }
264 
265 #if CONFIG_LIBVPX_VP9_ENCODER
266 static int set_pix_fmt(AVCodecContext *avctx, vpx_codec_caps_t codec_caps,
267  struct vpx_codec_enc_cfg *enccfg, vpx_codec_flags_t *flags,
268  vpx_img_fmt_t *img_fmt)
269 {
270 #ifdef VPX_IMG_FMT_HIGHBITDEPTH
271  enccfg->g_bit_depth = enccfg->g_input_bit_depth = 8;
272 #endif
273  switch (avctx->pix_fmt) {
274  case AV_PIX_FMT_YUV420P:
275  enccfg->g_profile = 0;
276  *img_fmt = VPX_IMG_FMT_I420;
277  return 0;
278  case AV_PIX_FMT_YUV422P:
279  enccfg->g_profile = 1;
280  *img_fmt = VPX_IMG_FMT_I422;
281  return 0;
282 #if VPX_IMAGE_ABI_VERSION >= 3
283  case AV_PIX_FMT_YUV440P:
284  enccfg->g_profile = 1;
285  *img_fmt = VPX_IMG_FMT_I440;
286  return 0;
287 #endif
288  case AV_PIX_FMT_YUV444P:
289  enccfg->g_profile = 1;
290  *img_fmt = VPX_IMG_FMT_I444;
291  return 0;
292 #ifdef VPX_IMG_FMT_HIGHBITDEPTH
295  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
296  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
297  avctx->pix_fmt == AV_PIX_FMT_YUV420P10LE ? 10 : 12;
298  enccfg->g_profile = 2;
299  *img_fmt = VPX_IMG_FMT_I42016;
300  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
301  return 0;
302  }
303  break;
306  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
307  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
308  avctx->pix_fmt == AV_PIX_FMT_YUV422P10LE ? 10 : 12;
309  enccfg->g_profile = 3;
310  *img_fmt = VPX_IMG_FMT_I42216;
311  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
312  return 0;
313  }
314  break;
315 #if VPX_IMAGE_ABI_VERSION >= 3
318  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
319  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
320  avctx->pix_fmt == AV_PIX_FMT_YUV440P10LE ? 10 : 12;
321  enccfg->g_profile = 3;
322  *img_fmt = VPX_IMG_FMT_I44016;
323  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
324  return 0;
325  }
326  break;
327 #endif
330  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
331  enccfg->g_bit_depth = enccfg->g_input_bit_depth =
332  avctx->pix_fmt == AV_PIX_FMT_YUV444P10LE ? 10 : 12;
333  enccfg->g_profile = 3;
334  *img_fmt = VPX_IMG_FMT_I44416;
335  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
336  return 0;
337  }
338  break;
339 #endif
340  default:
341  break;
342  }
343  av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
344  return AVERROR_INVALIDDATA;
345 }
346 
347 #if VPX_ENCODER_ABI_VERSION > 8
348 static void set_colorspace(AVCodecContext *avctx)
349 {
350  enum vpx_color_space vpx_cs;
351 
352  switch (avctx->colorspace) {
353  case AVCOL_SPC_RGB: vpx_cs = VPX_CS_SRGB; break;
354  case AVCOL_SPC_BT709: vpx_cs = VPX_CS_BT_709; break;
355  case AVCOL_SPC_UNSPECIFIED: vpx_cs = VPX_CS_UNKNOWN; break;
356  case AVCOL_SPC_RESERVED: vpx_cs = VPX_CS_RESERVED; break;
357  case AVCOL_SPC_BT470BG: vpx_cs = VPX_CS_BT_601; break;
358  case AVCOL_SPC_SMPTE170M: vpx_cs = VPX_CS_SMPTE_170; break;
359  case AVCOL_SPC_SMPTE240M: vpx_cs = VPX_CS_SMPTE_240; break;
360  case AVCOL_SPC_BT2020_NCL: vpx_cs = VPX_CS_BT_2020; break;
361  default:
362  av_log(avctx, AV_LOG_WARNING, "Unsupported colorspace (%d)\n",
363  avctx->colorspace);
364  return;
365  }
366  codecctl_int(avctx, VP9E_SET_COLOR_SPACE, vpx_cs);
367 }
368 #endif
369 #endif
370 
371 static av_cold int vpx_init(AVCodecContext *avctx,
372  const struct vpx_codec_iface *iface)
373 {
374  VP8Context *ctx = avctx->priv_data;
375  struct vpx_codec_enc_cfg enccfg = { 0 };
376  struct vpx_codec_enc_cfg enccfg_alpha;
377  vpx_codec_flags_t flags = (avctx->flags & AV_CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
378  int res;
379  vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
380 #if CONFIG_LIBVPX_VP9_ENCODER
381  vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
382 #endif
383 
384  av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
385  av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
386 
387  if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
388  ctx->is_alpha = 1;
389 
390  if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
391  av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
392  vpx_codec_err_to_string(res));
393  return AVERROR(EINVAL);
394  }
395 
396 #if CONFIG_LIBVPX_VP9_ENCODER
397  if (avctx->codec_id == AV_CODEC_ID_VP9) {
398  if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
399  return AVERROR(EINVAL);
400  }
401 #endif
402 
403  if(!avctx->bit_rate)
404  if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
405  av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
406  return AVERROR(EINVAL);
407  }
408 
409  dump_enc_cfg(avctx, &enccfg);
410 
411  enccfg.g_w = avctx->width;
412  enccfg.g_h = avctx->height;
413  enccfg.g_timebase.num = avctx->time_base.num;
414  enccfg.g_timebase.den = avctx->time_base.den;
415  enccfg.g_threads = avctx->thread_count;
416  enccfg.g_lag_in_frames= ctx->lag_in_frames;
417 
418  if (avctx->flags & AV_CODEC_FLAG_PASS1)
419  enccfg.g_pass = VPX_RC_FIRST_PASS;
420  else if (avctx->flags & AV_CODEC_FLAG_PASS2)
421  enccfg.g_pass = VPX_RC_LAST_PASS;
422  else
423  enccfg.g_pass = VPX_RC_ONE_PASS;
424 
425  if (avctx->rc_min_rate == avctx->rc_max_rate &&
426  avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
427  enccfg.rc_end_usage = VPX_CBR;
428  } else if (ctx->crf >= 0) {
429  enccfg.rc_end_usage = VPX_CQ;
430 #if CONFIG_LIBVPX_VP9_ENCODER
431  if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
432  enccfg.rc_end_usage = VPX_Q;
433 #endif
434  }
435 
436  if (avctx->bit_rate) {
437  enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
439 #if CONFIG_LIBVPX_VP9_ENCODER
440  } else if (enccfg.rc_end_usage == VPX_Q) {
441 #endif
442  } else {
443  if (enccfg.rc_end_usage == VPX_CQ) {
444  enccfg.rc_target_bitrate = 1000000;
445  } else {
446  avctx->bit_rate = enccfg.rc_target_bitrate * 1000;
447  av_log(avctx, AV_LOG_WARNING,
448  "Neither bitrate nor constrained quality specified, using default bitrate of %dkbit/sec\n",
449  enccfg.rc_target_bitrate);
450  }
451  }
452 
453  if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
454  enccfg.rc_min_quantizer =
455  enccfg.rc_max_quantizer = 0;
456  } else {
457  if (avctx->qmin >= 0)
458  enccfg.rc_min_quantizer = avctx->qmin;
459  if (avctx->qmax >= 0)
460  enccfg.rc_max_quantizer = avctx->qmax;
461  }
462 
463  if (enccfg.rc_end_usage == VPX_CQ
465  || enccfg.rc_end_usage == VPX_Q
466 #endif
467  ) {
468  if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
469  av_log(avctx, AV_LOG_ERROR,
470  "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
471  ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
472  return AVERROR(EINVAL);
473  }
474  }
475 
476  enccfg.rc_dropframe_thresh = avctx->frame_skip_threshold;
477 
478  //0-100 (0 => CBR, 100 => VBR)
479  enccfg.rc_2pass_vbr_bias_pct = round(avctx->qcompress * 100);
480  if (avctx->bit_rate)
481  enccfg.rc_2pass_vbr_minsection_pct =
482  avctx->rc_min_rate * 100LL / avctx->bit_rate;
483  if (avctx->rc_max_rate)
484  enccfg.rc_2pass_vbr_maxsection_pct =
485  avctx->rc_max_rate * 100LL / avctx->bit_rate;
486 
487  if (avctx->rc_buffer_size)
488  enccfg.rc_buf_sz =
489  avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
490  if (avctx->rc_initial_buffer_occupancy)
491  enccfg.rc_buf_initial_sz =
492  avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
493  enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
494 #if FF_API_MPV_OPT
496  if (avctx->rc_buffer_aggressivity != 1.0) {
497  av_log(avctx, AV_LOG_WARNING, "The rc_buffer_aggressivity option is "
498  "deprecated, use the undershoot-pct private option instead.\n");
499  enccfg.rc_undershoot_pct = round(avctx->rc_buffer_aggressivity * 100);
500  }
502 #endif
503  if (ctx->rc_undershoot_pct >= 0)
504  enccfg.rc_undershoot_pct = ctx->rc_undershoot_pct;
505  if (ctx->rc_overshoot_pct >= 0)
506  enccfg.rc_overshoot_pct = ctx->rc_overshoot_pct;
507 
508  //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
509  if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
510  enccfg.kf_min_dist = avctx->keyint_min;
511  if (avctx->gop_size >= 0)
512  enccfg.kf_max_dist = avctx->gop_size;
513 
514  if (enccfg.g_pass == VPX_RC_FIRST_PASS)
515  enccfg.g_lag_in_frames = 0;
516  else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
517  int decode_size, ret;
518 
519  if (!avctx->stats_in) {
520  av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
521  return AVERROR_INVALIDDATA;
522  }
523 
524  ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
525  ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
526  if (ret < 0) {
527  av_log(avctx, AV_LOG_ERROR,
528  "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
529  ctx->twopass_stats.sz);
530  ctx->twopass_stats.sz = 0;
531  return ret;
532  }
533  decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
534  ctx->twopass_stats.sz);
535  if (decode_size < 0) {
536  av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
537  return AVERROR_INVALIDDATA;
538  }
539 
540  ctx->twopass_stats.sz = decode_size;
541  enccfg.rc_twopass_stats_in = ctx->twopass_stats;
542  }
543 
544  /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
545  complexity playback on low powered devices at the expense of encode
546  quality. */
547  if (avctx->profile != FF_PROFILE_UNKNOWN)
548  enccfg.g_profile = avctx->profile;
549 
550  enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
551 
552  dump_enc_cfg(avctx, &enccfg);
553  /* Construct Encoder Context */
554  res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
555  if (res != VPX_CODEC_OK) {
556  log_encoder_error(avctx, "Failed to initialize encoder");
557  return AVERROR(EINVAL);
558  }
559 
560  if (ctx->is_alpha) {
561  enccfg_alpha = enccfg;
562  res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
563  if (res != VPX_CODEC_OK) {
564  log_encoder_error(avctx, "Failed to initialize alpha encoder");
565  return AVERROR(EINVAL);
566  }
567  }
568 
569  //codec control failures are currently treated only as warnings
570  av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
571  codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
572  if (ctx->flags & VP8F_AUTO_ALT_REF)
573  ctx->auto_alt_ref = 1;
574  if (ctx->auto_alt_ref >= 0)
575  codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF, ctx->auto_alt_ref);
576  if (ctx->arnr_max_frames >= 0)
577  codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
578  if (ctx->arnr_strength >= 0)
579  codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
580  if (ctx->arnr_type >= 0)
581  codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
582 
584  codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, avctx->noise_reduction);
585  codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
586  }
587 #if FF_API_MPV_OPT
589  if (avctx->mb_threshold) {
590  av_log(avctx, AV_LOG_WARNING, "The mb_threshold option is deprecated, "
591  "use the static-thresh private option instead.\n");
592  ctx->static_thresh = avctx->mb_threshold;
593  }
595 #endif
596  codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
597  if (ctx->crf >= 0)
598  codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
599  if (ctx->max_intra_rate >= 0)
600  codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
601 
602 #if CONFIG_LIBVPX_VP9_ENCODER
603  if (avctx->codec_id == AV_CODEC_ID_VP9) {
604  if (ctx->lossless >= 0)
605  codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
606  if (ctx->tile_columns >= 0)
607  codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
608  if (ctx->tile_rows >= 0)
609  codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
610  if (ctx->frame_parallel >= 0)
611  codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
612  if (ctx->aq_mode >= 0)
613  codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
614 #if VPX_ENCODER_ABI_VERSION > 8
615  set_colorspace(avctx);
616 #endif
617  }
618 #endif
619 
620  av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
621 
622  //provide dummy value to initialize wrapper, values will be updated each _encode()
623  vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
624  (unsigned char*)1);
625 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_IMG_FMT_HIGHBITDEPTH)
626  if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
627  ctx->rawimg.bit_depth = enccfg.g_bit_depth;
628 #endif
629 
630  if (ctx->is_alpha)
631  vpx_img_wrap(&ctx->rawimg_alpha, VPX_IMG_FMT_I420, avctx->width, avctx->height, 1,
632  (unsigned char*)1);
633 
634  return 0;
635 }
636 
637 static inline void cx_pktcpy(struct FrameListData *dst,
638  const struct vpx_codec_cx_pkt *src,
639  const struct vpx_codec_cx_pkt *src_alpha,
640  VP8Context *ctx)
641 {
642  dst->pts = src->data.frame.pts;
643  dst->duration = src->data.frame.duration;
644  dst->flags = src->data.frame.flags;
645  dst->sz = src->data.frame.sz;
646  dst->buf = src->data.frame.buf;
647  dst->have_sse = 0;
648  /* For alt-ref frame, don't store PSNR or increment frame_number */
649  if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
650  dst->frame_number = ++ctx->frame_number;
651  dst->have_sse = ctx->have_sse;
652  if (ctx->have_sse) {
653  /* associate last-seen SSE to the frame. */
654  /* Transfers ownership from ctx to dst. */
655  /* WARNING! This makes the assumption that PSNR_PKT comes
656  just before the frame it refers to! */
657  memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
658  ctx->have_sse = 0;
659  }
660  } else {
661  dst->frame_number = -1; /* sanity marker */
662  }
663  if (src_alpha) {
664  dst->buf_alpha = src_alpha->data.frame.buf;
665  dst->sz_alpha = src_alpha->data.frame.sz;
666  } else {
667  dst->buf_alpha = NULL;
668  dst->sz_alpha = 0;
669  }
670 }
671 
672 /**
673  * Store coded frame information in format suitable for return from encode2().
674  *
675  * Write information from @a cx_frame to @a pkt
676  * @return packet data size on success
677  * @return a negative AVERROR on error
678  */
679 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
680  AVPacket *pkt)
681 {
682  int ret = ff_alloc_packet2(avctx, pkt, cx_frame->sz, 0);
683  uint8_t *side_data;
684  if (ret >= 0) {
685  int pict_type;
686  memcpy(pkt->data, cx_frame->buf, pkt->size);
687  pkt->pts = pkt->dts = cx_frame->pts;
688 #if FF_API_CODED_FRAME
690  avctx->coded_frame->pts = cx_frame->pts;
691  avctx->coded_frame->key_frame = !!(cx_frame->flags & VPX_FRAME_IS_KEY);
693 #endif
694 
695  if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
696  pict_type = AV_PICTURE_TYPE_I;
697 #if FF_API_CODED_FRAME
699  avctx->coded_frame->pict_type = pict_type;
701 #endif
702  pkt->flags |= AV_PKT_FLAG_KEY;
703  } else {
704  pict_type = AV_PICTURE_TYPE_P;
705 #if FF_API_CODED_FRAME
707  avctx->coded_frame->pict_type = pict_type;
709 #endif
710  }
711 
712  ff_side_data_set_encoder_stats(pkt, 0, cx_frame->sse + 1,
713  cx_frame->have_sse ? 3 : 0, pict_type);
714 
715  if (cx_frame->have_sse) {
716  int i;
717  /* Beware of the Y/U/V/all order! */
718 #if FF_API_CODED_FRAME
720  avctx->coded_frame->error[0] = cx_frame->sse[1];
721  avctx->coded_frame->error[1] = cx_frame->sse[2];
722  avctx->coded_frame->error[2] = cx_frame->sse[3];
723  avctx->coded_frame->error[3] = 0; // alpha
725 #endif
726  for (i = 0; i < 3; ++i) {
727  avctx->error[i] += cx_frame->sse[i + 1];
728  }
729  cx_frame->have_sse = 0;
730  }
731  if (cx_frame->sz_alpha > 0) {
732  side_data = av_packet_new_side_data(pkt,
734  cx_frame->sz_alpha + 8);
735  if(!side_data) {
736  av_free_packet(pkt);
737  return AVERROR(ENOMEM);
738  }
739  AV_WB64(side_data, 1);
740  memcpy(side_data + 8, cx_frame->buf_alpha, cx_frame->sz_alpha);
741  }
742  } else {
743  return ret;
744  }
745  return pkt->size;
746 }
747 
748 /**
749  * Queue multiple output frames from the encoder, returning the front-most.
750  * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
751  * the frame queue. Return the head frame if available.
752  * @return Stored frame size
753  * @return AVERROR(EINVAL) on output size error
754  * @return AVERROR(ENOMEM) on coded frame queue data allocation error
755  */
756 static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
757 {
758  VP8Context *ctx = avctx->priv_data;
759  const struct vpx_codec_cx_pkt *pkt;
760  const struct vpx_codec_cx_pkt *pkt_alpha = NULL;
761  const void *iter = NULL;
762  const void *iter_alpha = NULL;
763  int size = 0;
764 
765  if (ctx->coded_frame_list) {
766  struct FrameListData *cx_frame = ctx->coded_frame_list;
767  /* return the leading frame if we've already begun queueing */
768  size = storeframe(avctx, cx_frame, pkt_out);
769  if (size < 0)
770  return size;
771  ctx->coded_frame_list = cx_frame->next;
772  free_coded_frame(cx_frame);
773  }
774 
775  /* consume all available output from the encoder before returning. buffers
776  are only good through the next vpx_codec call */
777  while ((pkt = vpx_codec_get_cx_data(&ctx->encoder, &iter)) &&
778  (!ctx->is_alpha ||
779  (ctx->is_alpha && (pkt_alpha = vpx_codec_get_cx_data(&ctx->encoder_alpha, &iter_alpha))))) {
780  switch (pkt->kind) {
781  case VPX_CODEC_CX_FRAME_PKT:
782  if (!size) {
783  struct FrameListData cx_frame;
784 
785  /* avoid storing the frame when the list is empty and we haven't yet
786  provided a frame for output */
788  cx_pktcpy(&cx_frame, pkt, pkt_alpha, ctx);
789  size = storeframe(avctx, &cx_frame, pkt_out);
790  if (size < 0)
791  return size;
792  } else {
793  struct FrameListData *cx_frame =
794  av_malloc(sizeof(struct FrameListData));
795 
796  if (!cx_frame) {
797  av_log(avctx, AV_LOG_ERROR,
798  "Frame queue element alloc failed\n");
799  return AVERROR(ENOMEM);
800  }
801  cx_pktcpy(cx_frame, pkt, pkt_alpha, ctx);
802  cx_frame->buf = av_malloc(cx_frame->sz);
803 
804  if (!cx_frame->buf) {
805  av_log(avctx, AV_LOG_ERROR,
806  "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
807  cx_frame->sz);
808  av_freep(&cx_frame);
809  return AVERROR(ENOMEM);
810  }
811  memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
812  if (ctx->is_alpha) {
813  cx_frame->buf_alpha = av_malloc(cx_frame->sz_alpha);
814  if (!cx_frame->buf_alpha) {
815  av_log(avctx, AV_LOG_ERROR,
816  "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
817  cx_frame->sz_alpha);
818  av_free(cx_frame);
819  return AVERROR(ENOMEM);
820  }
821  memcpy(cx_frame->buf_alpha, pkt_alpha->data.frame.buf, pkt_alpha->data.frame.sz);
822  }
823  coded_frame_add(&ctx->coded_frame_list, cx_frame);
824  }
825  break;
826  case VPX_CODEC_STATS_PKT: {
827  struct vpx_fixed_buf *stats = &ctx->twopass_stats;
828  int err;
829  if ((err = av_reallocp(&stats->buf,
830  stats->sz +
831  pkt->data.twopass_stats.sz)) < 0) {
832  stats->sz = 0;
833  av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
834  return err;
835  }
836  memcpy((uint8_t*)stats->buf + stats->sz,
837  pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
838  stats->sz += pkt->data.twopass_stats.sz;
839  break;
840  }
841  case VPX_CODEC_PSNR_PKT:
842  av_assert0(!ctx->have_sse);
843  ctx->sse[0] = pkt->data.psnr.sse[0];
844  ctx->sse[1] = pkt->data.psnr.sse[1];
845  ctx->sse[2] = pkt->data.psnr.sse[2];
846  ctx->sse[3] = pkt->data.psnr.sse[3];
847  ctx->have_sse = 1;
848  break;
849  case VPX_CODEC_CUSTOM_PKT:
850  //ignore unsupported/unrecognized packet types
851  break;
852  }
853  }
854 
855  return size;
856 }
857 
858 static int vp8_encode(AVCodecContext *avctx, AVPacket *pkt,
859  const AVFrame *frame, int *got_packet)
860 {
861  VP8Context *ctx = avctx->priv_data;
862  struct vpx_image *rawimg = NULL;
863  struct vpx_image *rawimg_alpha = NULL;
864  int64_t timestamp = 0;
865  int res, coded_size;
866  vpx_enc_frame_flags_t flags = 0;
867 
868  if (frame) {
869  rawimg = &ctx->rawimg;
870  rawimg->planes[VPX_PLANE_Y] = frame->data[0];
871  rawimg->planes[VPX_PLANE_U] = frame->data[1];
872  rawimg->planes[VPX_PLANE_V] = frame->data[2];
873  rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
874  rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
875  rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
876  if (ctx->is_alpha) {
877  uint8_t *u_plane, *v_plane;
878  rawimg_alpha = &ctx->rawimg_alpha;
879  rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
880  u_plane = av_malloc(frame->linesize[1] * frame->height);
881  v_plane = av_malloc(frame->linesize[2] * frame->height);
882  if (!u_plane || !v_plane) {
883  av_free(u_plane);
884  av_free(v_plane);
885  return AVERROR(ENOMEM);
886  }
887  memset(u_plane, 0x80, frame->linesize[1] * frame->height);
888  rawimg_alpha->planes[VPX_PLANE_U] = u_plane;
889  memset(v_plane, 0x80, frame->linesize[2] * frame->height);
890  rawimg_alpha->planes[VPX_PLANE_V] = v_plane;
891  rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[0];
892  rawimg_alpha->stride[VPX_PLANE_U] = frame->linesize[1];
893  rawimg_alpha->stride[VPX_PLANE_V] = frame->linesize[2];
894  }
895  timestamp = frame->pts;
896  if (frame->pict_type == AV_PICTURE_TYPE_I)
897  flags |= VPX_EFLAG_FORCE_KF;
898  }
899 
900  res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
901  avctx->ticks_per_frame, flags, ctx->deadline);
902  if (res != VPX_CODEC_OK) {
903  log_encoder_error(avctx, "Error encoding frame");
904  return AVERROR_INVALIDDATA;
905  }
906 
907  if (ctx->is_alpha) {
908  res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
909  avctx->ticks_per_frame, flags, ctx->deadline);
910  if (res != VPX_CODEC_OK) {
911  log_encoder_error(avctx, "Error encoding alpha frame");
912  return AVERROR_INVALIDDATA;
913  }
914  }
915 
916  coded_size = queue_frames(avctx, pkt);
917 
918  if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
919  unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
920 
921  avctx->stats_out = av_malloc(b64_size);
922  if (!avctx->stats_out) {
923  av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
924  b64_size);
925  return AVERROR(ENOMEM);
926  }
927  av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
928  ctx->twopass_stats.sz);
929  }
930 
931  if (rawimg_alpha) {
932  av_freep(&rawimg_alpha->planes[VPX_PLANE_U]);
933  av_freep(&rawimg_alpha->planes[VPX_PLANE_V]);
934  }
935 
936  *got_packet = !!coded_size;
937  return 0;
938 }
939 
940 #define OFFSET(x) offsetof(VP8Context, x)
941 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
942 
943 #ifndef VPX_ERROR_RESILIENT_DEFAULT
944 #define VPX_ERROR_RESILIENT_DEFAULT 1
945 #define VPX_ERROR_RESILIENT_PARTITIONS 2
946 #endif
947 
948 #define COMMON_OPTIONS \
949  { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
950  { "auto-alt-ref", "Enable use of alternate reference " \
951  "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE}, \
952  { "lag-in-frames", "Number of frames to look ahead for " \
953  "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
954  { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
955  { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
956  { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
957  { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
958  { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
959  { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
960  { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
961  { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
962  { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
963  { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
964  { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
965  { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
966  { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
967  { "partitions", "The frame partitions are independently decodable " \
968  "by the bool decoder, meaning that partitions can be decoded even " \
969  "though earlier partitions have been lost. Note that intra predicition" \
970  " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
971  { "crf", "Select the quality for constant quality mode", offsetof(VP8Context, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
972  { "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 }, \
973  { "undershoot-pct", "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
974  { "overshoot-pct", "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
975 
976 #define LEGACY_OPTIONS \
977  {"speed", "", offsetof(VP8Context, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
978  {"quality", "", offsetof(VP8Context, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
979  {"vp8flags", "", offsetof(VP8Context, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
980  {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
981  {"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"}, \
982  {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VP8Context, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
983  {"arnr_strength", "altref noise reduction filter strength", offsetof(VP8Context, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
984  {"arnr_type", "altref noise reduction filter type", offsetof(VP8Context, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
985  {"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}, \
986 
987 #if CONFIG_LIBVPX_VP8_ENCODER
988 static const AVOption vp8_options[] = {
991  { NULL }
992 };
993 #endif
994 
995 #if CONFIG_LIBVPX_VP9_ENCODER
996 static const AVOption vp9_options[] = {
998  { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
999  { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1000  { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1001  { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
1002  { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
1003  { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
1004  { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
1005  { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
1006  { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
1008  { NULL }
1009 };
1010 #endif
1011 
1012 #undef COMMON_OPTIONS
1013 #undef LEGACY_OPTIONS
1014 
1015 static const AVCodecDefault defaults[] = {
1016  { "qmin", "-1" },
1017  { "qmax", "-1" },
1018  { "g", "-1" },
1019  { "keyint_min", "-1" },
1020  { NULL },
1021 };
1022 
1023 #if CONFIG_LIBVPX_VP8_ENCODER
1024 static av_cold int vp8_init(AVCodecContext *avctx)
1025 {
1026  return vpx_init(avctx, vpx_codec_vp8_cx());
1027 }
1028 
1029 static const AVClass class_vp8 = {
1030  .class_name = "libvpx-vp8 encoder",
1031  .item_name = av_default_item_name,
1032  .option = vp8_options,
1033  .version = LIBAVUTIL_VERSION_INT,
1034 };
1035 
1036 AVCodec ff_libvpx_vp8_encoder = {
1037  .name = "libvpx",
1038  .long_name = NULL_IF_CONFIG_SMALL("libvpx VP8"),
1039  .type = AVMEDIA_TYPE_VIDEO,
1040  .id = AV_CODEC_ID_VP8,
1041  .priv_data_size = sizeof(VP8Context),
1042  .init = vp8_init,
1043  .encode2 = vp8_encode,
1044  .close = vp8_free,
1047  .priv_class = &class_vp8,
1048  .defaults = defaults,
1049 };
1050 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
1051 
1052 #if CONFIG_LIBVPX_VP9_ENCODER
1053 static av_cold int vp9_init(AVCodecContext *avctx)
1054 {
1055  return vpx_init(avctx, vpx_codec_vp9_cx());
1056 }
1057 
1058 static const AVClass class_vp9 = {
1059  .class_name = "libvpx-vp9 encoder",
1060  .item_name = av_default_item_name,
1061  .option = vp9_options,
1062  .version = LIBAVUTIL_VERSION_INT,
1063 };
1064 
1065 static const AVProfile profiles[] = {
1066  { FF_PROFILE_VP9_0, "Profile 0" },
1067  { FF_PROFILE_VP9_1, "Profile 1" },
1068  { FF_PROFILE_VP9_2, "Profile 2" },
1069  { FF_PROFILE_VP9_3, "Profile 3" },
1070  { FF_PROFILE_UNKNOWN },
1071 };
1072 
1073 AVCodec ff_libvpx_vp9_encoder = {
1074  .name = "libvpx-vp9",
1075  .long_name = NULL_IF_CONFIG_SMALL("libvpx VP9"),
1076  .type = AVMEDIA_TYPE_VIDEO,
1077  .id = AV_CODEC_ID_VP9,
1078  .priv_data_size = sizeof(VP8Context),
1079  .init = vp9_init,
1080  .encode2 = vp8_encode,
1081  .close = vp8_free,
1083  .profiles = NULL_IF_CONFIG_SMALL(profiles),
1084  .priv_class = &class_vp9,
1085  .defaults = defaults,
1086  .init_static_data = ff_vp9_init_static,
1087 };
1088 #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:523
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:323
#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:284
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:618
planar YUV 4:2:0, 15bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
Definition: pixfmt.h:175
struct vpx_codec_ctx encoder
Definition: libvpxenc.c:63
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: avcodec.h:2951
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:940
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:72
#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:527
int rc_initial_buffer_occupancy
Number of bits which should be loaded into the rc buffer before decoding starts.
Definition: avcodec.h:2653
int tile_columns
Definition: libvpxenc.c:99
int num
numerator
Definition: rational.h:44
int size
Definition: avcodec.h:1434
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above ...
Definition: pixfmt.h:528
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:1732
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:2789
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:3125
int max_intra_rate
Definition: libvpxenc.c:93
AVCodec.
Definition: avcodec.h:3482
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB)
Definition: pixfmt.h:522
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:1641
#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:107
attribute_deprecated float rc_buffer_aggressivity
Definition: avcodec.h:2628
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:231
#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:202
planar YUV 4:4:4,36bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
Definition: pixfmt.h:296
#define FF_PROFILE_UNKNOWN
Definition: avcodec.h:3126
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:1433
int av_reallocp(void *ptr, size_t size)
Allocate or reallocate a block of memory.
Definition: mem.c:187
#define CONFIG_LIBVPX_VP9_ENCODER
Definition: config.h:1444
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:2781
#define av_log(a,...)
#define LEGACY_OPTIONS
Definition: libvpxenc.c:976
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: avcodec.h:1479
planar YUV 4:4:4, 30bpp, (1 Cr & Cb sample per 1x1 Y samples), little-endian
Definition: pixfmt.h:181
#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:679
av_default_item_name
#define AVERROR(e)
Definition: error.h:43
int frame_skip_threshold
frame skip threshold
Definition: avcodec.h:2695
#define CONFIG_LIBVPX_VP8_ENCODER
Definition: config.h:1443
#define COMMON_OPTIONS
Definition: libvpxenc.c:948
int qmax
maximum quantizer
Definition: avcodec.h:2564
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:178
#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:177
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:1607
Round to nearest and halfway cases away from zero.
Definition: mathematics.h:75
int rc_max_rate
maximum bitrate
Definition: avcodec.h:2614
simple assert() macros that are a bit more flexible than ISO C assert().
const char * name
Name of the codec implementation.
Definition: avcodec.h:3489
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:1439
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition: pixfmt.h:71
int rc_buffer_size
decoder bitstream buffer size
Definition: avcodec.h:2591
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:637
static av_cold void dump_enc_cfg(AVCodecContext *avctx, const struct vpx_codec_enc_cfg *cfg)
Definition: libvpxenc.c:140
int bit_rate
the average bitrate
Definition: avcodec.h:1577
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:1691
ITU-R BT2020 non-constant luminance system.
Definition: pixfmt.h:531
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:252
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:1650
planar YUV 4:2:0,18bpp, (1 Cr & Cb sample per 2x2 Y samples), little-endian
Definition: pixfmt.h:288
static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
Definition: libvpxenc.c:129
attribute_deprecated int mb_threshold
Definition: avcodec.h:2109
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:3043
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:371
int flags
VP8 specific flags, see VP8F_* below.
Definition: libvpxenc.c:79
static const AVCodecDefault defaults[]
Definition: libvpxenc.c:1015
#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:941
static const AVProfile profiles[]
AVS_Value src
Definition: avisynth_c.h:482
enum AVCodecID codec_id
Definition: avcodec.h:1529
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:1512
static int queue_frames(AVCodecContext *avctx, AVPacket *pkt_out)
Queue multiple output frames from the encoder, returning the front-most.
Definition: libvpxenc.c:756
int qmin
minimum quantizer
Definition: avcodec.h:2557
planar YUV 4:4:0,24bpp, (1 Cr & Cb sample per 1x2 Y samples), little-endian
Definition: pixfmt.h:325
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:2240
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:1804
static av_cold void free_coded_frame(struct FrameListData *cx_frame)
Definition: libvpxenc.c:212
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:2549
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:858
static enum AVPixelFormat pix_fmts[]
Definition: libkvazaar.c:245
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:253
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:2096
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:1717
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:3200
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:3202
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:67
planar YUV 4:2:2,24bpp, (1 Cr & Cb sample per 2x1 Y samples), little-endian
Definition: pixfmt.h:292
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:82
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:3199
AVProfile.
Definition: avcodec.h:3470
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:3034
int den
denominator
Definition: rational.h:45
static av_cold void free_frame_list(struct FrameListData *list)
Definition: libvpxenc.c:220
#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:2263
void * priv_data
Definition: avcodec.h:1554
#define av_free(p)
#define FF_PROFILE_VP9_2
Definition: avcodec.h:3201
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:83
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:1432
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:105
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:303
int rc_min_rate
minimum bitrate
Definition: avcodec.h:2621
AVPixelFormat
Pixel format.
Definition: pixfmt.h:65
This structure stores compressed data.
Definition: avcodec.h:1410
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:1426
Predicted.
Definition: avutil.h:267
int keyint_min
minimum GOP size
Definition: avcodec.h:2181
static int width