FFmpeg
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/9 encoder support via libvpx
24  */
25 
26 #include "config_components.h"
27 
28 #define VPX_DISABLE_CTRL_TYPECHECKS 1
29 #define VPX_CODEC_DISABLE_COMPAT 1
30 #include <vpx/vpx_encoder.h>
31 #include <vpx/vp8cx.h>
32 
33 #include "avcodec.h"
34 #include "codec_internal.h"
35 #include "encode.h"
36 #include "internal.h"
37 #include "libavutil/avassert.h"
38 #include "libvpx.h"
39 #include "packet_internal.h"
40 #include "profiles.h"
41 #include "libavutil/avstring.h"
42 #include "libavutil/base64.h"
43 #include "libavutil/common.h"
44 #include "libavutil/cpu.h"
45 #include "libavutil/fifo.h"
46 #include "libavutil/internal.h"
47 #include "libavutil/intreadwrite.h"
48 #include "libavutil/mathematics.h"
49 #include "libavutil/opt.h"
50 #include "libavutil/pixdesc.h"
51 
52 /**
53  * Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
54  * One encoded frame returned from the library.
55  */
56 struct FrameListData {
57  void *buf; /**< compressed data buffer */
58  size_t sz; /**< length of compressed data */
59  int64_t pts; /**< time stamp to show frame
60  (in timebase units) */
61  uint32_t flags; /**< flags for this frame */
62  uint64_t sse[4];
63  int have_sse; /**< true if we have pending sse[] */
64  struct FrameListData *next;
65 };
66 
67 typedef struct FrameData {
68  int64_t pts;
69  int64_t duration;
70 
71 #if FF_API_REORDERED_OPAQUE
72  int64_t reordered_opaque;
73 #endif
74  void *frame_opaque;
76 
78 } FrameData;
79 
80 typedef struct VPxEncoderContext {
81  AVClass *class;
82  struct vpx_codec_ctx encoder;
83  struct vpx_image rawimg;
84  struct vpx_codec_ctx encoder_alpha;
85  struct vpx_image rawimg_alpha;
86  uint8_t is_alpha;
87  struct vpx_fixed_buf twopass_stats;
89  int deadline; //i.e., RT/GOOD/BEST
90  uint64_t sse[4];
91  int have_sse; /**< true if we have pending sse[] */
94 
95  int cpu_used;
96  int sharpness;
97  /**
98  * VP8 specific flags, see VP8F_* below.
99  */
100  int flags;
101 #define VP8F_ERROR_RESILIENT 0x00000001 ///< Enable measures appropriate for streaming over lossy links
102 #define VP8F_AUTO_ALT_REF 0x00000002 ///< Enable automatic alternate reference frame generation
103 
105 
109 
110  int tune;
111 
114  int crf;
119 
123 
124  // VP9-only
125  int lossless;
129  int aq_mode;
132  int vpx_cs;
133  float level;
134  int row_mt;
139 
140  // This FIFO is used to propagate various properties from frames to packets.
142  /**
143  * If the driver does not support ROI then warn the first time we
144  * encounter a frame with ROI side data.
145  */
147 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_CTRL_VP9E_SET_MAX_INTER_BITRATE_PCT)
148  vpx_svc_ref_frame_config_t ref_frame_config;
149 #endif
150 } VPxContext;
151 
152 /** String mappings for enum vp8e_enc_control_id */
153 static const char *const ctlidstr[] = {
154  [VP8E_SET_CPUUSED] = "VP8E_SET_CPUUSED",
155  [VP8E_SET_ENABLEAUTOALTREF] = "VP8E_SET_ENABLEAUTOALTREF",
156  [VP8E_SET_NOISE_SENSITIVITY] = "VP8E_SET_NOISE_SENSITIVITY",
157  [VP8E_SET_STATIC_THRESHOLD] = "VP8E_SET_STATIC_THRESHOLD",
158  [VP8E_SET_TOKEN_PARTITIONS] = "VP8E_SET_TOKEN_PARTITIONS",
159  [VP8E_SET_ARNR_MAXFRAMES] = "VP8E_SET_ARNR_MAXFRAMES",
160  [VP8E_SET_ARNR_STRENGTH] = "VP8E_SET_ARNR_STRENGTH",
161  [VP8E_SET_ARNR_TYPE] = "VP8E_SET_ARNR_TYPE",
162  [VP8E_SET_TUNING] = "VP8E_SET_TUNING",
163  [VP8E_SET_CQ_LEVEL] = "VP8E_SET_CQ_LEVEL",
164  [VP8E_SET_MAX_INTRA_BITRATE_PCT] = "VP8E_SET_MAX_INTRA_BITRATE_PCT",
165  [VP8E_SET_SHARPNESS] = "VP8E_SET_SHARPNESS",
166  [VP8E_SET_TEMPORAL_LAYER_ID] = "VP8E_SET_TEMPORAL_LAYER_ID",
167 #if CONFIG_LIBVPX_VP9_ENCODER
168  [VP9E_SET_LOSSLESS] = "VP9E_SET_LOSSLESS",
169  [VP9E_SET_TILE_COLUMNS] = "VP9E_SET_TILE_COLUMNS",
170  [VP9E_SET_TILE_ROWS] = "VP9E_SET_TILE_ROWS",
171  [VP9E_SET_FRAME_PARALLEL_DECODING] = "VP9E_SET_FRAME_PARALLEL_DECODING",
172  [VP9E_SET_AQ_MODE] = "VP9E_SET_AQ_MODE",
173  [VP9E_SET_COLOR_SPACE] = "VP9E_SET_COLOR_SPACE",
174  [VP9E_SET_SVC_LAYER_ID] = "VP9E_SET_SVC_LAYER_ID",
175 #if VPX_ENCODER_ABI_VERSION >= 12
176  [VP9E_SET_SVC_PARAMETERS] = "VP9E_SET_SVC_PARAMETERS",
177  [VP9E_SET_SVC_REF_FRAME_CONFIG] = "VP9E_SET_SVC_REF_FRAME_CONFIG",
178 #endif
179  [VP9E_SET_SVC] = "VP9E_SET_SVC",
180 #if VPX_ENCODER_ABI_VERSION >= 11
181  [VP9E_SET_COLOR_RANGE] = "VP9E_SET_COLOR_RANGE",
182 #endif
183 #if VPX_ENCODER_ABI_VERSION >= 12
184  [VP9E_SET_TARGET_LEVEL] = "VP9E_SET_TARGET_LEVEL",
185  [VP9E_GET_LEVEL] = "VP9E_GET_LEVEL",
186 #endif
187 #ifdef VPX_CTRL_VP9E_SET_ROW_MT
188  [VP9E_SET_ROW_MT] = "VP9E_SET_ROW_MT",
189 #endif
190 #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
191  [VP9E_SET_TUNE_CONTENT] = "VP9E_SET_TUNE_CONTENT",
192 #endif
193 #ifdef VPX_CTRL_VP9E_SET_TPL
194  [VP9E_SET_TPL] = "VP9E_SET_TPL",
195 #endif
196 #ifdef VPX_CTRL_VP9E_SET_MIN_GF_INTERVAL
197  [VP9E_SET_MIN_GF_INTERVAL] = "VP9E_SET_MIN_GF_INTERVAL",
198 #endif
199 #endif
200 };
201 
202 static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
203 {
204  VPxContext *ctx = avctx->priv_data;
205  const char *error = vpx_codec_error(&ctx->encoder);
206  const char *detail = vpx_codec_error_detail(&ctx->encoder);
207 
208  av_log(avctx, AV_LOG_ERROR, "%s: %s\n", desc, error);
209  if (detail)
210  av_log(avctx, AV_LOG_ERROR, " Additional information: %s\n", detail);
211 }
212 
214  const struct vpx_codec_enc_cfg *cfg,
215  int level)
216 {
217  int width = -30;
218  int i;
219 
220  av_log(avctx, level, "vpx_codec_enc_cfg\n");
221  av_log(avctx, level, "generic settings\n"
222  " %*s%u\n %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
223 #if CONFIG_LIBVPX_VP9_ENCODER
224  " %*s%u\n %*s%u\n"
225 #endif
226  " %*s{%u/%u}\n %*s%u\n %*s%d\n %*s%u\n",
227  width, "g_usage:", cfg->g_usage,
228  width, "g_threads:", cfg->g_threads,
229  width, "g_profile:", cfg->g_profile,
230  width, "g_w:", cfg->g_w,
231  width, "g_h:", cfg->g_h,
232 #if CONFIG_LIBVPX_VP9_ENCODER
233  width, "g_bit_depth:", cfg->g_bit_depth,
234  width, "g_input_bit_depth:", cfg->g_input_bit_depth,
235 #endif
236  width, "g_timebase:", cfg->g_timebase.num, cfg->g_timebase.den,
237  width, "g_error_resilient:", cfg->g_error_resilient,
238  width, "g_pass:", cfg->g_pass,
239  width, "g_lag_in_frames:", cfg->g_lag_in_frames);
240  av_log(avctx, level, "rate control settings\n"
241  " %*s%u\n %*s%u\n %*s%u\n %*s%u\n"
242  " %*s%d\n %*s%p(%"SIZE_SPECIFIER")\n %*s%u\n",
243  width, "rc_dropframe_thresh:", cfg->rc_dropframe_thresh,
244  width, "rc_resize_allowed:", cfg->rc_resize_allowed,
245  width, "rc_resize_up_thresh:", cfg->rc_resize_up_thresh,
246  width, "rc_resize_down_thresh:", cfg->rc_resize_down_thresh,
247  width, "rc_end_usage:", cfg->rc_end_usage,
248  width, "rc_twopass_stats_in:", cfg->rc_twopass_stats_in.buf, cfg->rc_twopass_stats_in.sz,
249  width, "rc_target_bitrate:", cfg->rc_target_bitrate);
250  av_log(avctx, level, "quantizer settings\n"
251  " %*s%u\n %*s%u\n",
252  width, "rc_min_quantizer:", cfg->rc_min_quantizer,
253  width, "rc_max_quantizer:", cfg->rc_max_quantizer);
254  av_log(avctx, level, "bitrate tolerance\n"
255  " %*s%u\n %*s%u\n",
256  width, "rc_undershoot_pct:", cfg->rc_undershoot_pct,
257  width, "rc_overshoot_pct:", cfg->rc_overshoot_pct);
258  av_log(avctx, level, "temporal layering settings\n"
259  " %*s%u\n", width, "ts_number_layers:", cfg->ts_number_layers);
260  if (avctx->codec_id == AV_CODEC_ID_VP8) {
261  av_log(avctx, level,
262  "\n %*s", width, "ts_target_bitrate:");
263  for (i = 0; i < VPX_TS_MAX_LAYERS; i++)
264  av_log(avctx, level,
265  "%u ", cfg->ts_target_bitrate[i]);
266  }
267 #if (VPX_ENCODER_ABI_VERSION >= 12) && CONFIG_LIBVPX_VP9_ENCODER
268  if (avctx->codec_id == AV_CODEC_ID_VP9) {
269  av_log(avctx, level,
270  "\n %*s", width, "layer_target_bitrate:");
271  for (i = 0; i < VPX_TS_MAX_LAYERS; i++)
272  av_log(avctx, level,
273  "%u ", cfg->layer_target_bitrate[i]);
274  }
275 #endif
276  av_log(avctx, level, "\n");
277  av_log(avctx, level,
278  "\n %*s", width, "ts_rate_decimator:");
279  for (i = 0; i < VPX_TS_MAX_LAYERS; i++)
280  av_log(avctx, level, "%u ", cfg->ts_rate_decimator[i]);
281  av_log(avctx, level, "\n");
282  av_log(avctx, level,
283  "\n %*s%u\n", width, "ts_periodicity:", cfg->ts_periodicity);
284  av_log(avctx, level,
285  "\n %*s", width, "ts_layer_id:");
286  for (i = 0; i < VPX_TS_MAX_PERIODICITY; i++)
287  av_log(avctx, level, "%u ", cfg->ts_layer_id[i]);
288  av_log(avctx, level, "\n");
289  av_log(avctx, level, "decoder buffer model\n"
290  " %*s%u\n %*s%u\n %*s%u\n",
291  width, "rc_buf_sz:", cfg->rc_buf_sz,
292  width, "rc_buf_initial_sz:", cfg->rc_buf_initial_sz,
293  width, "rc_buf_optimal_sz:", cfg->rc_buf_optimal_sz);
294  av_log(avctx, level, "2 pass rate control settings\n"
295  " %*s%u\n %*s%u\n %*s%u\n",
296  width, "rc_2pass_vbr_bias_pct:", cfg->rc_2pass_vbr_bias_pct,
297  width, "rc_2pass_vbr_minsection_pct:", cfg->rc_2pass_vbr_minsection_pct,
298  width, "rc_2pass_vbr_maxsection_pct:", cfg->rc_2pass_vbr_maxsection_pct);
299 #if VPX_ENCODER_ABI_VERSION >= 14
300  av_log(avctx, level, " %*s%u\n",
301  width, "rc_2pass_vbr_corpus_complexity:", cfg->rc_2pass_vbr_corpus_complexity);
302 #endif
303  av_log(avctx, level, "keyframing settings\n"
304  " %*s%d\n %*s%u\n %*s%u\n",
305  width, "kf_mode:", cfg->kf_mode,
306  width, "kf_min_dist:", cfg->kf_min_dist,
307  width, "kf_max_dist:", cfg->kf_max_dist);
308  av_log(avctx, level, "\n");
309 }
310 
311 static void coded_frame_add(void *list, struct FrameListData *cx_frame)
312 {
313  struct FrameListData **p = list;
314 
315  while (*p)
316  p = &(*p)->next;
317  *p = cx_frame;
318  cx_frame->next = NULL;
319 }
320 
321 static av_cold void free_coded_frame(struct FrameListData *cx_frame)
322 {
323  av_freep(&cx_frame->buf);
324  av_freep(&cx_frame);
325 }
326 
328 {
329  struct FrameListData *p = list;
330 
331  while (p) {
332  list = list->next;
333  free_coded_frame(p);
334  p = list;
335  }
336 }
337 
338 static void frame_data_uninit(FrameData *fd)
339 {
342 }
343 
344 static av_cold void fifo_free(AVFifo **fifo)
345 {
346  FrameData fd;
347  while (av_fifo_read(*fifo, &fd, 1) >= 0)
348  frame_data_uninit(&fd);
349  av_fifo_freep2(fifo);
350 }
351 
352 static int frame_data_submit(AVCodecContext *avctx, AVFifo *fifo,
353  const AVFrame *frame)
354 {
355  VPxContext *ctx = avctx->priv_data;
356  const struct vpx_codec_enc_cfg *enccfg = ctx->encoder.config.enc;
357 
358  FrameData fd = { .pts = frame->pts };
359 
361  int ret;
362 
363 #if CONFIG_LIBVPX_VP9_ENCODER
364  // Keep HDR10+ if it has bit depth higher than 8 and
365  // it has PQ trc (SMPTE2084).
367  if (avctx->codec_id == AV_CODEC_ID_VP9 && sd &&
368  enccfg->g_bit_depth > 8 && avctx->color_trc == AVCOL_TRC_SMPTE2084) {
369  fd.hdr10_plus = av_buffer_ref(sd->buf);
370  if (!fd.hdr10_plus)
371  return AVERROR(ENOMEM);
372  }
373 #endif
374 
375  fd.duration = frame->duration;
376  fd.frame_opaque = frame->opaque;
377  if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE && frame->opaque_ref) {
379  if (ret < 0)
380  goto fail;
381  }
382 #if FF_API_REORDERED_OPAQUE
384  fd.reordered_opaque = frame->reordered_opaque;
386 #endif
387 
388  ret = av_fifo_write(fifo, &fd, 1);
389  if (ret < 0)
390  goto fail;
391 
392  return 0;
393 fail:
394  frame_data_uninit(&fd);
395  return ret;
396 }
397 
398 static int frame_data_apply(AVCodecContext *avctx, AVFifo *fifo, AVPacket *pkt)
399 {
400  FrameData fd;
401  uint8_t *data;
402  int ret = 0;
403 
404  if (av_fifo_peek(fifo, &fd, 1, 0) < 0)
405  return 0;
406  if (fd.pts != pkt->pts) {
407  av_log(avctx, AV_LOG_WARNING,
408  "Mismatching timestamps: libvpx %"PRId64" queued %"PRId64"; "
409  "this is a bug, please report it\n", pkt->pts, fd.pts);
410  goto skip;
411  }
412 
413 #if FF_API_REORDERED_OPAQUE
415  avctx->reordered_opaque = fd.reordered_opaque;
417 #endif
418 
419  pkt->duration = fd.duration;
420  if (avctx->flags & AV_CODEC_FLAG_COPY_OPAQUE) {
421  pkt->opaque = fd.frame_opaque;
423  fd.frame_opaque_ref = NULL;
424  }
425 
426  if (fd.hdr10_plus) {
428  if (!data) {
429  ret = AVERROR(ENOMEM);
430  goto skip;
431  }
432 
433  memcpy(data, fd.hdr10_plus->data, fd.hdr10_plus->size);
434  }
435 
436 skip:
437  av_fifo_drain2(fifo, 1);
438  frame_data_uninit(&fd);
439 
440  return ret;
441 }
442 
444  enum vp8e_enc_control_id id, int val)
445 {
446  VPxContext *ctx = avctx->priv_data;
447  char buf[80];
448  int width = -30;
449  int res;
450 
451  snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
452  av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, val);
453 
454  res = vpx_codec_control(&ctx->encoder, id, val);
455  if (res != VPX_CODEC_OK) {
456  snprintf(buf, sizeof(buf), "Failed to set %s codec control",
457  ctlidstr[id]);
458  log_encoder_error(avctx, buf);
459  return AVERROR(EINVAL);
460  }
461 
462  if (ctx->is_alpha) {
463  int res_alpha = vpx_codec_control(&ctx->encoder_alpha, id, val);
464  if (res_alpha != VPX_CODEC_OK) {
465  snprintf(buf, sizeof(buf), "Failed to set %s alpha codec control",
466  ctlidstr[id]);
467  log_encoder_error(avctx, buf);
468  return AVERROR(EINVAL);
469  }
470  }
471 
472  return 0;
473 }
474 
475 #if VPX_ENCODER_ABI_VERSION >= 12
476 static av_cold int codecctl_intp(AVCodecContext *avctx,
477  enum vp8e_enc_control_id id, int *val)
478 {
479  VPxContext *ctx = avctx->priv_data;
480  char buf[80];
481  int width = -30;
482  int res;
483 
484  snprintf(buf, sizeof(buf), "%s:", ctlidstr[id]);
485  av_log(avctx, AV_LOG_DEBUG, " %*s%d\n", width, buf, *val);
486 
487  res = vpx_codec_control(&ctx->encoder, id, val);
488  if (res != VPX_CODEC_OK) {
489  snprintf(buf, sizeof(buf), "Failed to set %s codec control",
490  ctlidstr[id]);
491  log_encoder_error(avctx, buf);
492  return AVERROR(EINVAL);
493  }
494 
495  if (ctx->is_alpha) {
496  int res_alpha = vpx_codec_control(&ctx->encoder_alpha, id, val);
497  if (res_alpha != VPX_CODEC_OK) {
498  snprintf(buf, sizeof(buf), "Failed to set %s alpha codec control",
499  ctlidstr[id]);
500  log_encoder_error(avctx, buf);
501  return AVERROR(EINVAL);
502  }
503  }
504 
505  return 0;
506 }
507 #endif
508 
509 static av_cold int vpx_free(AVCodecContext *avctx)
510 {
511  VPxContext *ctx = avctx->priv_data;
512 
513 #if VPX_ENCODER_ABI_VERSION >= 12
514  if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->level >= 0 &&
515  !(avctx->flags & AV_CODEC_FLAG_PASS1)) {
516  int level_out = 0;
517  if (!codecctl_intp(avctx, VP9E_GET_LEVEL, &level_out))
518  av_log(avctx, AV_LOG_INFO, "Encoded level %.1f\n", level_out * 0.1);
519  }
520 #endif
521 
522  av_freep(&ctx->ts_layer_flags);
523 
524  vpx_codec_destroy(&ctx->encoder);
525  if (ctx->is_alpha) {
526  vpx_codec_destroy(&ctx->encoder_alpha);
527  av_freep(&ctx->rawimg_alpha.planes[VPX_PLANE_U]);
528  av_freep(&ctx->rawimg_alpha.planes[VPX_PLANE_V]);
529  }
530  av_freep(&ctx->twopass_stats.buf);
531  av_freep(&avctx->stats_out);
532  free_frame_list(ctx->coded_frame_list);
533  free_frame_list(ctx->alpha_coded_frame_list);
534  if (ctx->fifo)
535  fifo_free(&ctx->fifo);
536  return 0;
537 }
538 
539 static void vp8_ts_parse_int_array(int *dest, char *value, size_t value_len, int max_entries)
540 {
541  int dest_idx = 0;
542  char *saveptr = NULL;
543  char *token = av_strtok(value, ",", &saveptr);
544 
545  while (token && dest_idx < max_entries) {
546  dest[dest_idx++] = strtoul(token, NULL, 10);
547  token = av_strtok(NULL, ",", &saveptr);
548  }
549 }
550 
551 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_CTRL_VP9E_SET_MAX_INTER_BITRATE_PCT)
552 static void vp8_ts_parse_int64_array(int64_t *dest, char *value, size_t value_len, int max_entries)
553 {
554  int dest_idx = 0;
555  char *saveptr = NULL;
556  char *token = av_strtok(value, ",", &saveptr);
557 
558  while (token && dest_idx < max_entries) {
559  dest[dest_idx++] = strtoull(token, NULL, 10);
560  token = av_strtok(NULL, ",", &saveptr);
561  }
562 }
563 #endif
564 
565 static void set_temporal_layer_pattern(int layering_mode, vpx_codec_enc_cfg_t *cfg,
566  int *layer_flags, int *flag_periodicity)
567 {
568  switch (layering_mode) {
569  case 2: {
570  /**
571  * 2-layers, 2-frame period.
572  */
573  static const int ids[2] = { 0, 1 };
574  cfg->ts_periodicity = 2;
575  *flag_periodicity = 2;
576  cfg->ts_number_layers = 2;
577  cfg->ts_rate_decimator[0] = 2;
578  cfg->ts_rate_decimator[1] = 1;
579  memcpy(cfg->ts_layer_id, ids, sizeof(ids));
580 
581  layer_flags[0] =
582  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
583  VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
584  layer_flags[1] =
585  VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_GF |
586  VP8_EFLAG_NO_UPD_LAST |
587  VP8_EFLAG_NO_REF_ARF | VP8_EFLAG_NO_REF_GF;
588  break;
589  }
590  case 3: {
591  /**
592  * 3-layers structure with one reference frame.
593  * This works same as temporal_layering_mode 3.
594  *
595  * 3-layers, 4-frame period.
596  */
597  static const int ids[4] = { 0, 2, 1, 2 };
598  cfg->ts_periodicity = 4;
599  *flag_periodicity = 4;
600  cfg->ts_number_layers = 3;
601  cfg->ts_rate_decimator[0] = 4;
602  cfg->ts_rate_decimator[1] = 2;
603  cfg->ts_rate_decimator[2] = 1;
604  memcpy(cfg->ts_layer_id, ids, sizeof(ids));
605 
606  /**
607  * 0=L, 1=GF, 2=ARF,
608  * Intra-layer prediction disabled.
609  */
610  layer_flags[0] =
611  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
612  VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
613  layer_flags[1] =
614  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
615  VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
616  VP8_EFLAG_NO_UPD_ARF;
617  layer_flags[2] =
618  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
619  VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_LAST;
620  layer_flags[3] =
621  VP8_EFLAG_NO_REF_LAST | VP8_EFLAG_NO_REF_ARF |
622  VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
623  VP8_EFLAG_NO_UPD_ARF;
624  break;
625  }
626  case 4: {
627  /**
628  * 3-layers structure.
629  * added dependency between the two TL2 frames (on top of case 3).
630  * 3-layers, 4-frame period.
631  */
632  static const int ids[4] = { 0, 2, 1, 2 };
633  cfg->ts_periodicity = 4;
634  *flag_periodicity = 4;
635  cfg->ts_number_layers = 3;
636  cfg->ts_rate_decimator[0] = 4;
637  cfg->ts_rate_decimator[1] = 2;
638  cfg->ts_rate_decimator[2] = 1;
639  memcpy(cfg->ts_layer_id, ids, sizeof(ids));
640 
641  /**
642  * 0=L, 1=GF, 2=ARF, Intra-layer prediction disabled.
643  */
644  layer_flags[0] =
645  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
646  VP8_EFLAG_NO_UPD_GF | VP8_EFLAG_NO_UPD_ARF;
647  layer_flags[1] =
648  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
649  VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF;
650  layer_flags[2] =
651  VP8_EFLAG_NO_REF_GF | VP8_EFLAG_NO_REF_ARF |
652  VP8_EFLAG_NO_UPD_ARF | VP8_EFLAG_NO_UPD_LAST;
653  layer_flags[3] =
654  VP8_EFLAG_NO_REF_LAST |
655  VP8_EFLAG_NO_UPD_LAST | VP8_EFLAG_NO_UPD_GF |
656  VP8_EFLAG_NO_UPD_ARF;
657  break;
658  }
659  default:
660  /**
661  * do not change the layer_flags or the flag_periodicity in this case;
662  * it might be that the code is using external flags to be used.
663  */
664  break;
665 
666  }
667 }
668 
669 static int vpx_ts_param_parse(VPxContext *ctx, struct vpx_codec_enc_cfg *enccfg,
670  char *key, char *value, enum AVCodecID codec_id)
671 {
672  size_t value_len = strlen(value);
673  int ts_layering_mode = 0;
674 
675  if (!value_len)
676  return -1;
677 
678  if (!strcmp(key, "ts_number_layers"))
679  enccfg->ts_number_layers = strtoul(value, &value, 10);
680  else if (!strcmp(key, "ts_target_bitrate")) {
681  if (codec_id == AV_CODEC_ID_VP8)
682  vp8_ts_parse_int_array(enccfg->ts_target_bitrate, value, value_len, VPX_TS_MAX_LAYERS);
683 #if (VPX_ENCODER_ABI_VERSION >= 12) && CONFIG_LIBVPX_VP9_ENCODER
684  if (codec_id == AV_CODEC_ID_VP9)
685  vp8_ts_parse_int_array(enccfg->layer_target_bitrate, value, value_len, VPX_TS_MAX_LAYERS);
686 #endif
687  } else if (!strcmp(key, "ts_rate_decimator")) {
688  vp8_ts_parse_int_array(enccfg->ts_rate_decimator, value, value_len, VPX_TS_MAX_LAYERS);
689  } else if (!strcmp(key, "ts_periodicity")) {
690  enccfg->ts_periodicity = strtoul(value, &value, 10);
691  } else if (!strcmp(key, "ts_layer_id")) {
692  vp8_ts_parse_int_array(enccfg->ts_layer_id, value, value_len, VPX_TS_MAX_PERIODICITY);
693  } else if (!strcmp(key, "ts_layering_mode")) {
694  /* option for pre-defined temporal structures in function set_temporal_layer_pattern. */
695  ts_layering_mode = strtoul(value, &value, 4);
696  }
697 
698 #if (VPX_ENCODER_ABI_VERSION >= 12) && CONFIG_LIBVPX_VP9_ENCODER
699  enccfg->temporal_layering_mode = VP9E_TEMPORAL_LAYERING_MODE_BYPASS; // only bypass mode is supported for now.
700  enccfg->ss_number_layers = 1; // TODO: add spatial scalability support.
701 #endif
702  if (ts_layering_mode) {
703  // make sure the ts_layering_mode comes at the end of the ts_parameter string to ensure that
704  // correct configuration is done.
705  ctx->ts_layer_flags = av_malloc_array(VPX_TS_MAX_PERIODICITY, sizeof(*ctx->ts_layer_flags));
706  set_temporal_layer_pattern(ts_layering_mode, enccfg, ctx->ts_layer_flags, &enccfg->ts_periodicity);
707  }
708 
709  return 0;
710 }
711 
712 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_CTRL_VP9E_SET_MAX_INTER_BITRATE_PCT)
713 static int vpx_ref_frame_config_set_value(vpx_svc_ref_frame_config_t *ref_frame_config,
714  int ss_number_layers, char *key, char *value)
715 {
716  size_t value_len = strlen(value);
717 
718  if (!value_len)
719  return AVERROR(EINVAL);
720 
721  if (!strcmp(key, "rfc_update_buffer_slot")) {
722  vp8_ts_parse_int_array(ref_frame_config->update_buffer_slot, value, value_len, ss_number_layers);
723  } else if (!strcmp(key, "rfc_update_last")) {
724  vp8_ts_parse_int_array(ref_frame_config->update_last, value, value_len, ss_number_layers);
725  } else if (!strcmp(key, "rfc_update_golden")) {
726  vp8_ts_parse_int_array(ref_frame_config->update_golden, value, value_len, ss_number_layers);
727  } else if (!strcmp(key, "rfc_update_alt_ref")) {
728  vp8_ts_parse_int_array(ref_frame_config->update_alt_ref, value, value_len, ss_number_layers);
729  } else if (!strcmp(key, "rfc_lst_fb_idx")) {
730  vp8_ts_parse_int_array(ref_frame_config->lst_fb_idx, value, value_len, ss_number_layers);
731  } else if (!strcmp(key, "rfc_gld_fb_idx")) {
732  vp8_ts_parse_int_array(ref_frame_config->gld_fb_idx, value, value_len, ss_number_layers);
733  } else if (!strcmp(key, "rfc_alt_fb_idx")) {
734  vp8_ts_parse_int_array(ref_frame_config->alt_fb_idx, value, value_len, ss_number_layers);
735  } else if (!strcmp(key, "rfc_reference_last")) {
736  vp8_ts_parse_int_array(ref_frame_config->reference_last, value, value_len, ss_number_layers);
737  } else if (!strcmp(key, "rfc_reference_golden")) {
738  vp8_ts_parse_int_array(ref_frame_config->reference_golden, value, value_len, ss_number_layers);
739  } else if (!strcmp(key, "rfc_reference_alt_ref")) {
740  vp8_ts_parse_int_array(ref_frame_config->reference_alt_ref, value, value_len, ss_number_layers);
741  } else if (!strcmp(key, "rfc_reference_duration")) {
742  vp8_ts_parse_int64_array(ref_frame_config->duration, value, value_len, ss_number_layers);
743  }
744 
745  return 0;
746 }
747 
748 static int vpx_parse_ref_frame_config_element(vpx_svc_ref_frame_config_t *ref_frame_config,
749  int ss_number_layers, const char **buf)
750 {
751  const char key_val_sep[] = "=";
752  const char pairs_sep[] = ":";
753  char *key = av_get_token(buf, key_val_sep);
754  char *val = NULL;
755  int ret;
756 
757  if (key && *key && strspn(*buf, key_val_sep)) {
758  (*buf)++;
759  val = av_get_token(buf, pairs_sep);
760  }
761 
762  if (key && *key && val && *val)
763  ret = vpx_ref_frame_config_set_value(ref_frame_config, ss_number_layers, key, val);
764  else
765  ret = AVERROR(EINVAL);
766 
767  av_freep(&key);
768  av_freep(&val);
769 
770  return ret;
771 }
772 
773 static int vpx_parse_ref_frame_config(vpx_svc_ref_frame_config_t *ref_frame_config,
774  int ss_number_layers, const char *str)
775 {
776  int ret = 0;
777 
778  while (*str) {
779  ret =
780  vpx_parse_ref_frame_config_element(ref_frame_config, ss_number_layers, &str);
781  if (ret < 0)
782  return ret;
783 
784  if (*str)
785  str++;
786  }
787 
788  return ret;
789 }
790 #endif
791 
792 #if CONFIG_LIBVPX_VP9_ENCODER
793 static int set_pix_fmt(AVCodecContext *avctx, vpx_codec_caps_t codec_caps,
794  struct vpx_codec_enc_cfg *enccfg, vpx_codec_flags_t *flags,
795  vpx_img_fmt_t *img_fmt)
796 {
797  VPxContext av_unused *ctx = avctx->priv_data;
799  enccfg->g_bit_depth = enccfg->g_input_bit_depth = desc->comp[0].depth;
800  switch (avctx->pix_fmt) {
801  case AV_PIX_FMT_YUV420P:
802  case AV_PIX_FMT_YUVA420P:
803  enccfg->g_profile = 0;
804  *img_fmt = VPX_IMG_FMT_I420;
805  return 0;
806  case AV_PIX_FMT_YUV422P:
807  enccfg->g_profile = 1;
808  *img_fmt = VPX_IMG_FMT_I422;
809  return 0;
810  case AV_PIX_FMT_YUV440P:
811  enccfg->g_profile = 1;
812  *img_fmt = VPX_IMG_FMT_I440;
813  return 0;
814  case AV_PIX_FMT_GBRP:
815  ctx->vpx_cs = VPX_CS_SRGB;
816  case AV_PIX_FMT_YUV444P:
817  enccfg->g_profile = 1;
818  *img_fmt = VPX_IMG_FMT_I444;
819  return 0;
822  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
823  enccfg->g_profile = 2;
824  *img_fmt = VPX_IMG_FMT_I42016;
825  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
826  return 0;
827  }
828  break;
831  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
832  enccfg->g_profile = 3;
833  *img_fmt = VPX_IMG_FMT_I42216;
834  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
835  return 0;
836  }
837  break;
840  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
841  enccfg->g_profile = 3;
842  *img_fmt = VPX_IMG_FMT_I44016;
843  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
844  return 0;
845  }
846  break;
847  case AV_PIX_FMT_GBRP10:
848  case AV_PIX_FMT_GBRP12:
849  ctx->vpx_cs = VPX_CS_SRGB;
852  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH) {
853  enccfg->g_profile = 3;
854  *img_fmt = VPX_IMG_FMT_I44416;
855  *flags |= VPX_CODEC_USE_HIGHBITDEPTH;
856  return 0;
857  }
858  break;
859  default:
860  break;
861  }
862  av_log(avctx, AV_LOG_ERROR, "Unsupported pixel format.\n");
863  return AVERROR_INVALIDDATA;
864 }
865 
866 static void set_colorspace(AVCodecContext *avctx)
867 {
868  enum vpx_color_space vpx_cs;
869  VPxContext *ctx = avctx->priv_data;
870 
871  if (ctx->vpx_cs) {
872  vpx_cs = ctx->vpx_cs;
873  } else {
874  switch (avctx->colorspace) {
875  case AVCOL_SPC_RGB: vpx_cs = VPX_CS_SRGB; break;
876  case AVCOL_SPC_BT709: vpx_cs = VPX_CS_BT_709; break;
877  case AVCOL_SPC_UNSPECIFIED: vpx_cs = VPX_CS_UNKNOWN; break;
878  case AVCOL_SPC_RESERVED: vpx_cs = VPX_CS_RESERVED; break;
879  case AVCOL_SPC_BT470BG: vpx_cs = VPX_CS_BT_601; break;
880  case AVCOL_SPC_SMPTE170M: vpx_cs = VPX_CS_SMPTE_170; break;
881  case AVCOL_SPC_SMPTE240M: vpx_cs = VPX_CS_SMPTE_240; break;
882  case AVCOL_SPC_BT2020_NCL: vpx_cs = VPX_CS_BT_2020; break;
883  default:
884  av_log(avctx, AV_LOG_WARNING, "Unsupported colorspace (%d)\n",
885  avctx->colorspace);
886  return;
887  }
888  }
889  codecctl_int(avctx, VP9E_SET_COLOR_SPACE, vpx_cs);
890 }
891 
892 #if VPX_ENCODER_ABI_VERSION >= 11
893 static void set_color_range(AVCodecContext *avctx)
894 {
895  enum vpx_color_range vpx_cr;
896  switch (avctx->color_range) {
898  case AVCOL_RANGE_MPEG: vpx_cr = VPX_CR_STUDIO_RANGE; break;
899  case AVCOL_RANGE_JPEG: vpx_cr = VPX_CR_FULL_RANGE; break;
900  default:
901  av_log(avctx, AV_LOG_WARNING, "Unsupported color range (%d)\n",
902  avctx->color_range);
903  return;
904  }
905 
906  codecctl_int(avctx, VP9E_SET_COLOR_RANGE, vpx_cr);
907 }
908 #endif
909 #endif
910 
911 /**
912  * Set the target bitrate to VPX library default. Also set CRF to 32 if needed.
913  */
914 static void set_vp8_defaults(AVCodecContext *avctx,
915  struct vpx_codec_enc_cfg *enccfg)
916 {
917  VPxContext *ctx = avctx->priv_data;
918  av_assert0(!avctx->bit_rate);
919  avctx->bit_rate = enccfg->rc_target_bitrate * 1000;
920  if (enccfg->rc_end_usage == VPX_CQ) {
921  av_log(avctx, AV_LOG_WARNING,
922  "Bitrate not specified for constrained quality mode, using default of %dkbit/sec\n",
923  enccfg->rc_target_bitrate);
924  } else {
925  enccfg->rc_end_usage = VPX_CQ;
926  ctx->crf = 32;
927  av_log(avctx, AV_LOG_WARNING,
928  "Neither bitrate nor constrained quality specified, using default CRF of %d and bitrate of %dkbit/sec\n",
929  ctx->crf, enccfg->rc_target_bitrate);
930  }
931 }
932 
933 
934 #if CONFIG_LIBVPX_VP9_ENCODER
935 /**
936  * Keep the target bitrate at 0 to engage constant quality mode. If CRF is not
937  * set, use 32.
938  */
939 static void set_vp9_defaults(AVCodecContext *avctx,
940  struct vpx_codec_enc_cfg *enccfg)
941 {
942  VPxContext *ctx = avctx->priv_data;
943  av_assert0(!avctx->bit_rate);
944  if (enccfg->rc_end_usage != VPX_Q && ctx->lossless < 0) {
945  enccfg->rc_end_usage = VPX_Q;
946  ctx->crf = 32;
947  av_log(avctx, AV_LOG_WARNING,
948  "Neither bitrate nor constrained quality specified, using default CRF of %d\n",
949  ctx->crf);
950  }
951 }
952 #endif
953 
954 /**
955  * Called when the bitrate is not set. It sets appropriate default values for
956  * bitrate and CRF.
957  */
958 static void set_vpx_defaults(AVCodecContext *avctx,
959  struct vpx_codec_enc_cfg *enccfg)
960 {
961  av_assert0(!avctx->bit_rate);
962 #if CONFIG_LIBVPX_VP9_ENCODER
963  if (avctx->codec_id == AV_CODEC_ID_VP9) {
964  set_vp9_defaults(avctx, enccfg);
965  return;
966  }
967 #endif
968  set_vp8_defaults(avctx, enccfg);
969 }
970 
971 static av_cold int vpx_init(AVCodecContext *avctx,
972  const struct vpx_codec_iface *iface)
973 {
974  VPxContext *ctx = avctx->priv_data;
975  struct vpx_codec_enc_cfg enccfg = { 0 };
976  struct vpx_codec_enc_cfg enccfg_alpha;
977  vpx_codec_flags_t flags = (avctx->flags & AV_CODEC_FLAG_PSNR) ? VPX_CODEC_USE_PSNR : 0;
978  AVCPBProperties *cpb_props;
979  int res;
980  vpx_img_fmt_t img_fmt = VPX_IMG_FMT_I420;
981 #if CONFIG_LIBVPX_VP9_ENCODER
982  vpx_codec_caps_t codec_caps = vpx_codec_get_caps(iface);
983  vpx_svc_extra_cfg_t svc_params;
984 #endif
985  const AVDictionaryEntry* en = NULL;
986 
987  av_log(avctx, AV_LOG_INFO, "%s\n", vpx_codec_version_str());
988  av_log(avctx, AV_LOG_VERBOSE, "%s\n", vpx_codec_build_config());
989 
990  if (avctx->pix_fmt == AV_PIX_FMT_YUVA420P)
991  ctx->is_alpha = 1;
992 
993  if ((res = vpx_codec_enc_config_default(iface, &enccfg, 0)) != VPX_CODEC_OK) {
994  av_log(avctx, AV_LOG_ERROR, "Failed to get config: %s\n",
995  vpx_codec_err_to_string(res));
996  return AVERROR(EINVAL);
997  }
998 
999  ctx->fifo = av_fifo_alloc2(1, sizeof(FrameData), AV_FIFO_FLAG_AUTO_GROW);
1000  if (!ctx->fifo)
1001  return AVERROR(ENOMEM);
1002 
1003 #if CONFIG_LIBVPX_VP9_ENCODER
1004  if (avctx->codec_id == AV_CODEC_ID_VP9) {
1005  if (set_pix_fmt(avctx, codec_caps, &enccfg, &flags, &img_fmt))
1006  return AVERROR(EINVAL);
1007  }
1008 #endif
1009 
1010  if(!avctx->bit_rate)
1011  if(avctx->rc_max_rate || avctx->rc_buffer_size || avctx->rc_initial_buffer_occupancy) {
1012  av_log( avctx, AV_LOG_ERROR, "Rate control parameters set without a bitrate\n");
1013  return AVERROR(EINVAL);
1014  }
1015 
1016  dump_enc_cfg(avctx, &enccfg, AV_LOG_DEBUG);
1017 
1018  enccfg.g_w = avctx->width;
1019  enccfg.g_h = avctx->height;
1020  enccfg.g_timebase.num = avctx->time_base.num;
1021  enccfg.g_timebase.den = avctx->time_base.den;
1022  enccfg.g_threads =
1024  enccfg.g_lag_in_frames= ctx->lag_in_frames;
1025 
1026  if (avctx->flags & AV_CODEC_FLAG_PASS1)
1027  enccfg.g_pass = VPX_RC_FIRST_PASS;
1028  else if (avctx->flags & AV_CODEC_FLAG_PASS2)
1029  enccfg.g_pass = VPX_RC_LAST_PASS;
1030  else
1031  enccfg.g_pass = VPX_RC_ONE_PASS;
1032 
1033  if (avctx->rc_min_rate == avctx->rc_max_rate &&
1034  avctx->rc_min_rate == avctx->bit_rate && avctx->bit_rate) {
1035  enccfg.rc_end_usage = VPX_CBR;
1036  } else if (ctx->crf >= 0) {
1037  enccfg.rc_end_usage = VPX_CQ;
1038 #if CONFIG_LIBVPX_VP9_ENCODER
1039  if (!avctx->bit_rate && avctx->codec_id == AV_CODEC_ID_VP9)
1040  enccfg.rc_end_usage = VPX_Q;
1041 #endif
1042  }
1043 
1044  if (avctx->bit_rate) {
1045  enccfg.rc_target_bitrate = av_rescale_rnd(avctx->bit_rate, 1, 1000,
1047 #if CONFIG_LIBVPX_VP9_ENCODER
1048  enccfg.ss_target_bitrate[0] = enccfg.rc_target_bitrate;
1049 #endif
1050  } else {
1051  // Set bitrate to default value. Also sets CRF to default if needed.
1052  set_vpx_defaults(avctx, &enccfg);
1053  }
1054 
1055  if (avctx->codec_id == AV_CODEC_ID_VP9 && ctx->lossless == 1) {
1056  enccfg.rc_min_quantizer =
1057  enccfg.rc_max_quantizer = 0;
1058  } else {
1059  if (avctx->qmin >= 0)
1060  enccfg.rc_min_quantizer = avctx->qmin;
1061  if (avctx->qmax >= 0)
1062  enccfg.rc_max_quantizer = avctx->qmax;
1063  }
1064 
1065  if (enccfg.rc_end_usage == VPX_CQ
1066 #if CONFIG_LIBVPX_VP9_ENCODER
1067  || enccfg.rc_end_usage == VPX_Q
1068 #endif
1069  ) {
1070  if (ctx->crf < enccfg.rc_min_quantizer || ctx->crf > enccfg.rc_max_quantizer) {
1071  av_log(avctx, AV_LOG_ERROR,
1072  "CQ level %d must be between minimum and maximum quantizer value (%d-%d)\n",
1073  ctx->crf, enccfg.rc_min_quantizer, enccfg.rc_max_quantizer);
1074  return AVERROR(EINVAL);
1075  }
1076  }
1077 
1078  enccfg.rc_dropframe_thresh = ctx->drop_threshold;
1079 
1080  //0-100 (0 => CBR, 100 => VBR)
1081  enccfg.rc_2pass_vbr_bias_pct = lrint(avctx->qcompress * 100);
1082  if (avctx->bit_rate)
1083  enccfg.rc_2pass_vbr_minsection_pct =
1084  avctx->rc_min_rate * 100LL / avctx->bit_rate;
1085  if (avctx->rc_max_rate)
1086  enccfg.rc_2pass_vbr_maxsection_pct =
1087  avctx->rc_max_rate * 100LL / avctx->bit_rate;
1088 #if CONFIG_LIBVPX_VP9_ENCODER
1089  if (avctx->codec_id == AV_CODEC_ID_VP9) {
1090 #if VPX_ENCODER_ABI_VERSION >= 14
1091  if (ctx->corpus_complexity >= 0)
1092  enccfg.rc_2pass_vbr_corpus_complexity = ctx->corpus_complexity;
1093 #endif
1094  }
1095 #endif
1096 
1097  if (avctx->rc_buffer_size)
1098  enccfg.rc_buf_sz =
1099  avctx->rc_buffer_size * 1000LL / avctx->bit_rate;
1100  if (avctx->rc_initial_buffer_occupancy)
1101  enccfg.rc_buf_initial_sz =
1102  avctx->rc_initial_buffer_occupancy * 1000LL / avctx->bit_rate;
1103  enccfg.rc_buf_optimal_sz = enccfg.rc_buf_sz * 5 / 6;
1104  if (ctx->rc_undershoot_pct >= 0)
1105  enccfg.rc_undershoot_pct = ctx->rc_undershoot_pct;
1106  if (ctx->rc_overshoot_pct >= 0)
1107  enccfg.rc_overshoot_pct = ctx->rc_overshoot_pct;
1108 
1109  //_enc_init() will balk if kf_min_dist differs from max w/VPX_KF_AUTO
1110  if (avctx->keyint_min >= 0 && avctx->keyint_min == avctx->gop_size)
1111  enccfg.kf_min_dist = avctx->keyint_min;
1112  if (avctx->gop_size >= 0)
1113  enccfg.kf_max_dist = avctx->gop_size;
1114 
1115  if (enccfg.g_pass == VPX_RC_FIRST_PASS)
1116  enccfg.g_lag_in_frames = 0;
1117  else if (enccfg.g_pass == VPX_RC_LAST_PASS) {
1118  int decode_size, ret;
1119 
1120  if (!avctx->stats_in) {
1121  av_log(avctx, AV_LOG_ERROR, "No stats file for second pass\n");
1122  return AVERROR_INVALIDDATA;
1123  }
1124 
1125  ctx->twopass_stats.sz = strlen(avctx->stats_in) * 3 / 4;
1126  ret = av_reallocp(&ctx->twopass_stats.buf, ctx->twopass_stats.sz);
1127  if (ret < 0) {
1128  av_log(avctx, AV_LOG_ERROR,
1129  "Stat buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
1130  ctx->twopass_stats.sz);
1131  ctx->twopass_stats.sz = 0;
1132  return ret;
1133  }
1134  decode_size = av_base64_decode(ctx->twopass_stats.buf, avctx->stats_in,
1135  ctx->twopass_stats.sz);
1136  if (decode_size < 0) {
1137  av_log(avctx, AV_LOG_ERROR, "Stat buffer decode failed\n");
1138  return AVERROR_INVALIDDATA;
1139  }
1140 
1141  ctx->twopass_stats.sz = decode_size;
1142  enccfg.rc_twopass_stats_in = ctx->twopass_stats;
1143  }
1144 
1145  /* 0-3: For non-zero values the encoder increasingly optimizes for reduced
1146  complexity playback on low powered devices at the expense of encode
1147  quality. */
1148  if (avctx->profile != AV_PROFILE_UNKNOWN)
1149  enccfg.g_profile = avctx->profile;
1150 
1151  enccfg.g_error_resilient = ctx->error_resilient || ctx->flags & VP8F_ERROR_RESILIENT;
1152 
1153  while ((en = av_dict_iterate(ctx->vpx_ts_parameters, en))) {
1154  if (vpx_ts_param_parse(ctx, &enccfg, en->key, en->value, avctx->codec_id) < 0)
1155  av_log(avctx, AV_LOG_WARNING,
1156  "Error parsing option '%s = %s'.\n",
1157  en->key, en->value);
1158  }
1159 
1160  /* Construct Encoder Context */
1161  res = vpx_codec_enc_init(&ctx->encoder, iface, &enccfg, flags);
1162  if (res != VPX_CODEC_OK) {
1163  dump_enc_cfg(avctx, &enccfg, AV_LOG_WARNING);
1164  log_encoder_error(avctx, "Failed to initialize encoder");
1165  return AVERROR(EINVAL);
1166  }
1167  dump_enc_cfg(avctx, &enccfg, AV_LOG_DEBUG);
1168 
1169 #if CONFIG_LIBVPX_VP9_ENCODER
1170  if (avctx->codec_id == AV_CODEC_ID_VP9 && enccfg.ts_number_layers > 1) {
1171  memset(&svc_params, 0, sizeof(svc_params));
1172  for (int i = 0; i < enccfg.ts_number_layers; ++i) {
1173  svc_params.max_quantizers[i] = enccfg.rc_max_quantizer;
1174  svc_params.min_quantizers[i] = enccfg.rc_min_quantizer;
1175  }
1176  svc_params.scaling_factor_num[0] = enccfg.g_h;
1177  svc_params.scaling_factor_den[0] = enccfg.g_h;
1178 #if VPX_ENCODER_ABI_VERSION >= 12
1179  codecctl_int(avctx, VP9E_SET_SVC, 1);
1180  codecctl_intp(avctx, VP9E_SET_SVC_PARAMETERS, (int *)&svc_params);
1181 #endif
1182  }
1183 #endif
1184  if (ctx->is_alpha) {
1185  enccfg_alpha = enccfg;
1186  res = vpx_codec_enc_init(&ctx->encoder_alpha, iface, &enccfg_alpha, flags);
1187  if (res != VPX_CODEC_OK) {
1188  log_encoder_error(avctx, "Failed to initialize alpha encoder");
1189  return AVERROR(EINVAL);
1190  }
1191  }
1192 
1193  //codec control failures are currently treated only as warnings
1194  av_log(avctx, AV_LOG_DEBUG, "vpx_codec_control\n");
1195  codecctl_int(avctx, VP8E_SET_CPUUSED, ctx->cpu_used);
1196  if (ctx->flags & VP8F_AUTO_ALT_REF)
1197  ctx->auto_alt_ref = 1;
1198  if (ctx->auto_alt_ref >= 0)
1199  codecctl_int(avctx, VP8E_SET_ENABLEAUTOALTREF,
1200  avctx->codec_id == AV_CODEC_ID_VP8 ? !!ctx->auto_alt_ref : ctx->auto_alt_ref);
1201  if (ctx->arnr_max_frames >= 0)
1202  codecctl_int(avctx, VP8E_SET_ARNR_MAXFRAMES, ctx->arnr_max_frames);
1203  if (ctx->arnr_strength >= 0)
1204  codecctl_int(avctx, VP8E_SET_ARNR_STRENGTH, ctx->arnr_strength);
1205  if (ctx->arnr_type >= 0)
1206  codecctl_int(avctx, VP8E_SET_ARNR_TYPE, ctx->arnr_type);
1207  if (ctx->tune >= 0)
1208  codecctl_int(avctx, VP8E_SET_TUNING, ctx->tune);
1209 
1210  if (ctx->auto_alt_ref && ctx->is_alpha && avctx->codec_id == AV_CODEC_ID_VP8) {
1211  av_log(avctx, AV_LOG_ERROR, "Transparency encoding with auto_alt_ref does not work\n");
1212  return AVERROR(EINVAL);
1213  }
1214 
1215  if (ctx->sharpness >= 0)
1216  codecctl_int(avctx, VP8E_SET_SHARPNESS, ctx->sharpness);
1217 
1218  if (CONFIG_LIBVPX_VP8_ENCODER && avctx->codec_id == AV_CODEC_ID_VP8) {
1219  codecctl_int(avctx, VP8E_SET_NOISE_SENSITIVITY, ctx->noise_sensitivity);
1220  codecctl_int(avctx, VP8E_SET_TOKEN_PARTITIONS, av_log2(avctx->slices));
1221  }
1222  codecctl_int(avctx, VP8E_SET_STATIC_THRESHOLD, ctx->static_thresh);
1223  if (ctx->crf >= 0)
1224  codecctl_int(avctx, VP8E_SET_CQ_LEVEL, ctx->crf);
1225  if (ctx->max_intra_rate >= 0)
1226  codecctl_int(avctx, VP8E_SET_MAX_INTRA_BITRATE_PCT, ctx->max_intra_rate);
1227 
1228 #if CONFIG_LIBVPX_VP9_ENCODER
1229  if (avctx->codec_id == AV_CODEC_ID_VP9) {
1230  if (ctx->lossless >= 0)
1231  codecctl_int(avctx, VP9E_SET_LOSSLESS, ctx->lossless);
1232  if (ctx->tile_columns >= 0)
1233  codecctl_int(avctx, VP9E_SET_TILE_COLUMNS, ctx->tile_columns);
1234  if (ctx->tile_rows >= 0)
1235  codecctl_int(avctx, VP9E_SET_TILE_ROWS, ctx->tile_rows);
1236  if (ctx->frame_parallel >= 0)
1237  codecctl_int(avctx, VP9E_SET_FRAME_PARALLEL_DECODING, ctx->frame_parallel);
1238  if (ctx->aq_mode >= 0)
1239  codecctl_int(avctx, VP9E_SET_AQ_MODE, ctx->aq_mode);
1240  set_colorspace(avctx);
1241 #if VPX_ENCODER_ABI_VERSION >= 11
1242  set_color_range(avctx);
1243 #endif
1244 #if VPX_ENCODER_ABI_VERSION >= 12
1245  codecctl_int(avctx, VP9E_SET_TARGET_LEVEL, ctx->level < 0 ? 255 : lrint(ctx->level * 10));
1246 #endif
1247 #ifdef VPX_CTRL_VP9E_SET_ROW_MT
1248  if (ctx->row_mt >= 0)
1249  codecctl_int(avctx, VP9E_SET_ROW_MT, ctx->row_mt);
1250 #endif
1251 #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
1252  if (ctx->tune_content >= 0)
1253  codecctl_int(avctx, VP9E_SET_TUNE_CONTENT, ctx->tune_content);
1254 #endif
1255 #ifdef VPX_CTRL_VP9E_SET_TPL
1256  if (ctx->tpl_model >= 0)
1257  codecctl_int(avctx, VP9E_SET_TPL, ctx->tpl_model);
1258 #endif
1259 #ifdef VPX_CTRL_VP9E_SET_MIN_GF_INTERVAL
1260  if (ctx->min_gf_interval >= 0)
1261  codecctl_int(avctx, VP9E_SET_MIN_GF_INTERVAL, ctx->min_gf_interval);
1262 #endif
1263  }
1264 #endif
1265 
1266  av_log(avctx, AV_LOG_DEBUG, "Using deadline: %d\n", ctx->deadline);
1267 
1268  //provide dummy value to initialize wrapper, values will be updated each _encode()
1269  vpx_img_wrap(&ctx->rawimg, img_fmt, avctx->width, avctx->height, 1,
1270  (unsigned char*)1);
1271 #if CONFIG_LIBVPX_VP9_ENCODER
1272  if (avctx->codec_id == AV_CODEC_ID_VP9 && (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH))
1273  ctx->rawimg.bit_depth = enccfg.g_bit_depth;
1274 #endif
1275 
1276  cpb_props = ff_encode_add_cpb_side_data(avctx);
1277  if (!cpb_props)
1278  return AVERROR(ENOMEM);
1279 
1280  if (enccfg.rc_end_usage == VPX_CBR ||
1281  enccfg.g_pass != VPX_RC_ONE_PASS) {
1282  cpb_props->max_bitrate = avctx->rc_max_rate;
1283  cpb_props->min_bitrate = avctx->rc_min_rate;
1284  cpb_props->avg_bitrate = avctx->bit_rate;
1285  }
1286  cpb_props->buffer_size = avctx->rc_buffer_size;
1287 
1288  return 0;
1289 }
1290 
1291 static inline void cx_pktcpy(struct FrameListData *dst,
1292  const struct vpx_codec_cx_pkt *src,
1293  VPxContext *ctx)
1294 {
1295  dst->pts = src->data.frame.pts;
1296  dst->flags = src->data.frame.flags;
1297  dst->sz = src->data.frame.sz;
1298  dst->buf = src->data.frame.buf;
1299  dst->have_sse = 0;
1300  /* For alt-ref frame, don't store PSNR */
1301  if (!(dst->flags & VPX_FRAME_IS_INVISIBLE)) {
1302  dst->have_sse = ctx->have_sse;
1303  if (ctx->have_sse) {
1304  /* associate last-seen SSE to the frame. */
1305  /* Transfers ownership from ctx to dst. */
1306  /* WARNING! This makes the assumption that PSNR_PKT comes
1307  just before the frame it refers to! */
1308  memcpy(dst->sse, ctx->sse, sizeof(dst->sse));
1309  ctx->have_sse = 0;
1310  }
1311  }
1312 }
1313 
1314 /**
1315  * Store coded frame information in format suitable for return from encode2().
1316  *
1317  * Write information from @a cx_frame to @a pkt
1318  * @return packet data size on success
1319  * @return a negative AVERROR on error
1320  */
1321 static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame,
1322  struct FrameListData *alpha_cx_frame, AVPacket *pkt)
1323 {
1324  VPxContext *ctx = avctx->priv_data;
1325  int ret = ff_get_encode_buffer(avctx, pkt, cx_frame->sz, 0);
1326  uint8_t *side_data;
1327  int pict_type;
1328  int quality;
1329 
1330  if (ret < 0)
1331  return ret;
1332 
1333  memcpy(pkt->data, cx_frame->buf, pkt->size);
1334  pkt->pts = pkt->dts = cx_frame->pts;
1335 
1336  if (!!(cx_frame->flags & VPX_FRAME_IS_KEY)) {
1337  pict_type = AV_PICTURE_TYPE_I;
1339  } else {
1340  pict_type = AV_PICTURE_TYPE_P;
1341  }
1342 
1343  ret = vpx_codec_control(&ctx->encoder, VP8E_GET_LAST_QUANTIZER_64, &quality);
1344  if (ret != VPX_CODEC_OK)
1345  quality = 0;
1347  cx_frame->have_sse ? 3 : 0, pict_type);
1348 
1349  if (cx_frame->have_sse) {
1350  /* Beware of the Y/U/V/all order! */
1351  for (int i = 0; i < 3; ++i)
1352  avctx->error[i] += cx_frame->sse[i + 1];
1353  cx_frame->have_sse = 0;
1354  }
1355  if (alpha_cx_frame) {
1356  side_data = av_packet_new_side_data(pkt,
1358  alpha_cx_frame->sz + 8);
1359  if (!side_data) {
1361  return AVERROR(ENOMEM);
1362  }
1363  AV_WB64(side_data, 1);
1364  memcpy(side_data + 8, alpha_cx_frame->buf, alpha_cx_frame->sz);
1365  }
1366  ret = frame_data_apply(avctx, ctx->fifo, pkt);
1367  if (ret < 0)
1368  return ret;
1369 
1370  return pkt->size;
1371 }
1372 
1373 /**
1374  * Queue multiple output frames from the encoder, returning the front-most.
1375  * In cases where vpx_codec_get_cx_data() returns more than 1 frame append
1376  * the frame queue. Return the head frame if available.
1377  * @return Stored frame size
1378  * @return AVERROR(EINVAL) on output size error
1379  * @return AVERROR(ENOMEM) on coded frame queue data allocation error
1380  */
1381 static int queue_frames(AVCodecContext *avctx, struct vpx_codec_ctx *encoder,
1382  struct FrameListData **frame_list, AVPacket *pkt_out)
1383 {
1384  VPxContext *ctx = avctx->priv_data;
1385  const struct vpx_codec_cx_pkt *pkt;
1386  const void *iter = NULL;
1387  int size = 0;
1388 
1389  if (!ctx->is_alpha && *frame_list) {
1390  struct FrameListData *cx_frame = *frame_list;
1391  /* return the leading frame if we've already begun queueing */
1392  size = storeframe(avctx, cx_frame, NULL, pkt_out);
1393  if (size < 0)
1394  return size;
1395  *frame_list = cx_frame->next;
1396  free_coded_frame(cx_frame);
1397  }
1398 
1399  /* consume all available output from the encoder before returning. buffers
1400  are only good through the next vpx_codec call */
1401  while (pkt = vpx_codec_get_cx_data(encoder, &iter)) {
1402  switch (pkt->kind) {
1403  case VPX_CODEC_CX_FRAME_PKT:
1404  if (!ctx->is_alpha && !size) {
1405  struct FrameListData cx_frame;
1406 
1407  /* avoid storing the frame when the list is empty and we haven't yet
1408  provided a frame for output */
1409  av_assert0(!ctx->coded_frame_list);
1410  cx_pktcpy(&cx_frame, pkt, ctx);
1411  size = storeframe(avctx, &cx_frame, NULL, pkt_out);
1412  if (size < 0)
1413  return size;
1414  } else {
1415  struct FrameListData *cx_frame = av_malloc(sizeof(*cx_frame));
1416 
1417  if (!cx_frame) {
1418  av_log(avctx, AV_LOG_ERROR,
1419  "Frame queue element alloc failed\n");
1420  return AVERROR(ENOMEM);
1421  }
1422  cx_pktcpy(cx_frame, pkt, ctx);
1423  cx_frame->buf = av_malloc(cx_frame->sz);
1424 
1425  if (!cx_frame->buf) {
1426  av_log(avctx, AV_LOG_ERROR,
1427  "Data buffer alloc (%"SIZE_SPECIFIER" bytes) failed\n",
1428  cx_frame->sz);
1429  av_freep(&cx_frame);
1430  return AVERROR(ENOMEM);
1431  }
1432  memcpy(cx_frame->buf, pkt->data.frame.buf, pkt->data.frame.sz);
1433  coded_frame_add(frame_list, cx_frame);
1434  }
1435  break;
1436  case VPX_CODEC_STATS_PKT: {
1437  struct vpx_fixed_buf *stats = &ctx->twopass_stats;
1438  uint8_t *tmp;
1439  if (!pkt_out)
1440  break;
1441  tmp = av_fast_realloc(stats->buf,
1442  &ctx->twopass_stats_size,
1443  stats->sz +
1444  pkt->data.twopass_stats.sz);
1445  if (!tmp) {
1446  av_freep(&stats->buf);
1447  stats->sz = 0;
1448  av_log(avctx, AV_LOG_ERROR, "Stat buffer realloc failed\n");
1449  return AVERROR(ENOMEM);
1450  }
1451  stats->buf = tmp;
1452  memcpy((uint8_t*)stats->buf + stats->sz,
1453  pkt->data.twopass_stats.buf, pkt->data.twopass_stats.sz);
1454  stats->sz += pkt->data.twopass_stats.sz;
1455  break;
1456  }
1457  case VPX_CODEC_PSNR_PKT:
1458  if (!pkt_out)
1459  break;
1460  av_assert0(!ctx->have_sse);
1461  ctx->sse[0] = pkt->data.psnr.sse[0];
1462  ctx->sse[1] = pkt->data.psnr.sse[1];
1463  ctx->sse[2] = pkt->data.psnr.sse[2];
1464  ctx->sse[3] = pkt->data.psnr.sse[3];
1465  ctx->have_sse = 1;
1466  break;
1467  case VPX_CODEC_CUSTOM_PKT:
1468  //ignore unsupported/unrecognized packet types
1469  break;
1470  }
1471  }
1472 
1473  return size;
1474 }
1475 
1476 static int set_roi_map(AVCodecContext *avctx, const AVFrameSideData *sd, int frame_width, int frame_height,
1477  vpx_roi_map_t *roi_map, int block_size, int segment_cnt)
1478 {
1479  /**
1480  * range of vpx_roi_map_t.delta_q[i] is [-63, 63]
1481  */
1482 #define MAX_DELTA_Q 63
1483 
1484  const AVRegionOfInterest *roi = NULL;
1485  int nb_rois;
1486  uint32_t self_size;
1487  int segment_id;
1488 
1489  /* record the mapping from delta_q to "segment id + 1" in segment_mapping[].
1490  * the range of delta_q is [-MAX_DELTA_Q, MAX_DELTA_Q],
1491  * and its corresponding array index is [0, 2 * MAX_DELTA_Q],
1492  * and so the length of the mapping array is 2 * MAX_DELTA_Q + 1.
1493  * "segment id + 1", so we can say there's no mapping if the value of array element is zero.
1494  */
1495  int segment_mapping[2 * MAX_DELTA_Q + 1] = { 0 };
1496 
1497  memset(roi_map, 0, sizeof(*roi_map));
1498 
1499  /* segment id 0 in roi_map is reserved for the areas not covered by AVRegionOfInterest.
1500  * segment id 0 in roi_map is also for the areas with AVRegionOfInterest.qoffset near 0.
1501  * (delta_q of segment id 0 is 0).
1502  */
1503  segment_mapping[MAX_DELTA_Q] = 1;
1504  segment_id = 1;
1505 
1506  roi = (const AVRegionOfInterest*)sd->data;
1507  self_size = roi->self_size;
1508  if (!self_size || sd->size % self_size) {
1509  av_log(avctx, AV_LOG_ERROR, "Invalid AVRegionOfInterest.self_size.\n");
1510  return AVERROR(EINVAL);
1511  }
1512  nb_rois = sd->size / self_size;
1513 
1514  /* This list must be iterated from zero because regions are
1515  * defined in order of decreasing importance. So discard less
1516  * important areas if they exceed the segment count.
1517  */
1518  for (int i = 0; i < nb_rois; i++) {
1519  int delta_q;
1520  int mapping_index;
1521 
1522  roi = (const AVRegionOfInterest*)(sd->data + self_size * i);
1523  if (!roi->qoffset.den) {
1524  av_log(avctx, AV_LOG_ERROR, "AVRegionOfInterest.qoffset.den must not be zero.\n");
1525  return AVERROR(EINVAL);
1526  }
1527 
1528  delta_q = (int)(roi->qoffset.num * 1.0f / roi->qoffset.den * MAX_DELTA_Q);
1530 
1531  mapping_index = delta_q + MAX_DELTA_Q;
1532  if (!segment_mapping[mapping_index]) {
1533  if (segment_id == segment_cnt) {
1534  av_log(avctx, AV_LOG_WARNING,
1535  "ROI only supports %d segments (and segment 0 is reserved for non-ROIs), skipping the left ones.\n",
1536  segment_cnt);
1537  break;
1538  }
1539 
1540  segment_mapping[mapping_index] = segment_id + 1;
1541  roi_map->delta_q[segment_id] = delta_q;
1542  segment_id++;
1543  }
1544  }
1545 
1546  roi_map->rows = (frame_height + block_size - 1) / block_size;
1547  roi_map->cols = (frame_width + block_size - 1) / block_size;
1548  roi_map->roi_map = av_calloc(roi_map->rows * roi_map->cols, sizeof(*roi_map->roi_map));
1549  if (!roi_map->roi_map) {
1550  av_log(avctx, AV_LOG_ERROR, "roi_map alloc failed.\n");
1551  return AVERROR(ENOMEM);
1552  }
1553 
1554  /* This list must be iterated in reverse, so for the case that
1555  * two regions are overlapping, the more important area takes effect.
1556  */
1557  for (int i = nb_rois - 1; i >= 0; i--) {
1558  int delta_q;
1559  int mapping_value;
1560  int starty, endy, startx, endx;
1561 
1562  roi = (const AVRegionOfInterest*)(sd->data + self_size * i);
1563 
1564  starty = av_clip(roi->top / block_size, 0, roi_map->rows);
1565  endy = av_clip((roi->bottom + block_size - 1) / block_size, 0, roi_map->rows);
1566  startx = av_clip(roi->left / block_size, 0, roi_map->cols);
1567  endx = av_clip((roi->right + block_size - 1) / block_size, 0, roi_map->cols);
1568 
1569  delta_q = (int)(roi->qoffset.num * 1.0f / roi->qoffset.den * MAX_DELTA_Q);
1571 
1572  mapping_value = segment_mapping[delta_q + MAX_DELTA_Q];
1573  if (mapping_value) {
1574  for (int y = starty; y < endy; y++)
1575  for (int x = startx; x < endx; x++)
1576  roi_map->roi_map[x + y * roi_map->cols] = mapping_value - 1;
1577  }
1578  }
1579 
1580  return 0;
1581 }
1582 
1583 static int vp9_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd)
1584 {
1585  VPxContext *ctx = avctx->priv_data;
1586 
1587 #ifdef VPX_CTRL_VP9E_SET_ROI_MAP
1588  int version = vpx_codec_version();
1589  int major = VPX_VERSION_MAJOR(version);
1590  int minor = VPX_VERSION_MINOR(version);
1591  int patch = VPX_VERSION_PATCH(version);
1592 
1593  if (major > 1 || (major == 1 && minor > 8) || (major == 1 && minor == 8 && patch >= 1)) {
1594  vpx_roi_map_t roi_map;
1595  const int segment_cnt = 8;
1596  const int block_size = 8;
1597  int ret;
1598 
1599  if (ctx->aq_mode > 0 || ctx->cpu_used < 5 || ctx->deadline != VPX_DL_REALTIME) {
1600  if (!ctx->roi_warned) {
1601  ctx->roi_warned = 1;
1602  av_log(avctx, AV_LOG_WARNING, "ROI is only enabled when aq_mode is 0, cpu_used >= 5 "
1603  "and deadline is REALTIME, so skipping ROI.\n");
1604  return AVERROR(EINVAL);
1605  }
1606  }
1607 
1608  ret = set_roi_map(avctx, sd, frame_width, frame_height, &roi_map, block_size, segment_cnt);
1609  if (ret) {
1610  log_encoder_error(avctx, "Failed to set_roi_map.\n");
1611  return ret;
1612  }
1613 
1614  memset(roi_map.ref_frame, -1, sizeof(roi_map.ref_frame));
1615 
1616  if (vpx_codec_control(&ctx->encoder, VP9E_SET_ROI_MAP, &roi_map)) {
1617  log_encoder_error(avctx, "Failed to set VP9E_SET_ROI_MAP codec control.\n");
1619  }
1620  av_freep(&roi_map.roi_map);
1621  return ret;
1622  }
1623 #endif
1624 
1625  if (!ctx->roi_warned) {
1626  ctx->roi_warned = 1;
1627  av_log(avctx, AV_LOG_WARNING, "ROI is not supported, please upgrade libvpx to version >= 1.8.1. "
1628  "You may need to rebuild ffmpeg.\n");
1629  }
1630  return 0;
1631 }
1632 
1633 static int vp8_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd)
1634 {
1635  vpx_roi_map_t roi_map;
1636  const int segment_cnt = 4;
1637  const int block_size = 16;
1638  VPxContext *ctx = avctx->priv_data;
1639 
1640  int ret = set_roi_map(avctx, sd, frame_width, frame_height, &roi_map, block_size, segment_cnt);
1641  if (ret) {
1642  log_encoder_error(avctx, "Failed to set_roi_map.\n");
1643  return ret;
1644  }
1645 
1646  if (vpx_codec_control(&ctx->encoder, VP8E_SET_ROI_MAP, &roi_map)) {
1647  log_encoder_error(avctx, "Failed to set VP8E_SET_ROI_MAP codec control.\n");
1649  }
1650 
1651  av_freep(&roi_map.roi_map);
1652  return ret;
1653 }
1654 
1655 static int realloc_alpha_uv(AVCodecContext *avctx, int width, int height)
1656 {
1657  VPxContext *ctx = avctx->priv_data;
1658  struct vpx_image *rawimg_alpha = &ctx->rawimg_alpha;
1659  unsigned char **planes = rawimg_alpha->planes;
1660  int *stride = rawimg_alpha->stride;
1661 
1662  if (!planes[VPX_PLANE_U] ||
1663  !planes[VPX_PLANE_V] ||
1664  width != (int)rawimg_alpha->d_w ||
1665  height != (int)rawimg_alpha->d_h) {
1666  av_freep(&planes[VPX_PLANE_U]);
1667  av_freep(&planes[VPX_PLANE_V]);
1668 
1669  vpx_img_wrap(rawimg_alpha, VPX_IMG_FMT_I420, width, height, 1,
1670  (unsigned char*)1);
1671  planes[VPX_PLANE_U] = av_malloc_array(stride[VPX_PLANE_U], height);
1672  planes[VPX_PLANE_V] = av_malloc_array(stride[VPX_PLANE_V], height);
1673  if (!planes[VPX_PLANE_U] || !planes[VPX_PLANE_V])
1674  return AVERROR(ENOMEM);
1675 
1676  memset(planes[VPX_PLANE_U], 0x80, stride[VPX_PLANE_U] * height);
1677  memset(planes[VPX_PLANE_V], 0x80, stride[VPX_PLANE_V] * height);
1678  }
1679 
1680  return 0;
1681 }
1682 
1684  const AVFrame *frame, int *got_packet)
1685 {
1686  VPxContext *ctx = avctx->priv_data;
1687  struct vpx_image *rawimg = NULL;
1688  struct vpx_image *rawimg_alpha = NULL;
1689  int64_t timestamp = 0;
1690  int res, coded_size;
1691  vpx_enc_frame_flags_t flags = 0;
1692  const struct vpx_codec_enc_cfg *enccfg = ctx->encoder.config.enc;
1693  vpx_svc_layer_id_t layer_id;
1694  int layer_id_valid = 0;
1695  unsigned long duration = 0;
1696 
1697  if (avctx->qmax >= 0 && enccfg->rc_max_quantizer != avctx->qmax) {
1698  struct vpx_codec_enc_cfg cfg = *enccfg;
1699  cfg.rc_max_quantizer = avctx->qmax;
1700  res = vpx_codec_enc_config_set(&ctx->encoder, &cfg);
1701  if (res != VPX_CODEC_OK) {
1702  log_encoder_error(avctx, "Error reconfiguring encoder");
1703  return AVERROR_INVALIDDATA;
1704  }
1705  }
1706 
1707  if (frame) {
1709  rawimg = &ctx->rawimg;
1710  rawimg->planes[VPX_PLANE_Y] = frame->data[0];
1711  rawimg->planes[VPX_PLANE_U] = frame->data[1];
1712  rawimg->planes[VPX_PLANE_V] = frame->data[2];
1713  rawimg->stride[VPX_PLANE_Y] = frame->linesize[0];
1714  rawimg->stride[VPX_PLANE_U] = frame->linesize[1];
1715  rawimg->stride[VPX_PLANE_V] = frame->linesize[2];
1716  if (ctx->is_alpha) {
1717  rawimg_alpha = &ctx->rawimg_alpha;
1718  res = realloc_alpha_uv(avctx, frame->width, frame->height);
1719  if (res < 0)
1720  return res;
1721  rawimg_alpha->planes[VPX_PLANE_Y] = frame->data[3];
1722  rawimg_alpha->stride[VPX_PLANE_Y] = frame->linesize[3];
1723  }
1724  timestamp = frame->pts;
1725 #if VPX_IMAGE_ABI_VERSION >= 4
1726  switch (frame->color_range) {
1727  case AVCOL_RANGE_MPEG:
1728  rawimg->range = VPX_CR_STUDIO_RANGE;
1729  break;
1730  case AVCOL_RANGE_JPEG:
1731  rawimg->range = VPX_CR_FULL_RANGE;
1732  break;
1733  }
1734 #endif
1736  flags |= VPX_EFLAG_FORCE_KF;
1737  if (frame->metadata) {
1738  AVDictionaryEntry* en = av_dict_get(frame->metadata, "vp8-flags", NULL, 0);
1739  if (en) {
1740  flags |= strtoul(en->value, NULL, 10);
1741  }
1742 
1743  memset(&layer_id, 0, sizeof(layer_id));
1744 
1745  en = av_dict_get(frame->metadata, "temporal_id", NULL, 0);
1746  if (en) {
1747  layer_id.temporal_layer_id = strtoul(en->value, NULL, 10);
1748 #ifdef VPX_CTRL_VP9E_SET_MAX_INTER_BITRATE_PCT
1749  layer_id.temporal_layer_id_per_spatial[0] = layer_id.temporal_layer_id;
1750 #endif
1751  layer_id_valid = 1;
1752  }
1753 #if CONFIG_LIBVPX_VP9_ENCODER && defined(VPX_CTRL_VP9E_SET_MAX_INTER_BITRATE_PCT)
1754  en = av_dict_get(frame->metadata, "ref-frame-config", NULL, 0);
1755 
1756  if (en) {
1757  if (avctx->codec_id == AV_CODEC_ID_VP9) {
1758  int ret = vpx_parse_ref_frame_config(&ctx->ref_frame_config,
1759  enccfg->ss_number_layers, en->value);
1760  if (ret < 0) {
1761  av_log(avctx, AV_LOG_WARNING,
1762  "Error parsing ref_frame_config option %s.\n", en->value);
1763  return ret;
1764  }
1765 
1766  codecctl_intp(avctx, VP9E_SET_SVC_REF_FRAME_CONFIG, (int *)&ctx->ref_frame_config);
1767  } else {
1768  av_log(avctx, AV_LOG_WARNING,
1769  "Ignoring ref-frame-config for a non-VP9 codec\n");
1770  }
1771  }
1772 #endif
1773  }
1774 
1775  if (sd) {
1776  if (avctx->codec_id == AV_CODEC_ID_VP8) {
1777  vp8_encode_set_roi(avctx, frame->width, frame->height, sd);
1778  } else {
1779  vp9_encode_set_roi(avctx, frame->width, frame->height, sd);
1780  }
1781  }
1782 
1783  if (!(avctx->flags & AV_CODEC_FLAG_PASS1)) {
1784  res = frame_data_submit(avctx, ctx->fifo, frame);
1785  if (res < 0)
1786  return res;
1787  }
1788  }
1789 
1790  // this is for encoding with preset temporal layering patterns defined in
1791  // set_temporal_layer_pattern function.
1792  if (enccfg->ts_number_layers > 1 && ctx->ts_layer_flags) {
1793  if (flags & VPX_EFLAG_FORCE_KF) {
1794  // keyframe, reset temporal layering.
1795  ctx->current_temporal_idx = 0;
1796  flags = VPX_EFLAG_FORCE_KF;
1797  } else {
1798  flags = 0;
1799  }
1800 
1801  /* get the flags from the temporal layer configuration. */
1802  flags |= ctx->ts_layer_flags[ctx->current_temporal_idx];
1803 
1804  memset(&layer_id, 0, sizeof(layer_id));
1805 #if VPX_ENCODER_ABI_VERSION >= 12
1806  layer_id.spatial_layer_id = 0;
1807 #endif
1808  layer_id.temporal_layer_id = enccfg->ts_layer_id[ctx->current_temporal_idx];
1809 #ifdef VPX_CTRL_VP9E_SET_MAX_INTER_BITRATE_PCT
1810  layer_id.temporal_layer_id_per_spatial[0] = layer_id.temporal_layer_id;
1811 #endif
1812  layer_id_valid = 1;
1813  }
1814 
1815  if (layer_id_valid) {
1816  if (avctx->codec_id == AV_CODEC_ID_VP8) {
1817  codecctl_int(avctx, VP8E_SET_TEMPORAL_LAYER_ID, layer_id.temporal_layer_id);
1818  }
1819 #if CONFIG_LIBVPX_VP9_ENCODER && VPX_ENCODER_ABI_VERSION >= 12
1820  else if (avctx->codec_id == AV_CODEC_ID_VP9) {
1821  codecctl_intp(avctx, VP9E_SET_SVC_LAYER_ID, (int *)&layer_id);
1822  }
1823 #endif
1824  }
1825 
1826  if (frame && frame->duration > ULONG_MAX) {
1827  av_log(avctx, AV_LOG_WARNING,
1828  "Frame duration too large: %"PRId64"\n", frame->duration);
1829  } else if (frame && frame->duration)
1830  duration = frame->duration;
1831  else if (avctx->framerate.num > 0 && avctx->framerate.den > 0)
1832  duration = av_rescale_q(1, av_inv_q(avctx->framerate), avctx->time_base);
1833  else {
1835  duration =
1836 #if FF_API_TICKS_PER_FRAME
1837  avctx->ticks_per_frame ? avctx->ticks_per_frame :
1838 #endif
1839  1;
1841  }
1842 
1843  res = vpx_codec_encode(&ctx->encoder, rawimg, timestamp,
1844  duration, flags, ctx->deadline);
1845  if (res != VPX_CODEC_OK) {
1846  log_encoder_error(avctx, "Error encoding frame");
1847  return AVERROR_INVALIDDATA;
1848  }
1849 
1850  if (ctx->is_alpha) {
1851  res = vpx_codec_encode(&ctx->encoder_alpha, rawimg_alpha, timestamp,
1852  duration, flags, ctx->deadline);
1853  if (res != VPX_CODEC_OK) {
1854  log_encoder_error(avctx, "Error encoding alpha frame");
1855  return AVERROR_INVALIDDATA;
1856  }
1857  }
1858 
1859  coded_size = queue_frames(avctx, &ctx->encoder, &ctx->coded_frame_list, pkt);
1860  if (ctx->is_alpha) {
1861  queue_frames(avctx, &ctx->encoder_alpha, &ctx->alpha_coded_frame_list, NULL);
1862 
1863  if (ctx->coded_frame_list && ctx->alpha_coded_frame_list) {
1864  struct FrameListData *cx_frame = ctx->coded_frame_list;
1865  struct FrameListData *alpha_cx_frame = ctx->alpha_coded_frame_list;
1866  av_assert0(!coded_size);
1867  /* return the leading frame if we've already begun queueing */
1868  coded_size = storeframe(avctx, cx_frame, alpha_cx_frame, pkt);
1869  if (coded_size < 0)
1870  return coded_size;
1871  ctx->coded_frame_list = cx_frame->next;
1872  ctx->alpha_coded_frame_list = alpha_cx_frame->next;
1873  free_coded_frame(cx_frame);
1874  free_coded_frame(alpha_cx_frame);
1875  }
1876  }
1877 
1878  if (!frame && avctx->flags & AV_CODEC_FLAG_PASS1) {
1879  unsigned int b64_size = AV_BASE64_SIZE(ctx->twopass_stats.sz);
1880 
1881  avctx->stats_out = av_malloc(b64_size);
1882  if (!avctx->stats_out) {
1883  av_log(avctx, AV_LOG_ERROR, "Stat buffer alloc (%d bytes) failed\n",
1884  b64_size);
1885  return AVERROR(ENOMEM);
1886  }
1887  av_base64_encode(avctx->stats_out, b64_size, ctx->twopass_stats.buf,
1888  ctx->twopass_stats.sz);
1889  } else if (enccfg->ts_number_layers > 1 && ctx->ts_layer_flags) {
1890  ctx->current_temporal_idx = (ctx->current_temporal_idx + 1) % enccfg->ts_periodicity;
1891  }
1892 
1893  *got_packet = !!coded_size;
1894  return 0;
1895 }
1896 
1897 #define OFFSET(x) offsetof(VPxContext, x)
1898 #define VE AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_ENCODING_PARAM
1899 
1900 #define COMMON_OPTIONS \
1901  { "lag-in-frames", "Number of frames to look ahead for " \
1902  "alternate reference frame selection", OFFSET(lag_in_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1903  { "arnr-maxframes", "altref noise reduction max frame count", OFFSET(arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1904  { "arnr-strength", "altref noise reduction filter strength", OFFSET(arnr_strength), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1905  { "arnr-type", "altref noise reduction filter type", OFFSET(arnr_type), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "arnr_type"}, \
1906  { "backward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "arnr_type" }, \
1907  { "forward", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "arnr_type" }, \
1908  { "centered", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "arnr_type" }, \
1909  { "tune", "Tune the encoding to a specific scenario", OFFSET(tune), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE, "tune"}, \
1910  { "psnr", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_PSNR}, 0, 0, VE, "tune"}, \
1911  { "ssim", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VP8_TUNE_SSIM}, 0, 0, VE, "tune"}, \
1912  { "deadline", "Time to spend encoding, in microseconds.", OFFSET(deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
1913  { "best", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_BEST_QUALITY}, 0, 0, VE, "quality"}, \
1914  { "good", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_GOOD_QUALITY}, 0, 0, VE, "quality"}, \
1915  { "realtime", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = VPX_DL_REALTIME}, 0, 0, VE, "quality"}, \
1916  { "error-resilient", "Error resilience configuration", OFFSET(error_resilient), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, VE, "er"}, \
1917  { "max-intra-rate", "Maximum I-frame bitrate (pct) 0=unlimited", OFFSET(max_intra_rate), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE}, \
1918  { "default", "Improve resiliency against losses of whole frames", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_DEFAULT}, 0, 0, VE, "er"}, \
1919  { "partitions", "The frame partitions are independently decodable " \
1920  "by the bool decoder, meaning that partitions can be decoded even " \
1921  "though earlier partitions have been lost. Note that intra prediction" \
1922  " is still done over the partition boundary.", 0, AV_OPT_TYPE_CONST, {.i64 = VPX_ERROR_RESILIENT_PARTITIONS}, 0, 0, VE, "er"}, \
1923  { "crf", "Select the quality for constant quality mode", offsetof(VPxContext, crf), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, VE }, \
1924  { "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 }, \
1925  { "drop-threshold", "Frame drop threshold", offsetof(VPxContext, drop_threshold), AV_OPT_TYPE_INT, {.i64 = 0 }, INT_MIN, INT_MAX, VE }, \
1926  { "noise-sensitivity", "Noise sensitivity", OFFSET(noise_sensitivity), AV_OPT_TYPE_INT, {.i64 = 0 }, 0, 4, VE}, \
1927  { "undershoot-pct", "Datarate undershoot (min) target (%)", OFFSET(rc_undershoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 100, VE }, \
1928  { "overshoot-pct", "Datarate overshoot (max) target (%)", OFFSET(rc_overshoot_pct), AV_OPT_TYPE_INT, { .i64 = -1 }, -1, 1000, VE }, \
1929  { "ts-parameters", "Temporal scaling configuration using a :-separated list of key=value parameters", OFFSET(vpx_ts_parameters), AV_OPT_TYPE_DICT, {.str=NULL}, 0, 0, VE}, \
1930 
1931 #define LEGACY_OPTIONS \
1932  {"speed", "", offsetof(VPxContext, cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE}, \
1933  {"quality", "", offsetof(VPxContext, deadline), AV_OPT_TYPE_INT, {.i64 = VPX_DL_GOOD_QUALITY}, INT_MIN, INT_MAX, VE, "quality"}, \
1934  {"vp8flags", "", offsetof(VPxContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, 0, UINT_MAX, VE, "flags"}, \
1935  {"error_resilient", "enable error resilience", 0, AV_OPT_TYPE_CONST, {.i64 = VP8F_ERROR_RESILIENT}, INT_MIN, INT_MAX, VE, "flags"}, \
1936  {"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"}, \
1937  {"arnr_max_frames", "altref noise reduction max frame count", offsetof(VPxContext, arnr_max_frames), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 15, VE}, \
1938  {"arnr_strength", "altref noise reduction filter strength", offsetof(VPxContext, arnr_strength), AV_OPT_TYPE_INT, {.i64 = 3}, 0, 6, VE}, \
1939  {"arnr_type", "altref noise reduction filter type", offsetof(VPxContext, arnr_type), AV_OPT_TYPE_INT, {.i64 = 3}, 1, 3, VE}, \
1940  {"rc_lookahead", "Number of frames to look ahead for alternate reference frame selection", offsetof(VPxContext, lag_in_frames), AV_OPT_TYPE_INT, {.i64 = 25}, 0, 25, VE}, \
1941  {"sharpness", "Increase sharpness at the expense of lower PSNR", offsetof(VPxContext, sharpness), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 7, VE},
1942 
1943 #if CONFIG_LIBVPX_VP8_ENCODER
1944 static const AVOption vp8_options[] = {
1946  { "auto-alt-ref", "Enable use of alternate reference "
1947  "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1948  { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -16, 16, VE},
1950  { NULL }
1951 };
1952 #endif
1953 
1954 #if CONFIG_LIBVPX_VP9_ENCODER
1955 static const AVOption vp9_options[] = {
1957  { "auto-alt-ref", "Enable use of alternate reference "
1958  "frames (2-pass only)", OFFSET(auto_alt_ref), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1959  { "cpu-used", "Quality/Speed ratio modifier", OFFSET(cpu_used), AV_OPT_TYPE_INT, {.i64 = 1}, -8, 8, VE},
1960  { "lossless", "Lossless mode", OFFSET(lossless), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE},
1961  { "tile-columns", "Number of tile columns to use, log2", OFFSET(tile_columns), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 6, VE},
1962  { "tile-rows", "Number of tile rows to use, log2", OFFSET(tile_rows), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE},
1963  { "frame-parallel", "Enable frame parallel decodability features", OFFSET(frame_parallel), AV_OPT_TYPE_BOOL,{.i64 = -1}, -1, 1, VE},
1964 #if VPX_ENCODER_ABI_VERSION >= 12
1965  { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 4, VE, "aq_mode"},
1966 #else
1967  { "aq-mode", "adaptive quantization mode", OFFSET(aq_mode), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 3, VE, "aq_mode"},
1968 #endif
1969  { "none", "Aq not used", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "aq_mode" },
1970  { "variance", "Variance based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "aq_mode" },
1971  { "complexity", "Complexity based Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "aq_mode" },
1972  { "cyclic", "Cyclic Refresh Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 3}, 0, 0, VE, "aq_mode" },
1973 #if VPX_ENCODER_ABI_VERSION >= 12
1974  { "equator360", "360 video Aq", 0, AV_OPT_TYPE_CONST, {.i64 = 4}, 0, 0, VE, "aq_mode" },
1975  {"level", "Specify level", OFFSET(level), AV_OPT_TYPE_FLOAT, {.dbl=-1}, -1, 6.2, VE},
1976 #endif
1977 #ifdef VPX_CTRL_VP9E_SET_ROW_MT
1978  {"row-mt", "Row based multi-threading", OFFSET(row_mt), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE},
1979 #endif
1980 #ifdef VPX_CTRL_VP9E_SET_TUNE_CONTENT
1981 #if VPX_ENCODER_ABI_VERSION >= 14
1982  { "tune-content", "Tune content type", OFFSET(tune_content), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 2, VE, "tune_content" },
1983 #else
1984  { "tune-content", "Tune content type", OFFSET(tune_content), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 1, VE, "tune_content" },
1985 #endif
1986  { "default", "Regular video content", 0, AV_OPT_TYPE_CONST, {.i64 = 0}, 0, 0, VE, "tune_content" },
1987  { "screen", "Screen capture content", 0, AV_OPT_TYPE_CONST, {.i64 = 1}, 0, 0, VE, "tune_content" },
1988 #if VPX_ENCODER_ABI_VERSION >= 14
1989  { "film", "Film content; improves grain retention", 0, AV_OPT_TYPE_CONST, {.i64 = 2}, 0, 0, VE, "tune_content" },
1990 #endif
1991 #endif
1992 #if VPX_ENCODER_ABI_VERSION >= 14
1993  { "corpus-complexity", "corpus vbr complexity midpoint", OFFSET(corpus_complexity), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 10000, VE },
1994 #endif
1995 #ifdef VPX_CTRL_VP9E_SET_TPL
1996  { "enable-tpl", "Enable temporal dependency model", OFFSET(tpl_model), AV_OPT_TYPE_BOOL, {.i64 = -1}, -1, 1, VE },
1997 #endif
1998 #ifdef VPX_CTRL_VP9E_SET_MIN_GF_INTERVAL
1999  { "min-gf-interval", "Minimum golden/alternate reference frame interval", OFFSET(min_gf_interval), AV_OPT_TYPE_INT, {.i64 = -1}, -1, INT_MAX, VE },
2000 #endif
2002  { NULL }
2003 };
2004 #endif
2005 
2006 #undef COMMON_OPTIONS
2007 #undef LEGACY_OPTIONS
2008 
2009 static const FFCodecDefault defaults[] = {
2010  { "b", "0" },
2011  { "qmin", "-1" },
2012  { "qmax", "-1" },
2013  { "g", "-1" },
2014  { "keyint_min", "-1" },
2015  { NULL },
2016 };
2017 
2018 #if CONFIG_LIBVPX_VP8_ENCODER
2019 static av_cold int vp8_init(AVCodecContext *avctx)
2020 {
2021  return vpx_init(avctx, vpx_codec_vp8_cx());
2022 }
2023 
2024 static const AVClass class_vp8 = {
2025  .class_name = "libvpx-vp8 encoder",
2026  .item_name = av_default_item_name,
2027  .option = vp8_options,
2028  .version = LIBAVUTIL_VERSION_INT,
2029 };
2030 
2032  .p.name = "libvpx",
2033  CODEC_LONG_NAME("libvpx VP8"),
2034  .p.type = AVMEDIA_TYPE_VIDEO,
2035  .p.id = AV_CODEC_ID_VP8,
2036  .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
2039  .priv_data_size = sizeof(VPxContext),
2040  .init = vp8_init,
2042  .close = vpx_free,
2043  .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE |
2045  .p.pix_fmts = (const enum AVPixelFormat[]){ AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUVA420P, AV_PIX_FMT_NONE },
2046  .p.priv_class = &class_vp8,
2047  .defaults = defaults,
2048  .p.wrapper_name = "libvpx",
2049 };
2050 #endif /* CONFIG_LIBVPX_VP8_ENCODER */
2051 
2052 #if CONFIG_LIBVPX_VP9_ENCODER
2053 static av_cold int vp9_init(AVCodecContext *avctx)
2054 {
2055  return vpx_init(avctx, vpx_codec_vp9_cx());
2056 }
2057 
2058 static const enum AVPixelFormat vp9_pix_fmts_highcol[] = {
2066 };
2067 
2068 static const enum AVPixelFormat vp9_pix_fmts_highbd[] = {
2086 };
2087 
2088 static av_cold void vp9_init_static(FFCodec *codec)
2089 {
2090  vpx_codec_caps_t codec_caps = vpx_codec_get_caps(vpx_codec_vp9_cx());
2091  if (codec_caps & VPX_CODEC_CAP_HIGHBITDEPTH)
2092  codec->p.pix_fmts = vp9_pix_fmts_highbd;
2093  else
2094  codec->p.pix_fmts = vp9_pix_fmts_highcol;
2095 }
2096 
2097 static const AVClass class_vp9 = {
2098  .class_name = "libvpx-vp9 encoder",
2099  .item_name = av_default_item_name,
2100  .option = vp9_options,
2101  .version = LIBAVUTIL_VERSION_INT,
2102 };
2103 
2105  .p.name = "libvpx-vp9",
2106  CODEC_LONG_NAME("libvpx VP9"),
2107  .p.type = AVMEDIA_TYPE_VIDEO,
2108  .p.id = AV_CODEC_ID_VP9,
2109  .p.capabilities = AV_CODEC_CAP_DR1 | AV_CODEC_CAP_DELAY |
2112  .p.profiles = NULL_IF_CONFIG_SMALL(ff_vp9_profiles),
2113  .p.priv_class = &class_vp9,
2114  .p.wrapper_name = "libvpx",
2115  .priv_data_size = sizeof(VPxContext),
2116  .init = vp9_init,
2118  .close = vpx_free,
2119  .caps_internal = FF_CODEC_CAP_NOT_INIT_THREADSAFE |
2121  .defaults = defaults,
2122  .init_static_data = vp9_init_static,
2123 };
2124 #endif /* CONFIG_LIBVPX_VP9_ENCODER */
error
static void error(const char *err)
Definition: target_bsf_fuzzer.c:31
av_packet_unref
void av_packet_unref(AVPacket *pkt)
Wipe the packet.
Definition: avpacket.c:423
av_fifo_drain2
void av_fifo_drain2(AVFifo *f, size_t size)
Discard the specified amount of data from an AVFifo.
Definition: fifo.c:266
FF_ENABLE_DEPRECATION_WARNINGS
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:73
AV_LOG_WARNING
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:186
AVFrame::color_range
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: frame.h:656
AVPixelFormat
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
level
uint8_t level
Definition: svq3.c:204
FrameListData::pts
int64_t pts
time stamp to show frame (in timebase units)
Definition: libaomenc.c:58
av_clip
#define av_clip
Definition: common.h:96
AVCodecContext::keyint_min
int keyint_min
minimum GOP size
Definition: avcodec.h:994
vp9_init
static av_cold int vp9_init(AVFormatContext *ctx, int st_index, PayloadContext *data)
Definition: rtpdec_vp9.c:34
AVERROR
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining all references to the list are updated That means that if a filter requires that its input and output have the same format amongst a supported all it has to do is use a reference to the same list of formats query_formats can leave some formats unset and return AVERROR(EAGAIN) to cause the negotiation mechanism toagain later. That can be used by filters with complex requirements to use the format negotiated on one link to set the formats supported on another. Frame references ownership and permissions
opt.h
set_color_range
static void set_color_range(AVCodecContext *avctx)
Definition: libaomenc.c:508
AVCodecContext::colorspace
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:1029
FrameData
Definition: ffmpeg.h:636
av_frame_get_side_data
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition: frame.c:824
AVCodecContext::rc_min_rate
int64_t rc_min_rate
minimum bitrate
Definition: avcodec.h:1291
vp8_ts_parse_int_array
static void vp8_ts_parse_int_array(int *dest, char *value, size_t value_len, int max_entries)
Definition: libvpxenc.c:539
frame_data_uninit
static void frame_data_uninit(FrameData *fd)
Definition: libvpxenc.c:338
stats
static void stats(AVPacket *const *in, int n_in, unsigned *_max, unsigned *_sum)
Definition: vp9_superframe_bsf.c:34
AVFrame::duration
int64_t duration
Duration of the frame, in the same units as pts.
Definition: frame.h:807
av_pix_fmt_desc_get
const AVPixFmtDescriptor * av_pix_fmt_desc_get(enum AVPixelFormat pix_fmt)
Definition: pixdesc.c:2964
ff_side_data_set_encoder_stats
int ff_side_data_set_encoder_stats(AVPacket *pkt, int quality, int64_t *error, int error_count, int pict_type)
Definition: avpacket.c:603
AVBufferRef::data
uint8_t * data
The data buffer.
Definition: buffer.h:90
VPxEncoderContext::rawimg_alpha
struct vpx_image rawimg_alpha
Definition: libvpxenc.c:85
ff_libvpx_vp9_encoder
FFCodec ff_libvpx_vp9_encoder
av_unused
#define av_unused
Definition: attributes.h:131
AVCodec::pix_fmts
enum AVPixelFormat * pix_fmts
array of supported pixel formats, or NULL if unknown, array is terminated by -1
Definition: codec.h:209
AVFrame::opaque
void * opaque
Frame owner's private data.
Definition: frame.h:501
VPxEncoderContext
Definition: libvpxenc.c:80
VPxEncoderContext::is_alpha
uint8_t is_alpha
Definition: libvpxenc.c:86
av_fifo_peek
int av_fifo_peek(const AVFifo *f, void *buf, size_t nb_elems, size_t offset)
Read data from a FIFO without modifying FIFO state.
Definition: fifo.c:255
VPxEncoderContext::rawimg
struct vpx_image rawimg
Definition: libvpxenc.c:83
AVFrame
This structure describes decoded (raw) audio or video data.
Definition: frame.h:340
tmp
static uint8_t tmp[11]
Definition: aes_ctr.c:28
pixdesc.h
AVFrame::pts
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:452
AVCodecContext::color_trc
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:1022
AVFrame::width
int width
Definition: frame.h:412
AVCOL_RANGE_JPEG
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:673
internal.h
AVPacket::data
uint8_t * data
Definition: packet.h:491
VP8F_ERROR_RESILIENT
#define VP8F_ERROR_RESILIENT
Enable measures appropriate for streaming over lossy links.
Definition: libvpxenc.c:101
AVOption
AVOption.
Definition: opt.h:251
encode.h
set_pix_fmt
static int set_pix_fmt(AVCodecContext *avctx, struct aom_image *img)
Definition: libaomdec.c:65
data
const char data[16]
Definition: mxf.c:148
AV_PIX_FMT_YUV420P10
#define AV_PIX_FMT_YUV420P10
Definition: pixfmt.h:468
FF_CODEC_CAP_NOT_INIT_THREADSAFE
#define FF_CODEC_CAP_NOT_INIT_THREADSAFE
The codec is not known to be init-threadsafe (i.e.
Definition: codec_internal.h:34
FFCodec
Definition: codec_internal.h:127
AV_LOG_VERBOSE
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:196
AVCOL_SPC_RGB
@ AVCOL_SPC_RGB
order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1
Definition: pixfmt.h:600
VP8F_AUTO_ALT_REF
#define VP8F_AUTO_ALT_REF
Enable automatic alternate reference frame generation.
Definition: libvpxenc.c:102
AVPacket::duration
int64_t duration
Duration of this packet in AVStream->time_base units, 0 if unknown.
Definition: packet.h:509
VPxEncoderContext::have_sse
int have_sse
true if we have pending sse[]
Definition: libvpxenc.c:91
AV_PIX_FMT_YUV440P
@ AV_PIX_FMT_YUV440P
planar YUV 4:4:0 (1 Cr & Cb sample per 1x2 Y samples)
Definition: pixfmt.h:99
mathematics.h
AVDictionary
Definition: dict.c:34
AV_CODEC_FLAG_PSNR
#define AV_CODEC_FLAG_PSNR
error[?] variables will be set during encoding.
Definition: avcodec.h:322
av_buffer_ref
AVBufferRef * av_buffer_ref(const AVBufferRef *buf)
Create a new reference to an AVBuffer.
Definition: buffer.c:103
VPxEncoderContext::fifo
AVFifo * fifo
Definition: libvpxenc.c:141
VPxEncoderContext::level
float level
Definition: libvpxenc.c:133
AVCodecContext::qmax
int qmax
maximum quantizer
Definition: avcodec.h:1255
VPxEncoderContext::aq_mode
int aq_mode
Definition: libvpxenc.c:129
AV_PKT_FLAG_KEY
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:546
quality
trying all byte sequences megabyte in length and selecting the best looking sequence will yield cases to try But a word about quality
Definition: rate_distortion.txt:12
AV_WB64
#define AV_WB64(p, v)
Definition: intreadwrite.h:431
AVFrame::data
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:361
av_malloc
#define av_malloc(s)
Definition: tableprint_vlc.h:30
AVFrame::opaque_ref
AVBufferRef * opaque_ref
Frame owner's private data.
Definition: frame.h:768
VPxEncoderContext::encoder_alpha
struct vpx_codec_ctx encoder_alpha
Definition: libvpxenc.c:84
AVCodecContext::framerate
AVRational framerate
Definition: avcodec.h:1803
AVCOL_SPC_BT470BG
@ AVCOL_SPC_BT470BG
also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601
Definition: pixfmt.h:605
VPxEncoderContext::auto_alt_ref
int auto_alt_ref
Definition: libvpxenc.c:104
AVCOL_SPC_RESERVED
@ AVCOL_SPC_RESERVED
reserved for future use by ITU-T and ISO/IEC just like 15-255 are
Definition: pixfmt.h:603
FrameListData::flags
uint32_t flags
flags for this frame
Definition: libaomenc.c:62
VPxEncoderContext::coded_frame_list
struct FrameListData * coded_frame_list
Definition: libvpxenc.c:92
AV_CODEC_FLAG_COPY_OPAQUE
#define AV_CODEC_FLAG_COPY_OPAQUE
Definition: avcodec.h:295
fifo.h
FFCodecDefault
Definition: codec_internal.h:97
FFCodec::p
AVCodec p
The public AVCodec.
Definition: codec_internal.h:131
VPxEncoderContext::deadline
int deadline
Definition: libvpxenc.c:89
AVPacket::opaque_ref
AVBufferRef * opaque_ref
AVBufferRef for free use by the API user.
Definition: packet.h:527
fail
#define fail()
Definition: checkasm.h:138
av_fifo_write
int av_fifo_write(AVFifo *f, const void *buf, size_t nb_elems)
Write data into a FIFO.
Definition: fifo.c:188
AVCodecContext::thread_count
int thread_count
thread count is used to decide how many independent tasks should be passed to execute()
Definition: avcodec.h:1532
AV_PIX_FMT_GBRP10
#define AV_PIX_FMT_GBRP10
Definition: pixfmt.h:484
VPxEncoderContext::drop_threshold
int drop_threshold
Definition: libvpxenc.c:130
set_vp8_defaults
static void set_vp8_defaults(AVCodecContext *avctx, struct vpx_codec_enc_cfg *enccfg)
Set the target bitrate to VPX library default.
Definition: libvpxenc.c:914
VPxEncoderContext::roi_warned
int roi_warned
If the driver does not support ROI then warn the first time we encounter a frame with ROI side data.
Definition: libvpxenc.c:146
AVCodecContext::flags
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:521
codecctl_int
static av_cold int codecctl_int(AVCodecContext *avctx, enum vp8e_enc_control_id id, int val)
Definition: libvpxenc.c:443
realloc_alpha_uv
static int realloc_alpha_uv(AVCodecContext *avctx, int width, int height)
Definition: libvpxenc.c:1655
val
static double val(void *priv, double ch)
Definition: aeval.c:78
vpx_ts_param_parse
static int vpx_ts_param_parse(VPxContext *ctx, struct vpx_codec_enc_cfg *enccfg, char *key, char *value, enum AVCodecID codec_id)
Definition: libvpxenc.c:669
VPxEncoderContext::max_intra_rate
int max_intra_rate
Definition: libvpxenc.c:116
FF_CODEC_ENCODE_CB
#define FF_CODEC_ENCODE_CB(func)
Definition: codec_internal.h:315
AVRational::num
int num
Numerator.
Definition: rational.h:59
LEGACY_OPTIONS
#define LEGACY_OPTIONS
Definition: libvpxenc.c:1931
AV_PIX_FMT_YUV444P10
#define AV_PIX_FMT_YUV444P10
Definition: pixfmt.h:471
vpx_encode
static int vpx_encode(AVCodecContext *avctx, AVPacket *pkt, const AVFrame *frame, int *got_packet)
Definition: libvpxenc.c:1683
avassert.h
lrint
#define lrint
Definition: tablegen.h:53
pkt
AVPacket * pkt
Definition: movenc.c:59
AV_LOG_ERROR
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:180
AVFrameSideData::size
size_t size
Definition: frame.h:249
av_cold
#define av_cold
Definition: attributes.h:90
AVRegionOfInterest
Structure describing a single Region Of Interest.
Definition: frame.h:265
AV_PROFILE_UNKNOWN
#define AV_PROFILE_UNKNOWN
Definition: defs.h:65
av_fifo_read
int av_fifo_read(AVFifo *f, void *buf, size_t nb_elems)
Read data from a FIFO.
Definition: fifo.c:240
AVCodecContext::rc_initial_buffer_occupancy
int rc_initial_buffer_occupancy
Number of bits which should be loaded into the rc buffer before decoding starts.
Definition: avcodec.h:1312
duration
int64_t duration
Definition: movenc.c:64
av_dict_get
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:62
AVFrame::reordered_opaque
attribute_deprecated int64_t reordered_opaque
reordered opaque 64 bits (generally an integer or a double precision float PTS but can be anything).
Definition: frame.h:561
av_fast_realloc
void * av_fast_realloc(void *ptr, unsigned int *size, size_t min_size)
Reallocate the given buffer if it is not large enough, otherwise do nothing.
Definition: mem.c:495
width
#define width
intreadwrite.h
AVCodecContext::stats_in
char * stats_in
pass2 encoding statistics input buffer Concatenated stuff from stats_out of pass1 should be placed he...
Definition: avcodec.h:1334
AV_PIX_FMT_YUVA420P
@ AV_PIX_FMT_YUVA420P
planar YUV 4:2:0, 20bpp, (1 Cr & Cb sample per 2x2 Y & A samples)
Definition: pixfmt.h:101
COMMON_OPTIONS
#define COMMON_OPTIONS
Definition: libvpxenc.c:1900
AVRegionOfInterest::bottom
int bottom
Definition: frame.h:281
AVFormatContext::flags
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1233
vpx_init
static av_cold int vpx_init(AVCodecContext *avctx, const struct vpx_codec_iface *iface)
Definition: libvpxenc.c:971
AVCOL_SPC_SMPTE170M
@ AVCOL_SPC_SMPTE170M
also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above
Definition: pixfmt.h:606
log_encoder_error
static av_cold void log_encoder_error(AVCodecContext *avctx, const char *desc)
Definition: libvpxenc.c:202
AVDictionaryEntry::key
char * key
Definition: dict.h:90
AV_CODEC_ID_VP9
@ AV_CODEC_ID_VP9
Definition: codec_id.h:220
AV_CODEC_CAP_OTHER_THREADS
#define AV_CODEC_CAP_OTHER_THREADS
Codec supports multithreading through a method other than slice- or frame-level multithreading.
Definition: codec.h:124
av_strtok
char * av_strtok(char *s, const char *delim, char **saveptr)
Split the string into several tokens which can be accessed by successive calls to av_strtok().
Definition: avstring.c:178
VPxEncoderContext::row_mt
int row_mt
Definition: libvpxenc.c:134
init
int(* init)(AVBSFContext *ctx)
Definition: dts2pts_bsf.c:365
FrameListData::sse
uint64_t sse[4]
Definition: libaomenc.c:63
AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE
#define AV_CODEC_CAP_ENCODER_REORDERED_OPAQUE
This encoder can reorder user opaque values from input AVFrames and return them with corresponding ou...
Definition: codec.h:159
VPxEncoderContext::lag_in_frames
int lag_in_frames
Definition: libvpxenc.c:112
tile_rows
int tile_rows
Definition: h265_levels.c:217
av_assert0
#define av_assert0(cond)
assert() equivalent, that is always enabled.
Definition: avassert.h:40
AV_LOG_DEBUG
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:201
VPxEncoderContext::arnr_type
int arnr_type
Definition: libvpxenc.c:108
ctx
AVFormatContext * ctx
Definition: movenc.c:48
MAX_DELTA_Q
#define MAX_DELTA_Q
av_rescale_q
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq)
Rescale a 64-bit integer by 2 rational numbers.
Definition: mathematics.c:142
VPxEncoderContext::static_thresh
int static_thresh
Definition: libvpxenc.c:115
codec_id
enum AVCodecID codec_id
Definition: vaapi_decode.c:389
AV_PIX_FMT_YUV420P
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:66
VPxEncoderContext::rc_undershoot_pct
int rc_undershoot_pct
Definition: libvpxenc.c:117
AVCodecContext::rc_max_rate
int64_t rc_max_rate
maximum bitrate
Definition: avcodec.h:1284
AVCodecContext::error
uint64_t error[AV_NUM_DATA_POINTERS]
error
Definition: avcodec.h:1466
key
const char * key
Definition: hwcontext_opencl.c:174
MAX_VPX_THREADS
#define MAX_VPX_THREADS
Definition: libvpx.h:24
cx_pktcpy
static void cx_pktcpy(struct FrameListData *dst, const struct vpx_codec_cx_pkt *src, VPxContext *ctx)
Definition: libvpxenc.c:1291
VPxEncoderContext::current_temporal_idx
int current_temporal_idx
Definition: libvpxenc.c:122
AVPacket::opaque
void * opaque
for some private data of the user
Definition: packet.h:516
AVCPBProperties
This structure describes the bitrate properties of an encoded bitstream.
Definition: defs.h:269
CODEC_LONG_NAME
#define CODEC_LONG_NAME(str)
Definition: codec_internal.h:272
frame
static AVFrame * frame
Definition: demux_decode.c:54
AVCodecContext::codec_id
enum AVCodecID codec_id
Definition: avcodec.h:451
if
if(ret)
Definition: filter_design.txt:179
set_vpx_defaults
static void set_vpx_defaults(AVCodecContext *avctx, struct vpx_codec_enc_cfg *enccfg)
Called when the bitrate is not set.
Definition: libvpxenc.c:958
AVCodecContext::rc_buffer_size
int rc_buffer_size
decoder bitstream buffer size
Definition: avcodec.h:1269
VPxEncoderContext::ts_layer_flags
int * ts_layer_flags
Definition: libvpxenc.c:121
LIBAVUTIL_VERSION_INT
#define LIBAVUTIL_VERSION_INT
Definition: version.h:85
AVClass
Describe the class of an AVClass context structure.
Definition: log.h:66
NULL
#define NULL
Definition: coverity.c:32
AVCodecContext::color_range
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:1039
av_buffer_unref
void av_buffer_unref(AVBufferRef **buf)
Free a given reference and automatically free the buffer if there are no more references to it.
Definition: buffer.c:139
frame_data_apply
static int frame_data_apply(AVCodecContext *avctx, AVFifo *fifo, AVPacket *pkt)
Definition: libvpxenc.c:398
VPxEncoderContext::twopass_stats
struct vpx_fixed_buf twopass_stats
Definition: libvpxenc.c:87
vpx_free
static av_cold int vpx_free(AVCodecContext *avctx)
Definition: libvpxenc.c:509
delta_q
#define delta_q(name)
Definition: cbs_av1.c:625
AVCodecContext::bit_rate
int64_t bit_rate
the average bitrate
Definition: avcodec.h:491
FrameData::duration
int64_t duration
Definition: librav1e.c:59
AVRegionOfInterest::self_size
uint32_t self_size
Must be set to the size of this data structure (that is, sizeof(AVRegionOfInterest)).
Definition: frame.h:270
av_default_item_name
const char * av_default_item_name(void *ptr)
Return the context name.
Definition: log.c:237
AV_PICTURE_TYPE_I
@ AV_PICTURE_TYPE_I
Intra.
Definition: avutil.h:279
profiles.h
AV_PIX_FMT_YUV440P10
#define AV_PIX_FMT_YUV440P10
Definition: pixfmt.h:470
list
Filter the word “frame” indicates either a video frame or a group of audio as stored in an AVFrame structure Format for each input and each output the list of supported formats For video that means pixel format For audio that means channel sample they are references to shared objects When the negotiation mechanism computes the intersection of the formats supported at each end of a all references to both lists are replaced with a reference to the intersection And when a single format is eventually chosen for a link amongst the remaining list
Definition: filter_design.txt:25
VPxEncoderContext::noise_sensitivity
int noise_sensitivity
Definition: libvpxenc.c:131
FrameData::frame_opaque
void * frame_opaque
Definition: librav1e.c:64
FrameListData::buf
void * buf
compressed data buffer
Definition: libaomenc.c:56
AV_ROUND_NEAR_INF
@ AV_ROUND_NEAR_INF
Round to nearest and halfway cases away from zero.
Definition: mathematics.h:135
VPxEncoderContext::crf
int crf
Definition: libvpxenc.c:114
VPxEncoderContext::tpl_model
int tpl_model
Definition: libvpxenc.c:137
AV_PIX_FMT_YUV422P10
#define AV_PIX_FMT_YUV422P10
Definition: pixfmt.h:469
av_base64_decode
int av_base64_decode(uint8_t *out, const char *in_str, int out_size)
Decode a base64-encoded string.
Definition: base64.c:81
VPxEncoderContext::encoder
struct vpx_codec_ctx encoder
Definition: libvpxenc.c:82
VPxEncoderContext::flags
int flags
VP8 specific flags, see VP8F_* below.
Definition: libvpxenc.c:100
base64.h
AVCOL_RANGE_UNSPECIFIED
@ AVCOL_RANGE_UNSPECIFIED
Definition: pixfmt.h:639
free_frame_list
static av_cold void free_frame_list(struct FrameListData *list)
Definition: libvpxenc.c:327
AVCodecID
AVCodecID
Identify the syntax and semantics of the bitstream.
Definition: codec_id.h:49
vp8_encode_set_roi
static int vp8_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd)
Definition: libvpxenc.c:1633
av_cpu_count
int av_cpu_count(void)
Definition: cpu.c:209
AVCodecContext::qcompress
float qcompress
amount of qscale change between easy & hard scenes (0.0-1.0)
Definition: avcodec.h:1240
AVCodecContext::time_base
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:563
AVCOL_TRC_SMPTE2084
@ AVCOL_TRC_SMPTE2084
SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems.
Definition: pixfmt.h:587
av_rescale_rnd
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:58
FrameListData::next
struct FrameListData * next
Definition: libaomenc.c:66
AVCodecContext::stats_out
char * stats_out
pass1 encoding statistics output buffer
Definition: avcodec.h:1326
VPxEncoderContext::rc_overshoot_pct
int rc_overshoot_pct
Definition: libvpxenc.c:118
AVFrame::pict_type
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:442
AV_CODEC_CAP_DR1
#define AV_CODEC_CAP_DR1
Codec uses get_buffer() or get_encode_buffer() for allocating buffers and supports custom allocators.
Definition: codec.h:52
AVPacket::size
int size
Definition: packet.h:492
AVFifo
Definition: fifo.c:35
NULL_IF_CONFIG_SMALL
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification.
Definition: internal.h:106
AVCodecContext::gop_size
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition: avcodec.h:643
codec_internal.h
AV_PKT_DATA_DYNAMIC_HDR10_PLUS
@ AV_PKT_DATA_DYNAMIC_HDR10_PLUS
HDR10+ dynamic metadata associated with a video frame.
Definition: packet.h:300
cpu.h
FrameData::hdr10_plus
AVBufferRef * hdr10_plus
Definition: libvpxenc.c:77
fifo_free
static av_cold void fifo_free(AVFifo **fifo)
Definition: libvpxenc.c:344
AV_PIX_FMT_YUV422P12
#define AV_PIX_FMT_YUV422P12
Definition: pixfmt.h:473
size
int size
Definition: twinvq_data.h:10344
VPxEncoderContext::lossless
int lossless
Definition: libvpxenc.c:125
av_reallocp
int av_reallocp(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory through a pointer to a pointer.
Definition: mem.c:186
AV_PIX_FMT_YUV444P12
#define AV_PIX_FMT_YUV444P12
Definition: pixfmt.h:475
AVFrameSideData::data
uint8_t * data
Definition: frame.h:248
VPxEncoderContext::tune_content
int tune_content
Definition: libvpxenc.c:135
VPxEncoderContext::corpus_complexity
int corpus_complexity
Definition: libvpxenc.c:136
VPxEncoderContext::tile_rows
int tile_rows
Definition: libvpxenc.c:127
AVCPBProperties::min_bitrate
int64_t min_bitrate
Minimum bitrate of the stream, in bits per second.
Definition: defs.h:279
FrameListData
Portion of struct vpx_codec_cx_pkt from vpx_encoder.h.
Definition: libaomenc.c:55
VPxEncoderContext::sharpness
int sharpness
Definition: libvpxenc.c:96
vp9_encode_set_roi
static int vp9_encode_set_roi(AVCodecContext *avctx, int frame_width, int frame_height, const AVFrameSideData *sd)
Definition: libvpxenc.c:1583
AVPacket::dts
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:490
AV_CODEC_FLAG_PASS2
#define AV_CODEC_FLAG_PASS2
Use internal 2pass ratecontrol in second pass mode.
Definition: avcodec.h:310
height
#define height
FrameData::pts
int64_t pts
Definition: ffmpeg.h:641
AVPacket::flags
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:497
FrameData::frame_opaque_ref
AVBufferRef * frame_opaque_ref
Definition: librav1e.c:65
AVCPBProperties::avg_bitrate
int64_t avg_bitrate
Average bitrate of the stream, in bits per second.
Definition: defs.h:284
version
version
Definition: libkvazaar.c:321
AVRegionOfInterest::right
int right
Definition: frame.h:283
VPxEncoderContext::tune
int tune
Definition: libvpxenc.c:110
AVBufferRef::size
size_t size
Size of data in bytes.
Definition: buffer.h:94
AV_LOG_INFO
#define AV_LOG_INFO
Standard information.
Definition: log.h:191
AV_OPT_TYPE_FLOAT
@ AV_OPT_TYPE_FLOAT
Definition: opt.h:228
AVCOL_SPC_SMPTE240M
@ AVCOL_SPC_SMPTE240M
derived from 170M primaries and D65 white point, 170M is derived from BT470 System M's primaries
Definition: pixfmt.h:607
frame_data_submit
static int frame_data_submit(AVCodecContext *avctx, AVFifo *fifo, const AVFrame *frame)
Definition: libvpxenc.c:352
VPxEncoderContext::twopass_stats_size
unsigned twopass_stats_size
Definition: libvpxenc.c:88
AVRegionOfInterest::left
int left
Definition: frame.h:282
AV_BASE64_SIZE
#define AV_BASE64_SIZE(x)
Calculate the output size needed to base64-encode x bytes to a null-terminated string.
Definition: base64.h:66
VPxEncoderContext::vpx_ts_parameters
AVDictionary * vpx_ts_parameters
Definition: libvpxenc.c:120
VPxEncoderContext::tile_columns
int tile_columns
Definition: libvpxenc.c:126
i
#define i(width, name, range_min, range_max)
Definition: cbs_h2645.c:255
AVPacket::pts
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:484
AVCOL_SPC_BT2020_NCL
@ AVCOL_SPC_BT2020_NCL
ITU-R BT2020 non-constant luminance system.
Definition: pixfmt.h:610
AVRegionOfInterest::top
int top
Distance in pixels from the top edge of the frame to the top and bottom edges and from the left edge ...
Definition: frame.h:280
internal.h
AV_PIX_FMT_GBRP12
#define AV_PIX_FMT_GBRP12
Definition: pixfmt.h:485
av_malloc_array
#define av_malloc_array(a, b)
Definition: tableprint_vlc.h:31
common.h
AVCPBProperties::max_bitrate
int64_t max_bitrate
Maximum bitrate of the stream, in bits per second.
Definition: defs.h:274
planes
static const struct @363 planes[]
value
it s the only field you need to keep assuming you have a context There is some magic you don t need to care about around this just let it vf default value
Definition: writing_filters.txt:86
FFMIN
#define FFMIN(a, b)
Definition: macros.h:49
AVCodec::name
const char * name
Name of the codec implementation.
Definition: codec.h:194
av_inv_q
static av_always_inline AVRational av_inv_q(AVRational q)
Invert a rational.
Definition: rational.h:159
av_buffer_replace
int av_buffer_replace(AVBufferRef **pdst, const AVBufferRef *src)
Ensure dst refers to the same data as src.
Definition: buffer.c:233
AVCOL_SPC_UNSPECIFIED
@ AVCOL_SPC_UNSPECIFIED
Definition: pixfmt.h:602
AVCodecContext::height
int height
Definition: avcodec.h:621
AVCodecContext::pix_fmt
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:658
AVCOL_RANGE_MPEG
@ AVCOL_RANGE_MPEG
Narrow or limited range content.
Definition: pixfmt.h:656
av_calloc
void * av_calloc(size_t nmemb, size_t size)
Definition: mem.c:262
defaults
static const FFCodecDefault defaults[]
Definition: libvpxenc.c:2009
avcodec.h
stride
#define stride
Definition: h264pred_template.c:537
av_uninit
#define av_uninit(x)
Definition: attributes.h:154
AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL
@ AV_PKT_DATA_MATROSKA_BLOCKADDITIONAL
Data found in BlockAdditional element of matroska container.
Definition: packet.h:192
ret
ret
Definition: filter_design.txt:187
AVClass::class_name
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:71
AVCPBProperties::buffer_size
int64_t buffer_size
The size of the buffer to which the ratecontrol is applied, in bits.
Definition: defs.h:290
VPxEncoderContext::cpu_used
int cpu_used
Definition: libvpxenc.c:95
VPxEncoderContext::alpha_coded_frame_list
struct FrameListData * alpha_coded_frame_list
Definition: libvpxenc.c:93
av_fifo_alloc2
AVFifo * av_fifo_alloc2(size_t nb_elems, size_t elem_size, unsigned int flags)
Allocate and initialize an AVFifo with a given element size.
Definition: fifo.c:47
AV_PIX_FMT_YUV420P12
#define AV_PIX_FMT_YUV420P12
Definition: pixfmt.h:472
SIZE_SPECIFIER
#define SIZE_SPECIFIER
Definition: internal.h:141
AV_FRAME_DATA_DYNAMIC_HDR_PLUS
@ AV_FRAME_DATA_DYNAMIC_HDR_PLUS
HDR dynamic metadata associated with a video frame.
Definition: frame.h:159
AVCodecContext
main external API structure.
Definition: avcodec.h:441
AVFrame::height
int height
Definition: frame.h:412
av_packet_new_side_data
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, size_t size)
Allocate new information of a packet.
Definition: avpacket.c:231
ff_get_encode_buffer
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition: encode.c:105
AVCodecContext::qmin
int qmin
minimum quantizer
Definition: avcodec.h:1248
AVRational::den
int den
Denominator.
Definition: rational.h:60
storeframe
static int storeframe(AVCodecContext *avctx, struct FrameListData *cx_frame, struct FrameListData *alpha_cx_frame, AVPacket *pkt)
Store coded frame information in format suitable for return from encode2().
Definition: libvpxenc.c:1321
AV_PIX_FMT_NONE
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
AV_OPT_TYPE_INT
@ AV_OPT_TYPE_INT
Definition: opt.h:225
AVCodecContext::profile
int profile
profile
Definition: avcodec.h:1596
av_get_token
char * av_get_token(const char **buf, const char *term)
Unescape the given string until a non escaped terminating char, and return the token corresponding to...
Definition: avstring.c:143
AVFrame::metadata
AVDictionary * metadata
metadata.
Definition: frame.h:708
ctlidstr
static const char *const ctlidstr[]
String mappings for enum vp8e_enc_control_id.
Definition: libvpxenc.c:153
AVCodecContext::ticks_per_frame
attribute_deprecated int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:579
av_base64_encode
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:145
AV_CODEC_CAP_DELAY
#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: codec.h:76
VPxEncoderContext::frame_parallel
int frame_parallel
Definition: libvpxenc.c:128
ff_libvpx_vp8_encoder
const FFCodec ff_libvpx_vp8_encoder
AV_PIX_FMT_YUV444P
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:71
VPxEncoderContext::error_resilient
int error_resilient
Definition: libvpxenc.c:113
FF_DISABLE_DEPRECATION_WARNINGS
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:72
AV_PIX_FMT_GBRP
@ AV_PIX_FMT_GBRP
planar GBR 4:4:4 24bpp
Definition: pixfmt.h:158
OFFSET
#define OFFSET(x)
Definition: libvpxenc.c:1897
desc
const char * desc
Definition: libsvtav1.c:83
AV_PICTURE_TYPE_P
@ AV_PICTURE_TYPE_P
Predicted.
Definition: avutil.h:280
AVMEDIA_TYPE_VIDEO
@ AVMEDIA_TYPE_VIDEO
Definition: avutil.h:201
coded_frame_add
static void coded_frame_add(void *list, struct FrameListData *cx_frame)
Definition: libvpxenc.c:311
AV_PIX_FMT_YUV422P
@ AV_PIX_FMT_YUV422P
planar YUV 4:2:2, 16bpp, (1 Cr & Cb sample per 2x1 Y samples)
Definition: pixfmt.h:70
AVBufferRef
A reference to a data buffer.
Definition: buffer.h:82
packet_internal.h
FF_CODEC_CAP_AUTO_THREADS
#define FF_CODEC_CAP_AUTO_THREADS
Codec handles avctx->thread_count == 0 (auto) internally.
Definition: codec_internal.h:73
AVFrameSideData
Structure to hold side data for an AVFrame.
Definition: frame.h:246
AVPixFmtDescriptor
Descriptor that unambiguously describes how the bits of a pixel are stored in the up to 4 data planes...
Definition: pixdesc.h:69
set_temporal_layer_pattern
static void set_temporal_layer_pattern(int layering_mode, vpx_codec_enc_cfg_t *cfg, int *layer_flags, int *flag_periodicity)
Definition: libvpxenc.c:565
dump_enc_cfg
static av_cold void dump_enc_cfg(AVCodecContext *avctx, const struct vpx_codec_enc_cfg *cfg, int level)
Definition: libvpxenc.c:213
AVDictionaryEntry
Definition: dict.h:89
VPxEncoderContext::arnr_max_frames
int arnr_max_frames
Definition: libvpxenc.c:106
AVCodecContext::slices
int slices
Number of slices.
Definition: avcodec.h:1055
AVPacket
This structure stores compressed data.
Definition: packet.h:468
AVCodecContext::priv_data
void * priv_data
Definition: avcodec.h:468
VPxEncoderContext::vpx_cs
int vpx_cs
Definition: libvpxenc.c:132
AV_OPT_TYPE_BOOL
@ AV_OPT_TYPE_BOOL
Definition: opt.h:244
av_freep
#define av_freep(p)
Definition: tableprint_vlc.h:34
src
INIT_CLIP pixel * src
Definition: h264pred_template.c:418
set_roi_map
static int set_roi_map(AVCodecContext *avctx, const AVFrameSideData *sd, int frame_width, int frame_height, vpx_roi_map_t *roi_map, int block_size, int segment_cnt)
Definition: libvpxenc.c:1476
queue_frames
static int queue_frames(AVCodecContext *avctx, struct vpx_codec_ctx *encoder, struct FrameListData **frame_list, AVPacket *pkt_out)
Queue multiple output frames from the encoder, returning the front-most.
Definition: libvpxenc.c:1381
AVCodecContext::width
int width
picture width / height.
Definition: avcodec.h:621
AV_FRAME_DATA_REGIONS_OF_INTEREST
@ AV_FRAME_DATA_REGIONS_OF_INTEREST
Regions Of Interest, the data is an array of AVRegionOfInterest type, the number of array element is ...
Definition: frame.h:165
AV_CODEC_ID_VP8
@ AV_CODEC_ID_VP8
Definition: codec_id.h:192
flags
#define flags(name, subs,...)
Definition: cbs_av1.c:474
AVFrame::linesize
int linesize[AV_NUM_DATA_POINTERS]
For video, a positive or negative value, which is typically indicating the size in bytes of each pict...
Definition: frame.h:385
av_log
#define av_log(a,...)
Definition: tableprint_vlc.h:27
FrameListData::sz
size_t sz
length of compressed data
Definition: libaomenc.c:57
av_fifo_freep2
void av_fifo_freep2(AVFifo **f)
Free an AVFifo and reset pointer to NULL.
Definition: fifo.c:286
AVERROR_INVALIDDATA
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition: error.h:61
libvpx.h
AV_PIX_FMT_YUV440P12
#define AV_PIX_FMT_YUV440P12
Definition: pixfmt.h:474
free_coded_frame
static av_cold void free_coded_frame(struct FrameListData *cx_frame)
Definition: libvpxenc.c:321
VPxEncoderContext::arnr_strength
int arnr_strength
Definition: libvpxenc.c:107
vp8_init
static av_cold int vp8_init(AVFormatContext *s, int st_index, PayloadContext *vp8)
Definition: rtpdec_vp8.c:263
ff_encode_add_cpb_side_data
AVCPBProperties * ff_encode_add_cpb_side_data(AVCodecContext *avctx)
Add a CPB properties side data to an encoding context.
Definition: encode.c:870
AVDictionaryEntry::value
char * value
Definition: dict.h:91
avstring.h
FF_QP2LAMBDA
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
AVCOL_SPC_BT709
@ AVCOL_SPC_BT709
also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / derived in SMPTE RP 177 Annex B
Definition: pixfmt.h:601
VE
#define VE
Definition: libvpxenc.c:1898
int
int
Definition: ffmpeg_filter.c:368
AVRegionOfInterest::qoffset
AVRational qoffset
Quantisation offset.
Definition: frame.h:307
AV_OPT_TYPE_CONST
@ AV_OPT_TYPE_CONST
Definition: opt.h:234
snprintf
#define snprintf
Definition: snprintf.h:34
av_log2
int av_log2(unsigned v)
Definition: intmath.c:26
VPxEncoderContext::sse
uint64_t sse[4]
Definition: libvpxenc.c:90
av_dict_iterate
const AVDictionaryEntry * av_dict_iterate(const AVDictionary *m, const AVDictionaryEntry *prev)
Iterate over a dictionary.
Definition: dict.c:44
skip
static void BS_FUNC() skip(BSCTX *bc, unsigned int n)
Skip n bits in the buffer.
Definition: bitstream_template.h:375
AV_FIFO_FLAG_AUTO_GROW
#define AV_FIFO_FLAG_AUTO_GROW
Automatically resize the FIFO on writes, so that the data fits.
Definition: fifo.h:67
ff_vp9_profiles
const AVProfile ff_vp9_profiles[]
Definition: profiles.c:152
AV_CODEC_FLAG_PASS1
#define AV_CODEC_FLAG_PASS1
Use internal 2pass ratecontrol in first pass mode.
Definition: avcodec.h:306
VPxEncoderContext::min_gf_interval
int min_gf_interval
Definition: libvpxenc.c:138
FrameListData::have_sse
int have_sse
true if we have pending sse[]
Definition: libaomenc.c:64