FFmpeg  4.4.9
nvenc.c
Go to the documentation of this file.
1 /*
2  * H.264/HEVC hardware encoding using nvidia nvenc
3  * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21 
22 #include "config.h"
23 
24 #include "nvenc.h"
25 #include "hevc_sei.h"
26 
28 #include "libavutil/hwcontext.h"
29 #include "libavutil/cuda_check.h"
30 #include "libavutil/imgutils.h"
31 #include "libavutil/avassert.h"
32 #include "libavutil/mem.h"
33 #include "libavutil/pixdesc.h"
34 #include "atsc_a53.h"
35 #include "encode.h"
36 #include "internal.h"
37 #include "packet_internal.h"
38 
39 #define CHECK_CU(x) FF_CUDA_CHECK_DL(avctx, dl_fn->cuda_dl, x)
40 
41 #define NVENC_CAP 0x30
42 
43 #ifndef NVENC_NO_DEPRECATED_RC
44 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
45  rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
46  rc == NV_ENC_PARAMS_RC_CBR_HQ)
47 #else
48 #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR)
49 #endif
50 
51 const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
56  AV_PIX_FMT_P016, // Truncated to 10bits
57  AV_PIX_FMT_YUV444P16, // Truncated to 10bits
61 #if CONFIG_D3D11VA
63 #endif
65 };
66 
68  HW_CONFIG_ENCODER_FRAMES(CUDA, CUDA),
70 #if CONFIG_D3D11VA
71  HW_CONFIG_ENCODER_FRAMES(D3D11, D3D11VA),
73 #endif
74  NULL,
75 };
76 
77 #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
78  pix_fmt == AV_PIX_FMT_P016 || \
79  pix_fmt == AV_PIX_FMT_YUV444P16)
80 
81 #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
82  pix_fmt == AV_PIX_FMT_YUV444P16)
83 
84 static const struct {
85  NVENCSTATUS nverr;
86  int averr;
87  const char *desc;
88 } nvenc_errors[] = {
89  { NV_ENC_SUCCESS, 0, "success" },
90  { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
91  { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
92  { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
93  { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
94  { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
95  { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
96  { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
97  { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
98  { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
99  { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
100  { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
101  { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
102  { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
103  { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
104  { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
105  { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
106  { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
107  { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
108  { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
109  { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
110  { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
111  { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
112  { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
113  { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
114  { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
115 };
116 
117 static int nvenc_map_error(NVENCSTATUS err, const char **desc)
118 {
119  int i;
120  for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
121  if (nvenc_errors[i].nverr == err) {
122  if (desc)
123  *desc = nvenc_errors[i].desc;
124  return nvenc_errors[i].averr;
125  }
126  }
127  if (desc)
128  *desc = "unknown error";
129  return AVERROR_UNKNOWN;
130 }
131 
132 static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err,
133  const char *error_string)
134 {
135  const char *desc;
136  const char *details = "(no details)";
137  int ret = nvenc_map_error(err, &desc);
138 
139 #ifdef NVENC_HAVE_GETLASTERRORSTRING
140  NvencContext *ctx = avctx->priv_data;
141  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
142 
143  if (p_nvenc && ctx->nvencoder)
144  details = p_nvenc->nvEncGetLastErrorString(ctx->nvencoder);
145 #endif
146 
147  av_log(avctx, AV_LOG_ERROR, "%s: %s (%d): %s\n", error_string, desc, err, details);
148 
149  return ret;
150 }
151 
152 typedef struct GUIDTuple {
153  const GUID guid;
154  int flags;
155 } GUIDTuple;
156 
157 #define PRESET_ALIAS(alias, name, ...) \
158  [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
159 
160 #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
161 
163 {
164  GUIDTuple presets[] = {
165 #ifdef NVENC_HAVE_NEW_PRESETS
166  PRESET(P1),
167  PRESET(P2),
168  PRESET(P3),
169  PRESET(P4),
170  PRESET(P5),
171  PRESET(P6),
172  PRESET(P7),
173  PRESET_ALIAS(SLOW, P7, NVENC_TWO_PASSES),
174  PRESET_ALIAS(MEDIUM, P4, NVENC_ONE_PASS),
176  // Compat aliases
181  PRESET_ALIAS(LOW_LATENCY_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOWLATENCY),
184  PRESET_ALIAS(LOSSLESS_DEFAULT, P4, NVENC_DEPRECATED_PRESET | NVENC_LOSSLESS),
186 #else
187  PRESET(DEFAULT),
188  PRESET(HP),
189  PRESET(HQ),
190  PRESET(BD),
191  PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
192  PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
193  PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
194  PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
195  PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
196  PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
197  PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
198  PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
199 #endif
200  };
201 
202  GUIDTuple *t = &presets[ctx->preset];
203 
204  ctx->init_encode_params.presetGUID = t->guid;
205  ctx->flags = t->flags;
206 
207 #ifdef NVENC_HAVE_NEW_PRESETS
208  if (ctx->tuning_info == NV_ENC_TUNING_INFO_LOSSLESS)
210 #endif
211 }
212 
213 #undef PRESET
214 #undef PRESET_ALIAS
215 
217 {
218 #if NVENCAPI_CHECK_VERSION(11, 1)
219  const char *minver = "(unknown)";
220 #elif NVENCAPI_CHECK_VERSION(11, 0)
221 # if defined(_WIN32) || defined(__CYGWIN__)
222  const char *minver = "456.71";
223 # else
224  const char *minver = "455.28";
225 # endif
226 #elif NVENCAPI_CHECK_VERSION(10, 0)
227 # if defined(_WIN32) || defined(__CYGWIN__)
228  const char *minver = "450.51";
229 # else
230  const char *minver = "445.87";
231 # endif
232 #elif NVENCAPI_CHECK_VERSION(9, 1)
233 # if defined(_WIN32) || defined(__CYGWIN__)
234  const char *minver = "436.15";
235 # else
236  const char *minver = "435.21";
237 # endif
238 #elif NVENCAPI_CHECK_VERSION(9, 0)
239 # if defined(_WIN32) || defined(__CYGWIN__)
240  const char *minver = "418.81";
241 # else
242  const char *minver = "418.30";
243 # endif
244 #elif NVENCAPI_CHECK_VERSION(8, 2)
245 # if defined(_WIN32) || defined(__CYGWIN__)
246  const char *minver = "397.93";
247 # else
248  const char *minver = "396.24";
249 #endif
250 #elif NVENCAPI_CHECK_VERSION(8, 1)
251 # if defined(_WIN32) || defined(__CYGWIN__)
252  const char *minver = "390.77";
253 # else
254  const char *minver = "390.25";
255 # endif
256 #else
257 # if defined(_WIN32) || defined(__CYGWIN__)
258  const char *minver = "378.66";
259 # else
260  const char *minver = "378.13";
261 # endif
262 #endif
263  av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
264 }
265 
267 {
268  NvencContext *ctx = avctx->priv_data;
269  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
270  NVENCSTATUS err;
271  uint32_t nvenc_max_ver;
272  int ret;
273 
274  ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
275  if (ret < 0)
276  return ret;
277 
278  ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
279  if (ret < 0) {
281  return ret;
282  }
283 
284  err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
285  if (err != NV_ENC_SUCCESS)
286  return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
287 
288  av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
289 
290  if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
291  av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
292  "Required: %d.%d Found: %d.%d\n",
293  NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
294  nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
296  return AVERROR(ENOSYS);
297  }
298 
299  dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
300 
301  err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
302  if (err != NV_ENC_SUCCESS)
303  return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
304 
305  av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
306 
307  return 0;
308 }
309 
311 {
312  NvencContext *ctx = avctx->priv_data;
313  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
314 
315  if (ctx->d3d11_device)
316  return 0;
317 
318  return CHECK_CU(dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context));
319 }
320 
322 {
323  NvencContext *ctx = avctx->priv_data;
324  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
325  CUcontext dummy;
326 
327  if (ctx->d3d11_device)
328  return 0;
329 
330  return CHECK_CU(dl_fn->cuda_dl->cuCtxPopCurrent(&dummy));
331 }
332 
334 {
335  NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
336  NvencContext *ctx = avctx->priv_data;
337  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
338  NVENCSTATUS ret;
339 
340  params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
341  params.apiVersion = NVENCAPI_VERSION;
342  if (ctx->d3d11_device) {
343  params.device = ctx->d3d11_device;
344  params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
345  } else {
346  params.device = ctx->cu_context;
347  params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
348  }
349 
350  ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
351  if (ret != NV_ENC_SUCCESS) {
352  ctx->nvencoder = NULL;
353  return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
354  }
355 
356  return 0;
357 }
358 
360 {
361  NvencContext *ctx = avctx->priv_data;
362  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
363  int i, ret, count = 0;
364  GUID *guids = NULL;
365 
366  ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
367 
368  if (ret != NV_ENC_SUCCESS || !count)
369  return AVERROR(ENOSYS);
370 
371  guids = av_malloc(count * sizeof(GUID));
372  if (!guids)
373  return AVERROR(ENOMEM);
374 
375  ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
376  if (ret != NV_ENC_SUCCESS) {
377  ret = AVERROR(ENOSYS);
378  goto fail;
379  }
380 
381  ret = AVERROR(ENOSYS);
382  for (i = 0; i < count; i++) {
383  if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
384  ret = 0;
385  break;
386  }
387  }
388 
389 fail:
390  av_free(guids);
391 
392  return ret;
393 }
394 
395 static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
396 {
397  NvencContext *ctx = avctx->priv_data;
398  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
399  NV_ENC_CAPS_PARAM params = { 0 };
400  int ret, val = 0;
401 
402  params.version = NV_ENC_CAPS_PARAM_VER;
403  params.capsToQuery = cap;
404 
405  ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
406 
407  if (ret == NV_ENC_SUCCESS)
408  return val;
409  return 0;
410 }
411 
413 {
414  NvencContext *ctx = avctx->priv_data;
415  int ret;
416 
417  ret = nvenc_check_codec_support(avctx);
418  if (ret < 0) {
419  av_log(avctx, AV_LOG_WARNING, "Codec not supported\n");
420  return ret;
421  }
422 
423  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
424  if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
425  av_log(avctx, AV_LOG_WARNING, "YUV444P not supported\n");
426  return AVERROR(ENOSYS);
427  }
428 
429  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
430  if (ctx->flags & NVENC_LOSSLESS && ret <= 0) {
431  av_log(avctx, AV_LOG_WARNING, "Lossless encoding not supported\n");
432  return AVERROR(ENOSYS);
433  }
434 
435  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
436  if (ret < avctx->width) {
437  av_log(avctx, AV_LOG_WARNING, "Width %d exceeds %d\n",
438  avctx->width, ret);
439  return AVERROR(ENOSYS);
440  }
441 
442  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
443  if (ret < avctx->height) {
444  av_log(avctx, AV_LOG_WARNING, "Height %d exceeds %d\n",
445  avctx->height, ret);
446  return AVERROR(ENOSYS);
447  }
448 
449  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
450  if (ret < avctx->max_b_frames) {
451  av_log(avctx, AV_LOG_WARNING, "Max B-frames %d exceed %d\n",
452  avctx->max_b_frames, ret);
453 
454  return AVERROR(ENOSYS);
455  }
456 
457  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
458  if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
459  av_log(avctx, AV_LOG_WARNING,
460  "Interlaced encoding is not supported. Supported level: %d\n",
461  ret);
462  return AVERROR(ENOSYS);
463  }
464 
465  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
466  if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
467  av_log(avctx, AV_LOG_WARNING, "10 bit encode not supported\n");
468  return AVERROR(ENOSYS);
469  }
470 
471  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
472  if (ctx->rc_lookahead > 0 && ret <= 0) {
473  av_log(avctx, AV_LOG_WARNING, "RC lookahead not supported\n");
474  return AVERROR(ENOSYS);
475  }
476 
477  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
478  if (ctx->temporal_aq > 0 && ret <= 0) {
479  av_log(avctx, AV_LOG_WARNING, "Temporal AQ not supported\n");
480  return AVERROR(ENOSYS);
481  }
482 
483  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
484  if (ctx->weighted_pred > 0 && ret <= 0) {
485  av_log (avctx, AV_LOG_WARNING, "Weighted Prediction not supported\n");
486  return AVERROR(ENOSYS);
487  }
488 
489  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
490  if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
491  av_log(avctx, AV_LOG_WARNING, "CABAC entropy coding not supported\n");
492  return AVERROR(ENOSYS);
493  }
494 
495 #ifdef NVENC_HAVE_BFRAME_REF_MODE
496  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_BFRAME_REF_MODE);
497  if (ctx->b_ref_mode == NV_ENC_BFRAME_REF_MODE_EACH && ret != 1 && ret != 3) {
498  av_log(avctx, AV_LOG_WARNING, "Each B frame as reference is not supported\n");
499  return AVERROR(ENOSYS);
500  } else if (ctx->b_ref_mode != NV_ENC_BFRAME_REF_MODE_DISABLED && ret == 0) {
501  av_log(avctx, AV_LOG_WARNING, "B frames as references are not supported\n");
502  return AVERROR(ENOSYS);
503  }
504 #else
505  if (ctx->b_ref_mode != 0) {
506  av_log(avctx, AV_LOG_WARNING, "B frames as references need SDK 8.1 at build time\n");
507  return AVERROR(ENOSYS);
508  }
509 #endif
510 
511 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
512  ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_MULTIPLE_REF_FRAMES);
513  if(avctx->refs != NV_ENC_NUM_REF_FRAMES_AUTOSELECT && ret <= 0) {
514  av_log(avctx, AV_LOG_WARNING, "Multiple reference frames are not supported by the device\n");
515  return AVERROR(ENOSYS);
516  }
517 #else
518  if(avctx->refs != 0) {
519  av_log(avctx, AV_LOG_WARNING, "Multiple reference frames need SDK 9.1 at build time\n");
520  return AVERROR(ENOSYS);
521  }
522 #endif
523 
524  ctx->support_dyn_bitrate = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE);
525 
526  return 0;
527 }
528 
529 static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
530 {
531  NvencContext *ctx = avctx->priv_data;
532  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
533  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
534  char name[128] = { 0};
535  int major, minor, ret;
536  CUdevice cu_device;
537  int loglevel = AV_LOG_VERBOSE;
538 
539  if (ctx->device == LIST_DEVICES)
540  loglevel = AV_LOG_INFO;
541 
542  ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx));
543  if (ret < 0)
544  return ret;
545 
546  ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device));
547  if (ret < 0)
548  return ret;
549 
550  ret = CHECK_CU(dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device));
551  if (ret < 0)
552  return ret;
553 
554  av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
555  if (((major << 4) | minor) < NVENC_CAP) {
556  av_log(avctx, loglevel, "does not support NVENC\n");
557  goto fail;
558  }
559 
560  if (ctx->device != idx && ctx->device != ANY_DEVICE)
561  return -1;
562 
563  ret = CHECK_CU(dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device));
564  if (ret < 0)
565  goto fail;
566 
567  ctx->cu_context = ctx->cu_context_internal;
568  ctx->cu_stream = NULL;
569 
570  if ((ret = nvenc_pop_context(avctx)) < 0)
571  goto fail2;
572 
573  if ((ret = nvenc_open_session(avctx)) < 0)
574  goto fail2;
575 
576  if ((ret = nvenc_check_capabilities(avctx)) < 0)
577  goto fail3;
578 
579  av_log(avctx, loglevel, "supports NVENC\n");
580 
581  dl_fn->nvenc_device_count++;
582 
583  if (ctx->device == idx || ctx->device == ANY_DEVICE)
584  return 0;
585 
586 fail3:
587  if ((ret = nvenc_push_context(avctx)) < 0)
588  return ret;
589 
590  p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
591  ctx->nvencoder = NULL;
592 
593  if ((ret = nvenc_pop_context(avctx)) < 0)
594  return ret;
595 
596 fail2:
597  CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
598  ctx->cu_context_internal = NULL;
599 
600 fail:
601  return AVERROR(ENOSYS);
602 }
603 
605 {
606  NvencContext *ctx = avctx->priv_data;
607  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
608 
609  switch (avctx->codec->id) {
610  case AV_CODEC_ID_H264:
611  ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
612  break;
613  case AV_CODEC_ID_HEVC:
614  ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
615  break;
616  default:
617  return AVERROR_BUG;
618  }
619 
621 
623  av_log(avctx, AV_LOG_WARNING, "The selected preset is deprecated. Use p1 to p7 + -tune or fast/medium/slow.\n");
624 
625  if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
626  AVHWFramesContext *frames_ctx;
627  AVHWDeviceContext *hwdev_ctx;
628  AVCUDADeviceContext *cuda_device_hwctx = NULL;
629 #if CONFIG_D3D11VA
630  AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
631 #endif
632  int ret;
633 
634  if (avctx->hw_frames_ctx) {
635  frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
636  if (frames_ctx->format == AV_PIX_FMT_CUDA)
637  cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
638 #if CONFIG_D3D11VA
639  else if (frames_ctx->format == AV_PIX_FMT_D3D11)
640  d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
641 #endif
642  else
643  return AVERROR(EINVAL);
644  } else if (avctx->hw_device_ctx) {
645  hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
646  if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
647  cuda_device_hwctx = hwdev_ctx->hwctx;
648 #if CONFIG_D3D11VA
649  else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
650  d3d11_device_hwctx = hwdev_ctx->hwctx;
651 #endif
652  else
653  return AVERROR(EINVAL);
654  } else {
655  return AVERROR(EINVAL);
656  }
657 
658  if (cuda_device_hwctx) {
659  ctx->cu_context = cuda_device_hwctx->cuda_ctx;
660  ctx->cu_stream = cuda_device_hwctx->stream;
661  }
662 #if CONFIG_D3D11VA
663  else if (d3d11_device_hwctx) {
664  ctx->d3d11_device = d3d11_device_hwctx->device;
665  ID3D11Device_AddRef(ctx->d3d11_device);
666  }
667 #endif
668 
669  ret = nvenc_open_session(avctx);
670  if (ret < 0)
671  return ret;
672 
673  ret = nvenc_check_capabilities(avctx);
674  if (ret < 0) {
675  av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
676  return ret;
677  }
678  } else {
679  int i, nb_devices = 0;
680 
681  if (CHECK_CU(dl_fn->cuda_dl->cuInit(0)) < 0)
682  return AVERROR_UNKNOWN;
683 
684  if (CHECK_CU(dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) < 0)
685  return AVERROR_UNKNOWN;
686 
687  if (!nb_devices) {
688  av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
689  return AVERROR_EXTERNAL;
690  }
691 
692  av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
693 
694  dl_fn->nvenc_device_count = 0;
695  for (i = 0; i < nb_devices; ++i) {
696  if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
697  return 0;
698  }
699 
700  if (ctx->device == LIST_DEVICES)
701  return AVERROR_EXIT;
702 
703  if (!dl_fn->nvenc_device_count) {
704  av_log(avctx, AV_LOG_FATAL, "No capable devices found\n");
705  return AVERROR_EXTERNAL;
706  }
707 
708  av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
709  return AVERROR(EINVAL);
710  }
711 
712  return 0;
713 }
714 
715 static av_cold void set_constqp(AVCodecContext *avctx)
716 {
717  NvencContext *ctx = avctx->priv_data;
718  NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
719 
720  rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
721 
722  if (ctx->init_qp_p >= 0) {
723  rc->constQP.qpInterP = ctx->init_qp_p;
724  if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
725  rc->constQP.qpIntra = ctx->init_qp_i;
726  rc->constQP.qpInterB = ctx->init_qp_b;
727  } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
728  rc->constQP.qpIntra = av_clip(
729  rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
730  rc->constQP.qpInterB = av_clip(
731  rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
732  } else {
733  rc->constQP.qpIntra = rc->constQP.qpInterP;
734  rc->constQP.qpInterB = rc->constQP.qpInterP;
735  }
736  } else if (ctx->cqp >= 0) {
737  rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
738  if (avctx->b_quant_factor != 0.0)
739  rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
740  if (avctx->i_quant_factor != 0.0)
741  rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
742  }
743 
744  avctx->qmin = -1;
745  avctx->qmax = -1;
746 }
747 
748 static av_cold void set_vbr(AVCodecContext *avctx)
749 {
750  NvencContext *ctx = avctx->priv_data;
751  NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
752  int qp_inter_p;
753 
754  if (avctx->qmin >= 0 && avctx->qmax >= 0) {
755  rc->enableMinQP = 1;
756  rc->enableMaxQP = 1;
757 
758  rc->minQP.qpInterB = avctx->qmin;
759  rc->minQP.qpInterP = avctx->qmin;
760  rc->minQP.qpIntra = avctx->qmin;
761 
762  rc->maxQP.qpInterB = avctx->qmax;
763  rc->maxQP.qpInterP = avctx->qmax;
764  rc->maxQP.qpIntra = avctx->qmax;
765 
766  qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
767  } else if (avctx->qmin >= 0) {
768  rc->enableMinQP = 1;
769 
770  rc->minQP.qpInterB = avctx->qmin;
771  rc->minQP.qpInterP = avctx->qmin;
772  rc->minQP.qpIntra = avctx->qmin;
773 
774  qp_inter_p = avctx->qmin;
775  } else {
776  qp_inter_p = 26; // default to 26
777  }
778 
779  rc->enableInitialRCQP = 1;
780 
781  if (ctx->init_qp_p < 0) {
782  rc->initialRCQP.qpInterP = qp_inter_p;
783  } else {
784  rc->initialRCQP.qpInterP = ctx->init_qp_p;
785  }
786 
787  if (ctx->init_qp_i < 0) {
788  if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
789  rc->initialRCQP.qpIntra = av_clip(
790  rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
791  } else {
792  rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
793  }
794  } else {
795  rc->initialRCQP.qpIntra = ctx->init_qp_i;
796  }
797 
798  if (ctx->init_qp_b < 0) {
799  if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
800  rc->initialRCQP.qpInterB = av_clip(
801  rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
802  } else {
803  rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
804  }
805  } else {
806  rc->initialRCQP.qpInterB = ctx->init_qp_b;
807  }
808 }
809 
811 {
812  NvencContext *ctx = avctx->priv_data;
813  NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
814 
815  rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
816  rc->constQP.qpInterB = 0;
817  rc->constQP.qpInterP = 0;
818  rc->constQP.qpIntra = 0;
819 
820  avctx->qmin = -1;
821  avctx->qmax = -1;
822 }
823 
825 {
826  NvencContext *ctx = avctx->priv_data;
827  NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
828 
829  switch (ctx->rc) {
830  case NV_ENC_PARAMS_RC_CONSTQP:
831  set_constqp(avctx);
832  return;
833 #ifndef NVENC_NO_DEPRECATED_RC
834  case NV_ENC_PARAMS_RC_VBR_MINQP:
835  if (avctx->qmin < 0) {
836  av_log(avctx, AV_LOG_WARNING,
837  "The variable bitrate rate-control requires "
838  "the 'qmin' option set.\n");
839  set_vbr(avctx);
840  return;
841  }
842  /* fall through */
843  case NV_ENC_PARAMS_RC_VBR_HQ:
844 #endif
845  case NV_ENC_PARAMS_RC_VBR:
846  set_vbr(avctx);
847  break;
848  case NV_ENC_PARAMS_RC_CBR:
849 #ifndef NVENC_NO_DEPRECATED_RC
850  case NV_ENC_PARAMS_RC_CBR_HQ:
851  case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
852 #endif
853  break;
854  }
855 
856  rc->rateControlMode = ctx->rc;
857 }
858 
860 {
861  NvencContext *ctx = avctx->priv_data;
862  // default minimum of 4 surfaces
863  // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
864  // another multiply by 2 to avoid blocking next PBB group
865  int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
866 
867  // lookahead enabled
868  if (ctx->rc_lookahead > 0) {
869  // +1 is to account for lkd_bound calculation later
870  // +4 is to allow sufficient pipelining with lookahead
871  nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
872  if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
873  {
874  av_log(avctx, AV_LOG_WARNING,
875  "Defined rc_lookahead requires more surfaces, "
876  "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
877  }
878  ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
879  } else {
880  if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
881  {
882  av_log(avctx, AV_LOG_WARNING,
883  "Defined b-frame requires more surfaces, "
884  "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
885  ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
886  }
887  else if (ctx->nb_surfaces <= 0)
888  ctx->nb_surfaces = nb_surfaces;
889  // otherwise use user specified value
890  }
891 
892  ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
893  ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
894 
895  return 0;
896 }
897 
899 {
900  NvencContext *ctx = avctx->priv_data;
901 
902  if (avctx->global_quality > 0)
903  av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
904 
905  if (ctx->cqp < 0 && avctx->global_quality > 0)
906  ctx->cqp = avctx->global_quality;
907 
908  if (avctx->bit_rate > 0) {
909  ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
910  } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
911  ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
912  }
913 
914  if (avctx->rc_max_rate > 0)
915  ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
916 
917 #ifdef NVENC_HAVE_MULTIPASS
918  ctx->encode_config.rcParams.multiPass = ctx->multipass;
919 
920  if (ctx->flags & NVENC_ONE_PASS)
921  ctx->encode_config.rcParams.multiPass = NV_ENC_MULTI_PASS_DISABLED;
922  if (ctx->flags & NVENC_TWO_PASSES || ctx->twopass > 0)
923  ctx->encode_config.rcParams.multiPass = NV_ENC_TWO_PASS_FULL_RESOLUTION;
924 
925  if (ctx->rc < 0) {
926  if (ctx->cbr) {
927  ctx->rc = NV_ENC_PARAMS_RC_CBR;
928  } else if (ctx->cqp >= 0) {
929  ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
930  } else if (ctx->quality >= 0.0f) {
931  ctx->rc = NV_ENC_PARAMS_RC_VBR;
932  }
933  }
934 #else
935  if (ctx->rc < 0) {
936  if (ctx->flags & NVENC_ONE_PASS)
937  ctx->twopass = 0;
938  if (ctx->flags & NVENC_TWO_PASSES)
939  ctx->twopass = 1;
940 
941  if (ctx->twopass < 0)
942  ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
943 
944  if (ctx->cbr) {
945  if (ctx->twopass) {
946  ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
947  } else {
948  ctx->rc = NV_ENC_PARAMS_RC_CBR;
949  }
950  } else if (ctx->cqp >= 0) {
951  ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
952  } else if (ctx->twopass) {
953  ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
954  } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
955  ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
956  }
957  }
958 #endif
959 
960  if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
961  av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
962  av_log(avctx, AV_LOG_WARNING, "Use -rc constqp/cbr/vbr, -tune and -multipass instead.\n");
963 
964  ctx->rc &= ~RC_MODE_DEPRECATED;
965  }
966 
967 #ifdef NVENC_HAVE_LDKFS
968  if (ctx->ldkfs)
969  ctx->encode_config.rcParams.lowDelayKeyFrameScale = ctx->ldkfs;
970 #endif
971 
972  if (ctx->flags & NVENC_LOSSLESS) {
973  set_lossless(avctx);
974  } else if (ctx->rc >= 0) {
976  } else {
977  ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
978  set_vbr(avctx);
979  }
980 
981  if (avctx->rc_buffer_size > 0) {
982  ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
983  } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
984  avctx->rc_buffer_size = ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
985  }
986 
987  if (ctx->aq) {
988  ctx->encode_config.rcParams.enableAQ = 1;
989  ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
990  av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
991  }
992 
993  if (ctx->temporal_aq) {
994  ctx->encode_config.rcParams.enableTemporalAQ = 1;
995  av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
996  }
997 
998  if (ctx->rc_lookahead > 0) {
999  int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
1000  ctx->encode_config.frameIntervalP - 4;
1001 
1002  if (lkd_bound < 0) {
1003  av_log(avctx, AV_LOG_WARNING,
1004  "Lookahead not enabled. Increase buffer delay (-delay).\n");
1005  } else {
1006  ctx->encode_config.rcParams.enableLookahead = 1;
1007  ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
1008  ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
1009  ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
1010  av_log(avctx, AV_LOG_VERBOSE,
1011  "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
1012  ctx->encode_config.rcParams.lookaheadDepth,
1013  ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
1014  ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
1015  }
1016  }
1017 
1018  if (ctx->strict_gop) {
1019  ctx->encode_config.rcParams.strictGOPTarget = 1;
1020  av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
1021  }
1022 
1023  if (ctx->nonref_p)
1024  ctx->encode_config.rcParams.enableNonRefP = 1;
1025 
1026  if (ctx->zerolatency)
1027  ctx->encode_config.rcParams.zeroReorderDelay = 1;
1028 
1029  if (ctx->quality) {
1030  //convert from float to fixed point 8.8
1031  int tmp_quality = (int)(ctx->quality * 256.0f);
1032  ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
1033  ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
1034 
1035  av_log(avctx, AV_LOG_VERBOSE, "CQ(%d) mode enabled.\n", tmp_quality);
1036 
1037  // CQ mode shall discard avg bitrate/vbv buffer size and honor only max bitrate
1038  ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate = 0;
1039  ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size = 0;
1040  ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
1041  }
1042 }
1043 
1045 {
1046  NvencContext *ctx = avctx->priv_data;
1047  NV_ENC_CONFIG *cc = &ctx->encode_config;
1048  NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
1049  NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
1050 
1051  vui->colourMatrix = avctx->colorspace;
1052  vui->colourPrimaries = avctx->color_primaries;
1053  vui->transferCharacteristics = avctx->color_trc;
1054  vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1055  || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1056 
1057  vui->colourDescriptionPresentFlag =
1058  (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1059 
1060  vui->videoSignalTypePresentFlag =
1061  (vui->colourDescriptionPresentFlag
1062  || vui->videoFormat != 5
1063  || vui->videoFullRangeFlag != 0);
1064 
1065  h264->sliceMode = 3;
1066  h264->sliceModeData = 1;
1067 
1068  h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1069  h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1070  h264->outputAUD = ctx->aud;
1071 
1072  if (ctx->dpb_size >= 0) {
1073  /* 0 means "let the hardware decide" */
1074  h264->maxNumRefFrames = ctx->dpb_size;
1075  }
1076  if (avctx->gop_size >= 0) {
1077  h264->idrPeriod = cc->gopLength;
1078  }
1079 
1080  if (IS_CBR(cc->rcParams.rateControlMode)) {
1081  h264->outputBufferingPeriodSEI = 1;
1082  }
1083 
1084  h264->outputPictureTimingSEI = 1;
1085 
1086 #ifndef NVENC_NO_DEPRECATED_RC
1087  if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
1088  cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
1089  cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
1090  h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
1091  h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
1092  }
1093 #endif
1094 
1095  if (ctx->flags & NVENC_LOSSLESS) {
1096  h264->qpPrimeYZeroTransformBypassFlag = 1;
1097  } else {
1098  switch(ctx->profile) {
1100  cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
1102  break;
1104  cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
1105  avctx->profile = FF_PROFILE_H264_MAIN;
1106  break;
1108  cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
1109  avctx->profile = FF_PROFILE_H264_HIGH;
1110  break;
1112  cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1114  break;
1115  }
1116  }
1117 
1118  // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
1119  if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
1120  cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
1122  }
1123 
1124  h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
1125 
1126  h264->level = ctx->level;
1127 
1128  if (ctx->coder >= 0)
1129  h264->entropyCodingMode = ctx->coder;
1130 
1131 #ifdef NVENC_HAVE_BFRAME_REF_MODE
1132  h264->useBFramesAsRef = ctx->b_ref_mode;
1133 #endif
1134 
1135 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1136  h264->numRefL0 = avctx->refs;
1137  h264->numRefL1 = avctx->refs;
1138 #endif
1139 
1140  return 0;
1141 }
1142 
1144 {
1145  NvencContext *ctx = avctx->priv_data;
1146  NV_ENC_CONFIG *cc = &ctx->encode_config;
1147  NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
1148  NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
1149 
1150  vui->colourMatrix = avctx->colorspace;
1151  vui->colourPrimaries = avctx->color_primaries;
1152  vui->transferCharacteristics = avctx->color_trc;
1153  vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
1154  || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
1155 
1156  vui->colourDescriptionPresentFlag =
1157  (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
1158 
1159  vui->videoSignalTypePresentFlag =
1160  (vui->colourDescriptionPresentFlag
1161  || vui->videoFormat != 5
1162  || vui->videoFullRangeFlag != 0);
1163 
1164  hevc->sliceMode = 3;
1165  hevc->sliceModeData = 1;
1166 
1167  hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
1168  hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
1169  hevc->outputAUD = ctx->aud;
1170 
1171  if (ctx->dpb_size >= 0) {
1172  /* 0 means "let the hardware decide" */
1173  hevc->maxNumRefFramesInDPB = ctx->dpb_size;
1174  }
1175  if (avctx->gop_size >= 0) {
1176  hevc->idrPeriod = cc->gopLength;
1177  }
1178 
1179  if (IS_CBR(cc->rcParams.rateControlMode)) {
1180  hevc->outputBufferingPeriodSEI = 1;
1181  }
1182 
1183  hevc->outputPictureTimingSEI = 1;
1184 
1185  switch (ctx->profile) {
1187  cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
1188  avctx->profile = FF_PROFILE_HEVC_MAIN;
1189  break;
1191  cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1193  break;
1195  cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1196  avctx->profile = FF_PROFILE_HEVC_REXT;
1197  break;
1198  }
1199 
1200  // force setting profile as main10 if input is 10 bit
1201  if (IS_10BIT(ctx->data_pix_fmt)) {
1202  cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
1204  }
1205 
1206  // force setting profile as rext if input is yuv444
1207  if (IS_YUV444(ctx->data_pix_fmt)) {
1208  cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
1209  avctx->profile = FF_PROFILE_HEVC_REXT;
1210  }
1211 
1212  hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
1213 
1214  hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
1215 
1216  hevc->level = ctx->level;
1217 
1218  hevc->tier = ctx->tier;
1219 
1220 #ifdef NVENC_HAVE_HEVC_BFRAME_REF_MODE
1221  hevc->useBFramesAsRef = ctx->b_ref_mode;
1222 #endif
1223 
1224 #ifdef NVENC_HAVE_MULTIPLE_REF_FRAMES
1225  hevc->numRefL0 = avctx->refs;
1226  hevc->numRefL1 = avctx->refs;
1227 #endif
1228 
1229  return 0;
1230 }
1231 
1233 {
1234  switch (avctx->codec->id) {
1235  case AV_CODEC_ID_H264:
1236  return nvenc_setup_h264_config(avctx);
1237  case AV_CODEC_ID_HEVC:
1238  return nvenc_setup_hevc_config(avctx);
1239  /* Earlier switch/case will return if unknown codec is passed. */
1240  }
1241 
1242  return 0;
1243 }
1244 
1245 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1246  int sw, sh;
1247 
1248  sw = avctx->width;
1249  sh = avctx->height;
1250 
1251  if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1252  sw *= avctx->sample_aspect_ratio.num;
1253  sh *= avctx->sample_aspect_ratio.den;
1254  }
1255 
1256  av_reduce(dw, dh, sw, sh, 1024 * 1024);
1257 }
1258 
1260 {
1261  NvencContext *ctx = avctx->priv_data;
1262  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1263  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1264 
1265  NV_ENC_PRESET_CONFIG preset_config = { 0 };
1266  NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1267  AVCPBProperties *cpb_props;
1268  int res = 0;
1269  int dw, dh;
1270 
1271  ctx->encode_config.version = NV_ENC_CONFIG_VER;
1272  ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1273 
1274  ctx->init_encode_params.encodeHeight = avctx->height;
1275  ctx->init_encode_params.encodeWidth = avctx->width;
1276 
1277  ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1278 
1279  preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1280  preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1281 
1282 #ifdef NVENC_HAVE_NEW_PRESETS
1283  ctx->init_encode_params.tuningInfo = ctx->tuning_info;
1284 
1285  if (ctx->flags & NVENC_LOSSLESS)
1286  ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOSSLESS;
1287  else if (ctx->flags & NVENC_LOWLATENCY)
1288  ctx->init_encode_params.tuningInfo = NV_ENC_TUNING_INFO_LOW_LATENCY;
1289 
1290  nv_status = p_nvenc->nvEncGetEncodePresetConfigEx(ctx->nvencoder,
1291  ctx->init_encode_params.encodeGUID,
1292  ctx->init_encode_params.presetGUID,
1293  ctx->init_encode_params.tuningInfo,
1294  &preset_config);
1295 #else
1296  nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1297  ctx->init_encode_params.encodeGUID,
1298  ctx->init_encode_params.presetGUID,
1299  &preset_config);
1300 #endif
1301  if (nv_status != NV_ENC_SUCCESS)
1302  return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1303 
1304  memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1305 
1306  ctx->encode_config.version = NV_ENC_CONFIG_VER;
1307 
1308  compute_dar(avctx, &dw, &dh);
1309  ctx->init_encode_params.darHeight = dh;
1310  ctx->init_encode_params.darWidth = dw;
1311 
1312  if (avctx->framerate.num > 0 && avctx->framerate.den > 0) {
1313  ctx->init_encode_params.frameRateNum = avctx->framerate.num;
1314  ctx->init_encode_params.frameRateDen = avctx->framerate.den;
1315  } else {
1316  ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1317  ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1318  }
1319 
1320  ctx->init_encode_params.enableEncodeAsync = 0;
1321  ctx->init_encode_params.enablePTD = 1;
1322 
1323 #ifdef NVENC_HAVE_NEW_PRESETS
1324  /* If lookahead isn't set from CLI, use value from preset.
1325  * P6 & P7 presets may enable lookahead for better quality.
1326  * */
1327  if (ctx->rc_lookahead == 0 && ctx->encode_config.rcParams.enableLookahead)
1328  ctx->rc_lookahead = ctx->encode_config.rcParams.lookaheadDepth;
1329 #endif
1330 
1331  if (ctx->weighted_pred == 1)
1332  ctx->init_encode_params.enableWeightedPrediction = 1;
1333 
1334  if (ctx->bluray_compat) {
1335  ctx->aud = 1;
1336  ctx->dpb_size = FFMIN(FFMAX(avctx->refs, 0), 6);
1337  avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1338  switch (avctx->codec->id) {
1339  case AV_CODEC_ID_H264:
1340  /* maximum level depends on used resolution */
1341  break;
1342  case AV_CODEC_ID_HEVC:
1343  ctx->level = NV_ENC_LEVEL_HEVC_51;
1344  ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1345  break;
1346  }
1347  }
1348 
1349  if (avctx->gop_size > 0) {
1350  if (avctx->max_b_frames >= 0) {
1351  /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1352  ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1353  }
1354 
1355  ctx->encode_config.gopLength = avctx->gop_size;
1356  } else if (avctx->gop_size == 0) {
1357  ctx->encode_config.frameIntervalP = 0;
1358  ctx->encode_config.gopLength = 1;
1359  }
1360 
1361  nvenc_recalc_surfaces(avctx);
1362 
1363  nvenc_setup_rate_control(avctx);
1364 
1365  if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1366  ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1367  } else {
1368  ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1369  }
1370 
1371  res = nvenc_setup_codec_config(avctx);
1372  if (res)
1373  return res;
1374 
1375  res = nvenc_push_context(avctx);
1376  if (res < 0)
1377  return res;
1378 
1379  nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1380  if (nv_status != NV_ENC_SUCCESS) {
1381  nvenc_pop_context(avctx);
1382  return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1383  }
1384 
1385 #ifdef NVENC_HAVE_CUSTREAM_PTR
1386  if (ctx->cu_context) {
1387  nv_status = p_nvenc->nvEncSetIOCudaStreams(ctx->nvencoder, &ctx->cu_stream, &ctx->cu_stream);
1388  if (nv_status != NV_ENC_SUCCESS) {
1389  nvenc_pop_context(avctx);
1390  return nvenc_print_error(avctx, nv_status, "SetIOCudaStreams failed");
1391  }
1392  }
1393 #endif
1394 
1395  res = nvenc_pop_context(avctx);
1396  if (res < 0)
1397  return res;
1398 
1399  if (ctx->encode_config.frameIntervalP > 1)
1400  avctx->has_b_frames = 2;
1401 
1402  if (ctx->encode_config.rcParams.averageBitRate > 0)
1403  avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1404 
1405  cpb_props = ff_add_cpb_side_data(avctx);
1406  if (!cpb_props)
1407  return AVERROR(ENOMEM);
1408  cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1409  cpb_props->avg_bitrate = avctx->bit_rate;
1410  cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1411 
1412  return 0;
1413 }
1414 
1415 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1416 {
1417  switch (pix_fmt) {
1418  case AV_PIX_FMT_YUV420P:
1419  return NV_ENC_BUFFER_FORMAT_YV12_PL;
1420  case AV_PIX_FMT_NV12:
1421  return NV_ENC_BUFFER_FORMAT_NV12_PL;
1422  case AV_PIX_FMT_P010:
1423  case AV_PIX_FMT_P016:
1424  return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1425  case AV_PIX_FMT_YUV444P:
1426  return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1427  case AV_PIX_FMT_YUV444P16:
1428  return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1429  case AV_PIX_FMT_0RGB32:
1430  return NV_ENC_BUFFER_FORMAT_ARGB;
1431  case AV_PIX_FMT_0BGR32:
1432  return NV_ENC_BUFFER_FORMAT_ABGR;
1433  default:
1434  return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1435  }
1436 }
1437 
1438 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1439 {
1440  NvencContext *ctx = avctx->priv_data;
1441  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1442  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1443  NvencSurface* tmp_surface = &ctx->surfaces[idx];
1444 
1445  NVENCSTATUS nv_status;
1446  NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1447  allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1448 
1449  if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1450  ctx->surfaces[idx].in_ref = av_frame_alloc();
1451  if (!ctx->surfaces[idx].in_ref)
1452  return AVERROR(ENOMEM);
1453  } else {
1454  NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1455 
1456  ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1457  if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1458  av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1459  av_get_pix_fmt_name(ctx->data_pix_fmt));
1460  return AVERROR(EINVAL);
1461  }
1462 
1463  allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1464  allocSurf.width = avctx->width;
1465  allocSurf.height = avctx->height;
1466  allocSurf.bufferFmt = ctx->surfaces[idx].format;
1467 
1468  nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1469  if (nv_status != NV_ENC_SUCCESS) {
1470  return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1471  }
1472 
1473  ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1474  ctx->surfaces[idx].width = allocSurf.width;
1475  ctx->surfaces[idx].height = allocSurf.height;
1476  }
1477 
1478  nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1479  if (nv_status != NV_ENC_SUCCESS) {
1480  int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1481  if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1482  p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1483  av_frame_free(&ctx->surfaces[idx].in_ref);
1484  return err;
1485  }
1486 
1487  ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1488 
1489  av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1490 
1491  return 0;
1492 }
1493 
1495 {
1496  NvencContext *ctx = avctx->priv_data;
1497  int i, res = 0, res2;
1498 
1499  ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1500  if (!ctx->surfaces)
1501  return AVERROR(ENOMEM);
1502 
1503  ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1504  if (!ctx->timestamp_list)
1505  return AVERROR(ENOMEM);
1506 
1507  ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1508  if (!ctx->unused_surface_queue)
1509  return AVERROR(ENOMEM);
1510 
1511  ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1512  if (!ctx->output_surface_queue)
1513  return AVERROR(ENOMEM);
1514  ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1515  if (!ctx->output_surface_ready_queue)
1516  return AVERROR(ENOMEM);
1517 
1518  res = nvenc_push_context(avctx);
1519  if (res < 0)
1520  return res;
1521 
1522  for (i = 0; i < ctx->nb_surfaces; i++) {
1523  if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1524  goto fail;
1525  }
1526 
1527 fail:
1528  res2 = nvenc_pop_context(avctx);
1529  if (res2 < 0)
1530  return res2;
1531 
1532  return res;
1533 }
1534 
1536 {
1537  NvencContext *ctx = avctx->priv_data;
1538  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1539  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1540 
1541  NVENCSTATUS nv_status;
1542  uint32_t outSize = 0;
1543  char tmpHeader[256];
1544  NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1545  payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1546 
1547  payload.spsppsBuffer = tmpHeader;
1548  payload.inBufferSize = sizeof(tmpHeader);
1549  payload.outSPSPPSPayloadSize = &outSize;
1550 
1551  nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1552  if (nv_status != NV_ENC_SUCCESS) {
1553  return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1554  }
1555 
1556  avctx->extradata_size = outSize;
1558 
1559  if (!avctx->extradata) {
1560  return AVERROR(ENOMEM);
1561  }
1562 
1563  memcpy(avctx->extradata, tmpHeader, outSize);
1564 
1565  return 0;
1566 }
1567 
1569 {
1570  NvencContext *ctx = avctx->priv_data;
1571  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1572  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1573  int i, res;
1574 
1575  /* the encoder has to be flushed before it can be closed */
1576  if (ctx->nvencoder) {
1577  NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1578  .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1579 
1580  res = nvenc_push_context(avctx);
1581  if (res < 0)
1582  return res;
1583 
1584  p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
1585  }
1586 
1587  av_fifo_freep(&ctx->timestamp_list);
1588  av_fifo_freep(&ctx->output_surface_ready_queue);
1589  av_fifo_freep(&ctx->output_surface_queue);
1590  av_fifo_freep(&ctx->unused_surface_queue);
1591 
1592  if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1593  for (i = 0; i < ctx->nb_registered_frames; i++) {
1594  if (ctx->registered_frames[i].mapped)
1595  p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1596  if (ctx->registered_frames[i].regptr)
1597  p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1598  }
1599  ctx->nb_registered_frames = 0;
1600  }
1601 
1602  if (ctx->surfaces) {
1603  for (i = 0; i < ctx->nb_surfaces; ++i) {
1604  if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1605  p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1606  av_frame_free(&ctx->surfaces[i].in_ref);
1607  p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1608  }
1609  }
1610  av_freep(&ctx->surfaces);
1611  ctx->nb_surfaces = 0;
1612 
1613  av_frame_free(&ctx->frame);
1614 
1615  if (ctx->nvencoder) {
1616  p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1617 
1618  res = nvenc_pop_context(avctx);
1619  if (res < 0)
1620  return res;
1621  }
1622  ctx->nvencoder = NULL;
1623 
1624  if (ctx->cu_context_internal)
1625  CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1626  ctx->cu_context = ctx->cu_context_internal = NULL;
1627 
1628 #if CONFIG_D3D11VA
1629  if (ctx->d3d11_device) {
1630  ID3D11Device_Release(ctx->d3d11_device);
1631  ctx->d3d11_device = NULL;
1632  }
1633 #endif
1634 
1635  nvenc_free_functions(&dl_fn->nvenc_dl);
1636  cuda_free_functions(&dl_fn->cuda_dl);
1637 
1638  dl_fn->nvenc_device_count = 0;
1639 
1640  av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1641 
1642  return 0;
1643 }
1644 
1646 {
1647  NvencContext *ctx = avctx->priv_data;
1648  int ret;
1649 
1650  if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1651  AVHWFramesContext *frames_ctx;
1652  if (!avctx->hw_frames_ctx) {
1653  av_log(avctx, AV_LOG_ERROR,
1654  "hw_frames_ctx must be set when using GPU frames as input\n");
1655  return AVERROR(EINVAL);
1656  }
1657  frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1658  if (frames_ctx->format != avctx->pix_fmt) {
1659  av_log(avctx, AV_LOG_ERROR,
1660  "hw_frames_ctx must match the GPU frame type\n");
1661  return AVERROR(EINVAL);
1662  }
1663  ctx->data_pix_fmt = frames_ctx->sw_format;
1664  } else {
1665  ctx->data_pix_fmt = avctx->pix_fmt;
1666  }
1667 
1668  ctx->frame = av_frame_alloc();
1669  if (!ctx->frame)
1670  return AVERROR(ENOMEM);
1671 
1672  if ((ret = nvenc_load_libraries(avctx)) < 0)
1673  return ret;
1674 
1675  if ((ret = nvenc_setup_device(avctx)) < 0)
1676  return ret;
1677 
1678  if ((ret = nvenc_setup_encoder(avctx)) < 0)
1679  return ret;
1680 
1681  if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1682  return ret;
1683 
1684  if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1685  if ((ret = nvenc_setup_extradata(avctx)) < 0)
1686  return ret;
1687  }
1688 
1689  return 0;
1690 }
1691 
1693 {
1694  NvencSurface *tmp_surf;
1695 
1696  if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1697  // queue empty
1698  return NULL;
1699 
1700  av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1701  return tmp_surf;
1702 }
1703 
1704 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1705  NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1706 {
1707  int dst_linesize[4] = {
1708  lock_buffer_params->pitch,
1709  lock_buffer_params->pitch,
1710  lock_buffer_params->pitch,
1711  lock_buffer_params->pitch
1712  };
1713  uint8_t *dst_data[4];
1714  int ret;
1715 
1717  dst_linesize[1] = dst_linesize[2] >>= 1;
1718 
1719  ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1720  lock_buffer_params->bufferDataPtr, dst_linesize);
1721  if (ret < 0)
1722  return ret;
1723 
1725  FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1726 
1727  av_image_copy(dst_data, dst_linesize,
1728  (const uint8_t**)frame->data, frame->linesize, frame->format,
1729  avctx->width, avctx->height);
1730 
1731  return 0;
1732 }
1733 
1735 {
1736  NvencContext *ctx = avctx->priv_data;
1737  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1738  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1739  NVENCSTATUS nv_status;
1740 
1741  int i, first_round;
1742 
1743  if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1744  for (first_round = 1; first_round >= 0; first_round--) {
1745  for (i = 0; i < ctx->nb_registered_frames; i++) {
1746  if (!ctx->registered_frames[i].mapped) {
1747  if (ctx->registered_frames[i].regptr) {
1748  if (first_round)
1749  continue;
1750  nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1751  if (nv_status != NV_ENC_SUCCESS)
1752  return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1753  ctx->registered_frames[i].ptr = NULL;
1754  ctx->registered_frames[i].regptr = NULL;
1755  }
1756  return i;
1757  }
1758  }
1759  }
1760  } else {
1761  return ctx->nb_registered_frames++;
1762  }
1763 
1764  av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1765  return AVERROR(ENOMEM);
1766 }
1767 
1769 {
1770  NvencContext *ctx = avctx->priv_data;
1771  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1772  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1773 
1775  NV_ENC_REGISTER_RESOURCE reg = { 0 };
1776  int i, idx, ret;
1777 
1778  for (i = 0; i < ctx->nb_registered_frames; i++) {
1779  if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1780  return i;
1781  else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
1782  return i;
1783  }
1784 
1785  idx = nvenc_find_free_reg_resource(avctx);
1786  if (idx < 0)
1787  return idx;
1788 
1789  reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1790  reg.width = frames_ctx->width;
1791  reg.height = frames_ctx->height;
1792  reg.pitch = frame->linesize[0];
1793  reg.resourceToRegister = frame->data[0];
1794 
1795  if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1796  reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1797  }
1798  else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1799  reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1800  reg.subResourceIndex = (intptr_t)frame->data[1];
1801  }
1802 
1803  reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
1804  if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1805  av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1806  av_get_pix_fmt_name(frames_ctx->sw_format));
1807  return AVERROR(EINVAL);
1808  }
1809 
1810  ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1811  if (ret != NV_ENC_SUCCESS) {
1812  nvenc_print_error(avctx, ret, "Error registering an input resource");
1813  return AVERROR_UNKNOWN;
1814  }
1815 
1816  ctx->registered_frames[idx].ptr = frame->data[0];
1817  ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1818  ctx->registered_frames[idx].regptr = reg.registeredResource;
1819  return idx;
1820 }
1821 
1823  NvencSurface *nvenc_frame)
1824 {
1825  NvencContext *ctx = avctx->priv_data;
1826  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1827  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1828 
1829  int res;
1830  NVENCSTATUS nv_status;
1831 
1832  if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1833  int reg_idx = nvenc_register_frame(avctx, frame);
1834  if (reg_idx < 0) {
1835  av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1836  return reg_idx;
1837  }
1838 
1839  res = av_frame_ref(nvenc_frame->in_ref, frame);
1840  if (res < 0)
1841  return res;
1842 
1843  if (!ctx->registered_frames[reg_idx].mapped) {
1844  ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1845  ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1846  nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1847  if (nv_status != NV_ENC_SUCCESS) {
1848  av_frame_unref(nvenc_frame->in_ref);
1849  return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1850  }
1851  }
1852 
1853  ctx->registered_frames[reg_idx].mapped += 1;
1854 
1855  nvenc_frame->reg_idx = reg_idx;
1856  nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
1857  nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1858  nvenc_frame->pitch = frame->linesize[0];
1859 
1860  return 0;
1861  } else {
1862  NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1863 
1864  lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1865  lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1866 
1867  nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1868  if (nv_status != NV_ENC_SUCCESS) {
1869  return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1870  }
1871 
1872  nvenc_frame->pitch = lockBufferParams.pitch;
1873  res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1874 
1875  nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1876  if (nv_status != NV_ENC_SUCCESS) {
1877  return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1878  }
1879 
1880  return res;
1881  }
1882 }
1883 
1885  NV_ENC_PIC_PARAMS *params,
1886  NV_ENC_SEI_PAYLOAD *sei_data,
1887  int sei_count)
1888 {
1889  NvencContext *ctx = avctx->priv_data;
1890 
1891  switch (avctx->codec->id) {
1892  case AV_CODEC_ID_H264:
1893  params->codecPicParams.h264PicParams.sliceMode =
1894  ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1895  params->codecPicParams.h264PicParams.sliceModeData =
1896  ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1897  if (sei_count > 0) {
1898  params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1899  params->codecPicParams.h264PicParams.seiPayloadArrayCnt = sei_count;
1900  }
1901 
1902  break;
1903  case AV_CODEC_ID_HEVC:
1904  params->codecPicParams.hevcPicParams.sliceMode =
1905  ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1906  params->codecPicParams.hevcPicParams.sliceModeData =
1907  ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1908  if (sei_count > 0) {
1909  params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1910  params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = sei_count;
1911  }
1912 
1913  break;
1914  }
1915 }
1916 
1917 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1918 {
1919  av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
1920 }
1921 
1923 {
1924  int64_t timestamp = AV_NOPTS_VALUE;
1925  if (av_fifo_size(queue) > 0)
1926  av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
1927 
1928  return timestamp;
1929 }
1930 
1932  NV_ENC_LOCK_BITSTREAM *params,
1933  AVPacket *pkt)
1934 {
1935  NvencContext *ctx = avctx->priv_data;
1936 
1937  pkt->pts = params->outputTimeStamp;
1938  pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1939 
1940  pkt->dts -= FFMAX(ctx->encode_config.frameIntervalP - 1, 0) * FFMAX(avctx->ticks_per_frame, 1);
1941 
1942  return 0;
1943 }
1944 
1946 {
1947  NvencContext *ctx = avctx->priv_data;
1948  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1949  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1950 
1951  uint32_t slice_mode_data;
1952  uint32_t *slice_offsets = NULL;
1953  NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1954  NVENCSTATUS nv_status;
1955  int res = 0;
1956 
1957  enum AVPictureType pict_type;
1958 
1959  switch (avctx->codec->id) {
1960  case AV_CODEC_ID_H264:
1961  slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1962  break;
1963  case AV_CODEC_ID_H265:
1964  slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1965  break;
1966  default:
1967  av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1968  res = AVERROR(EINVAL);
1969  goto error;
1970  }
1971  slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1972 
1973  if (!slice_offsets) {
1974  res = AVERROR(ENOMEM);
1975  goto error;
1976  }
1977 
1978  lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1979 
1980  lock_params.doNotWait = 0;
1981  lock_params.outputBitstream = tmpoutsurf->output_surface;
1982  lock_params.sliceOffsets = slice_offsets;
1983 
1984  nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1985  if (nv_status != NV_ENC_SUCCESS) {
1986  res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1987  goto error;
1988  }
1989 
1990  res = ff_get_encode_buffer(avctx, pkt, lock_params.bitstreamSizeInBytes, 0);
1991 
1992  if (res < 0) {
1993  p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1994  goto error;
1995  }
1996 
1997  memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1998 
1999  nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
2000  if (nv_status != NV_ENC_SUCCESS) {
2001  res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
2002  goto error;
2003  }
2004 
2005 
2006  if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
2007  ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
2008  if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
2009  nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
2010  if (nv_status != NV_ENC_SUCCESS) {
2011  res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
2012  goto error;
2013  }
2014  } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
2015  res = AVERROR_BUG;
2016  goto error;
2017  }
2018 
2019  av_frame_unref(tmpoutsurf->in_ref);
2020 
2021  tmpoutsurf->input_surface = NULL;
2022  }
2023 
2024  switch (lock_params.pictureType) {
2025  case NV_ENC_PIC_TYPE_IDR:
2027  case NV_ENC_PIC_TYPE_I:
2028  pict_type = AV_PICTURE_TYPE_I;
2029  break;
2030  case NV_ENC_PIC_TYPE_P:
2031  pict_type = AV_PICTURE_TYPE_P;
2032  break;
2033  case NV_ENC_PIC_TYPE_B:
2034  pict_type = AV_PICTURE_TYPE_B;
2035  break;
2036  case NV_ENC_PIC_TYPE_BI:
2037  pict_type = AV_PICTURE_TYPE_BI;
2038  break;
2039  default:
2040  av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
2041  av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
2042  res = AVERROR_EXTERNAL;
2043  goto error;
2044  }
2045 
2046 #if FF_API_CODED_FRAME
2048  avctx->coded_frame->pict_type = pict_type;
2050 #endif
2051 
2053  (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
2054 
2055  res = nvenc_set_timestamp(avctx, &lock_params, pkt);
2056  if (res < 0)
2057  goto error2;
2058 
2059  av_free(slice_offsets);
2060 
2061  return 0;
2062 
2063 error:
2064  timestamp_queue_dequeue(ctx->timestamp_list);
2065 
2066 error2:
2067  av_free(slice_offsets);
2068 
2069  return res;
2070 }
2071 
2072 static int output_ready(AVCodecContext *avctx, int flush)
2073 {
2074  NvencContext *ctx = avctx->priv_data;
2075  int nb_ready, nb_pending;
2076 
2077  nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
2078  nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
2079  if (flush)
2080  return nb_ready > 0;
2081  return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
2082 }
2083 
2084 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
2085 {
2086  NvencContext *ctx = avctx->priv_data;
2087  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
2088  NVENCSTATUS ret;
2089 
2090  NV_ENC_RECONFIGURE_PARAMS params = { 0 };
2091  int needs_reconfig = 0;
2092  int needs_encode_config = 0;
2093  int reconfig_bitrate = 0, reconfig_dar = 0;
2094  int dw, dh;
2095 
2096  params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
2097  params.reInitEncodeParams = ctx->init_encode_params;
2098 
2099  compute_dar(avctx, &dw, &dh);
2100  if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
2101  av_log(avctx, AV_LOG_VERBOSE,
2102  "aspect ratio change (DAR): %d:%d -> %d:%d\n",
2103  ctx->init_encode_params.darWidth,
2104  ctx->init_encode_params.darHeight, dw, dh);
2105 
2106  params.reInitEncodeParams.darHeight = dh;
2107  params.reInitEncodeParams.darWidth = dw;
2108 
2109  needs_reconfig = 1;
2110  reconfig_dar = 1;
2111  }
2112 
2113  if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
2114  if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
2115  av_log(avctx, AV_LOG_VERBOSE,
2116  "avg bitrate change: %d -> %d\n",
2117  params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
2118  (uint32_t)avctx->bit_rate);
2119 
2120  params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
2121  reconfig_bitrate = 1;
2122  }
2123 
2124  if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
2125  av_log(avctx, AV_LOG_VERBOSE,
2126  "max bitrate change: %d -> %d\n",
2127  params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
2128  (uint32_t)avctx->rc_max_rate);
2129 
2130  params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
2131  reconfig_bitrate = 1;
2132  }
2133 
2134  if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2135  av_log(avctx, AV_LOG_VERBOSE,
2136  "vbv buffer size change: %d -> %d\n",
2137  params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2138  avctx->rc_buffer_size);
2139 
2140  params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2141  reconfig_bitrate = 1;
2142  }
2143 
2144  if (reconfig_bitrate) {
2145  params.resetEncoder = 1;
2146  params.forceIDR = 1;
2147 
2148  needs_encode_config = 1;
2149  needs_reconfig = 1;
2150  }
2151  }
2152 
2153  if (!needs_encode_config)
2154  params.reInitEncodeParams.encodeConfig = NULL;
2155 
2156  if (needs_reconfig) {
2157  ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, &params);
2158  if (ret != NV_ENC_SUCCESS) {
2159  nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2160  } else {
2161  if (reconfig_dar) {
2162  ctx->init_encode_params.darHeight = dh;
2163  ctx->init_encode_params.darWidth = dw;
2164  }
2165 
2166  if (reconfig_bitrate) {
2167  ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2168  ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2169  ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2170  }
2171 
2172  }
2173  }
2174 }
2175 
2176 static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2177 {
2178  NVENCSTATUS nv_status;
2179  NvencSurface *tmp_out_surf, *in_surf;
2180  int res, res2;
2181  NV_ENC_SEI_PAYLOAD sei_data[8];
2182  int sei_count = 0;
2183  int i;
2184 
2185  NvencContext *ctx = avctx->priv_data;
2186  NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2187  NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2188 
2189  NV_ENC_PIC_PARAMS pic_params = { 0 };
2190  pic_params.version = NV_ENC_PIC_PARAMS_VER;
2191 
2192  if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2193  return AVERROR(EINVAL);
2194 
2195  if (frame && frame->buf[0]) {
2196  in_surf = get_free_frame(ctx);
2197  if (!in_surf)
2198  return AVERROR(EAGAIN);
2199 
2200  res = nvenc_push_context(avctx);
2201  if (res < 0)
2202  return res;
2203 
2204  reconfig_encoder(avctx, frame);
2205 
2206  res = nvenc_upload_frame(avctx, frame, in_surf);
2207 
2208  res2 = nvenc_pop_context(avctx);
2209  if (res2 < 0)
2210  return res2;
2211 
2212  if (res)
2213  return res;
2214 
2215  pic_params.inputBuffer = in_surf->input_surface;
2216  pic_params.bufferFmt = in_surf->format;
2217  pic_params.inputWidth = in_surf->width;
2218  pic_params.inputHeight = in_surf->height;
2219  pic_params.inputPitch = in_surf->pitch;
2220  pic_params.outputBitstream = in_surf->output_surface;
2221 
2222  if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2223  if (frame->top_field_first)
2224  pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2225  else
2226  pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2227  } else {
2228  pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2229  }
2230 
2231  if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2232  pic_params.encodePicFlags =
2233  ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2234  } else {
2235  pic_params.encodePicFlags = 0;
2236  }
2237 
2238  pic_params.inputTimeStamp = frame->pts;
2239 
2241  void *a53_data = NULL;
2242  size_t a53_size = 0;
2243 
2244  if (ff_alloc_a53_sei(frame, 0, (void**)&a53_data, &a53_size) < 0) {
2245  av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2246  }
2247 
2248  if (a53_data) {
2249  sei_data[sei_count].payloadSize = (uint32_t)a53_size;
2250  sei_data[sei_count].payloadType = 4;
2251  sei_data[sei_count].payload = (uint8_t*)a53_data;
2252  sei_count ++;
2253  }
2254  }
2255 
2257  void *tc_data = NULL;
2258  size_t tc_size = 0;
2259 
2260  if (ff_alloc_timecode_sei(frame, avctx->framerate, 0, (void**)&tc_data, &tc_size) < 0) {
2261  av_log(ctx, AV_LOG_ERROR, "Not enough memory for timecode sei, skipping\n");
2262  }
2263 
2264  if (tc_data) {
2265  sei_data[sei_count].payloadSize = (uint32_t)tc_size;
2266  sei_data[sei_count].payloadType = SEI_TYPE_TIME_CODE;
2267  sei_data[sei_count].payload = (uint8_t*)tc_data;
2268  sei_count ++;
2269  }
2270  }
2271 
2272  nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data, sei_count);
2273  } else {
2274  pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2275  }
2276 
2277  res = nvenc_push_context(avctx);
2278  if (res < 0)
2279  return res;
2280 
2281  nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2282 
2283  for ( i = 0; i < sei_count; i++)
2284  av_freep(&sei_data[i].payload);
2285 
2286  res = nvenc_pop_context(avctx);
2287  if (res < 0)
2288  return res;
2289 
2290  if (nv_status != NV_ENC_SUCCESS &&
2291  nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2292  return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2293 
2294  if (frame && frame->buf[0]) {
2295  av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2296  timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2297  }
2298 
2299  /* all the pending buffers are now ready for output */
2300  if (nv_status == NV_ENC_SUCCESS) {
2301  while (av_fifo_size(ctx->output_surface_queue) > 0) {
2302  av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2303  av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2304  }
2305  }
2306 
2307  return 0;
2308 }
2309 
2311 {
2312  NvencSurface *tmp_out_surf;
2313  int res, res2;
2314 
2315  NvencContext *ctx = avctx->priv_data;
2316 
2317  AVFrame *frame = ctx->frame;
2318 
2319  if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2320  return AVERROR(EINVAL);
2321 
2322  if (!frame->buf[0]) {
2323  res = ff_encode_get_frame(avctx, frame);
2324  if (res < 0 && res != AVERROR_EOF)
2325  return res;
2326  }
2327 
2328  res = nvenc_send_frame(avctx, frame);
2329  if (res < 0) {
2330  if (res != AVERROR(EAGAIN))
2331  return res;
2332  } else
2334 
2335  if (output_ready(avctx, avctx->internal->draining)) {
2336  av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2337 
2338  res = nvenc_push_context(avctx);
2339  if (res < 0)
2340  return res;
2341 
2342  res = process_output_surface(avctx, pkt, tmp_out_surf);
2343 
2344  res2 = nvenc_pop_context(avctx);
2345  if (res2 < 0)
2346  return res2;
2347 
2348  if (res)
2349  return res;
2350 
2351  av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2352  } else if (avctx->internal->draining) {
2353  return AVERROR_EOF;
2354  } else {
2355  return AVERROR(EAGAIN);
2356  }
2357 
2358  return 0;
2359 }
2360 
2362 {
2363  NvencContext *ctx = avctx->priv_data;
2364 
2365  nvenc_send_frame(avctx, NULL);
2366  av_fifo_reset(ctx->timestamp_list);
2367 }
static void flush(AVCodecContext *avctx)
static double val(void *priv, double ch)
Definition: aeval.c:76
@ NONE
Definition: af_afade.c:54
int ff_alloc_a53_sei(const AVFrame *frame, size_t prefix_len, void **data, size_t *sei_size)
Check AVFrame for A53 side data and allocate and fill SEI message with A53 info.
Definition: atsc_a53.c:25
#define av_cold
Definition: attributes.h:88
uint8_t
simple assert() macros that are a bit more flexible than ISO C assert().
#define FF_PROFILE_H264_HIGH
Definition: avcodec.h:1905
#define FF_PROFILE_H264_MAIN
Definition: avcodec.h:1903
#define FF_PROFILE_HEVC_MAIN_10
Definition: avcodec.h:1951
#define FF_PROFILE_H264_HIGH_444_PREDICTIVE
Definition: avcodec.h:1913
#define FF_PROFILE_H264_BASELINE
Definition: avcodec.h:1901
#define FF_PROFILE_HEVC_REXT
Definition: avcodec.h:1953
#define FF_PROFILE_HEVC_MAIN
Definition: avcodec.h:1950
#define DEFAULT
Definition: avdct.c:28
int ff_side_data_set_encoder_stats(AVPacket *pkt, int quality, int64_t *error, int error_count, int pict_type)
Definition: avpacket.c:820
#define P1
Definition: cavsdsp.c:39
#define P2
Definition: cavsdsp.c:38
#define flags(name, subs,...)
Definition: cbs_av1.c:572
#define fail()
Definition: checkasm.h:133
#define AV_CODEC_ID_H265
Definition: codec_id.h:224
#define FFSWAP(type, a, b)
Definition: common.h:108
#define FFMIN(a, b)
Definition: common.h:105
#define av_clip
Definition: common.h:122
#define FFMAX(a, b)
Definition: common.h:103
#define NULL
Definition: coverity.c:32
long long int64_t
Definition: coverity.c:34
static __device__ float fabs(float a)
Definition: cuda_runtime.h:182
static enum AVPixelFormat pix_fmt
static AVFrame * frame
int ff_get_encode_buffer(AVCodecContext *avctx, AVPacket *avpkt, int64_t size, int flags)
Get a buffer for a packet.
Definition: encode.c:82
int ff_encode_get_frame(AVCodecContext *avctx, AVFrame *frame)
Called by encoders to get the next frame for encoding.
Definition: encode.c:162
int
#define AV_CODEC_FLAG_INTERLACED_DCT
Use interlaced DCT.
Definition: avcodec.h:321
#define AV_CODEC_FLAG_GLOBAL_HEADER
Place global headers in extradata instead of every keyframe.
Definition: avcodec.h:329
@ AV_CODEC_ID_H264
Definition: codec_id.h:76
@ AV_CODEC_ID_HEVC
Definition: codec_id.h:223
#define AV_INPUT_BUFFER_PADDING_SIZE
Required number of additionally allocated bytes at the end of the input bitstream for decoding.
Definition: avcodec.h:215
#define AV_PKT_FLAG_KEY
The packet contains a keyframe.
Definition: packet.h:410
#define FF_QP2LAMBDA
factor to convert from H.263 QP to lambda
Definition: avutil.h:227
#define AVERROR_EXIT
Immediate exit was requested; the called function should not be restarted.
Definition: error.h:56
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition: error.h:71
#define AVERROR_BUFFER_TOO_SMALL
Buffer too small.
Definition: error.h:51
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition: error.h:57
#define AVERROR_BUG
Internal bug, also see AVERROR_BUG2.
Definition: error.h:50
#define AVERROR_EOF
End of file.
Definition: error.h:55
#define AVERROR(e)
Definition: error.h:43
void av_frame_unref(AVFrame *frame)
Unreference all the buffers referenced by frame and reset the frame fields.
Definition: frame.c:553
int av_frame_ref(AVFrame *dst, const AVFrame *src)
Set up a new reference to the data described by the source frame.
Definition: frame.c:443
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:203
AVFrame * av_frame_alloc(void)
Allocate an AVFrame and set its fields to default values.
Definition: frame.c:190
AVFrameSideData * av_frame_get_side_data(const AVFrame *frame, enum AVFrameSideDataType type)
Definition: frame.c:738
@ AV_FRAME_DATA_A53_CC
ATSC A53 Part 4 Closed Captions.
Definition: frame.h:58
@ AV_FRAME_DATA_S12M_TIMECODE
Timecode which conforms to SMPTE ST 12-1.
Definition: frame.h:168
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:200
#define AV_LOG_FATAL
Something went wrong and recovery is not possible.
Definition: log.h:188
#define AV_LOG_VERBOSE
Detailed information.
Definition: log.h:210
#define AV_LOG_INFO
Standard information.
Definition: log.h:205
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:194
int av_reduce(int *dst_num, int *dst_den, int64_t num, int64_t den, int64_t max)
Reduce a fraction.
Definition: rational.c:35
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:237
void * av_mallocz_array(size_t nmemb, size_t size)
Allocate a memory block for an array with av_mallocz().
Definition: mem.c:190
int av_image_fill_pointers(uint8_t *data[4], enum AVPixelFormat pix_fmt, int height, uint8_t *ptr, const int linesizes[4])
Fill plane data pointers for an image with pixel format pix_fmt and height height.
Definition: imgutils.c:146
void av_image_copy(uint8_t *dst_data[4], int dst_linesizes[4], const uint8_t *src_data[4], const int src_linesizes[4], enum AVPixelFormat pix_fmt, int width, int height)
Copy image in src_data to dst_data.
Definition: imgutils.c:425
AVPictureType
Definition: avutil.h:272
@ AV_PICTURE_TYPE_I
Intra.
Definition: avutil.h:274
@ AV_PICTURE_TYPE_BI
BI type.
Definition: avutil.h:280
@ AV_PICTURE_TYPE_P
Predicted.
Definition: avutil.h:275
@ AV_PICTURE_TYPE_B
Bi-dir predicted.
Definition: avutil.h:276
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
#define P3
#define HW_CONFIG_ENCODER_DEVICE(format, device_type_)
Definition: hwconfig.h:96
#define HW_CONFIG_ENCODER_FRAMES(format, device_type_)
Definition: hwconfig.h:99
@ AV_HWDEVICE_TYPE_D3D11VA
Definition: hwcontext.h:35
@ AV_HWDEVICE_TYPE_CUDA
Definition: hwcontext.h:30
An API-specific header for AV_HWDEVICE_TYPE_CUDA.
misc image utilities
int i
Definition: input.c:407
AVCPBProperties * ff_add_cpb_side_data(AVCodecContext *avctx)
Add a CPB properties side data to an encoding context.
Definition: utils.c:1084
int ff_alloc_timecode_sei(const AVFrame *frame, AVRational rate, size_t prefix_len, void **data, size_t *sei_size)
Check AVFrame for S12M timecode side data and allocate and fill TC SEI message with timecode info.
Definition: utils.c:1124
void av_fifo_reset(AVFifoBuffer *f)
Reset the AVFifoBuffer to the state right after av_fifo_alloc, in particular it is emptied.
Definition: fifo.c:71
void av_fifo_freep(AVFifoBuffer **f)
Free an AVFifoBuffer and reset pointer to NULL.
Definition: fifo.c:63
int av_fifo_size(const AVFifoBuffer *f)
Return the amount of data in bytes in the AVFifoBuffer, that is the amount of data you can read from ...
Definition: fifo.c:77
int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void(*func)(void *, void *, int))
Feed data from an AVFifoBuffer to a user-supplied callback.
Definition: fifo.c:213
AVFifoBuffer * av_fifo_alloc(unsigned int size)
Initialize an AVFifoBuffer.
Definition: fifo.c:43
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int(*func)(void *, void *, int))
Feed data from a user-supplied callback to an AVFifoBuffer.
Definition: fifo.c:122
common internal API header
#define FF_DISABLE_DEPRECATION_WARNINGS
Definition: internal.h:83
#define FF_ENABLE_DEPRECATION_WARNINGS
Definition: internal.h:84
Memory handling functions.
int dummy
Definition: motion.c:64
static void nvenc_override_rate_control(AVCodecContext *avctx)
Definition: nvenc.c:824
static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
Definition: nvenc.c:266
static av_cold void set_constqp(AVCodecContext *avctx)
Definition: nvenc.c:715
static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
Definition: nvenc.c:1143
static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
Definition: nvenc.c:395
static int nvenc_push_context(AVCodecContext *avctx)
Definition: nvenc.c:310
av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
Definition: nvenc.c:1645
static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
Definition: nvenc.c:529
static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
Definition: nvenc.c:1734
int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
Definition: nvenc.c:2310
static int nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
Definition: nvenc.c:2176
static const struct @102 nvenc_errors[]
static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
Definition: nvenc.c:2084
static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
Definition: nvenc.c:1945
static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
Definition: nvenc.c:1768
static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
Definition: nvenc.c:859
static int nvenc_check_capabilities(AVCodecContext *avctx)
Definition: nvenc.c:412
#define IS_YUV444(pix_fmt)
Definition: nvenc.c:81
const AVCodecHWConfigInternal *const ff_nvenc_hw_configs[]
Definition: nvenc.c:67
static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
Definition: nvenc.c:1535
static void nvenc_codec_specific_pic_params(AVCodecContext *avctx, NV_ENC_PIC_PARAMS *params, NV_ENC_SEI_PAYLOAD *sei_data, int sei_count)
Definition: nvenc.c:1884
NVENCSTATUS nverr
Definition: nvenc.c:85
static void timestamp_queue_enqueue(AVFifoBuffer *queue, int64_t timestamp)
Definition: nvenc.c:1917
static int nvenc_set_timestamp(AVCodecContext *avctx, NV_ENC_LOCK_BITSTREAM *params, AVPacket *pkt)
Definition: nvenc.c:1931
#define PRESET_ALIAS(alias, name,...)
Definition: nvenc.c:157
static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
Definition: nvenc.c:1415
static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
Definition: nvenc.c:1232
const char * desc
Definition: nvenc.c:87
enum AVPixelFormat ff_nvenc_pix_fmts[]
Definition: nvenc.c:51
static void compute_dar(AVCodecContext *avctx, int *dw, int *dh)
Definition: nvenc.c:1245
static int nvenc_map_error(NVENCSTATUS err, const char **desc)
Definition: nvenc.c:117
static int nvenc_print_error(AVCodecContext *avctx, NVENCSTATUS err, const char *error_string)
Definition: nvenc.c:132
static av_cold int nvenc_open_session(AVCodecContext *avctx)
Definition: nvenc.c:333
static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
Definition: nvenc.c:1494
static int64_t timestamp_queue_dequeue(AVFifoBuffer *queue)
Definition: nvenc.c:1922
static void nvenc_map_preset(NvencContext *ctx)
Definition: nvenc.c:162
#define IS_10BIT(pix_fmt)
Definition: nvenc.c:77
static av_cold void set_lossless(AVCodecContext *avctx)
Definition: nvenc.c:810
#define CHECK_CU(x)
Definition: nvenc.c:39
static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
Definition: nvenc.c:1438
#define IS_CBR(rc)
Definition: nvenc.c:44
static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame, NvencSurface *nvenc_frame)
Definition: nvenc.c:1822
static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
Definition: nvenc.c:898
#define NVENC_CAP
Definition: nvenc.c:41
av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
Definition: nvenc.c:1568
static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
Definition: nvenc.c:216
int averr
Definition: nvenc.c:86
static int nvenc_check_codec_support(AVCodecContext *avctx)
Definition: nvenc.c:359
static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface, NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
Definition: nvenc.c:1704
static int nvenc_pop_context(AVCodecContext *avctx)
Definition: nvenc.c:321
static av_cold void set_vbr(AVCodecContext *avctx)
Definition: nvenc.c:748
#define PRESET(name,...)
Definition: nvenc.c:160
static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
Definition: nvenc.c:1044
static av_cold int nvenc_setup_device(AVCodecContext *avctx)
Definition: nvenc.c:604
static int output_ready(AVCodecContext *avctx, int flush)
Definition: nvenc.c:2072
static NvencSurface * get_free_frame(NvencContext *ctx)
Definition: nvenc.c:1692
static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
Definition: nvenc.c:1259
av_cold void ff_nvenc_encode_flush(AVCodecContext *avctx)
Definition: nvenc.c:2361
@ LIST_DEVICES
Definition: nvenc.h:147
@ ANY_DEVICE
Definition: nvenc.h:148
@ NVENC_DEPRECATED_PRESET
Definition: nvenc.h:143
@ NVENC_TWO_PASSES
Definition: nvenc.h:141
@ NVENC_LOSSLESS
Definition: nvenc.h:139
@ NVENC_LOWLATENCY
Definition: nvenc.h:138
@ NVENC_ONE_PASS
Definition: nvenc.h:140
@ NV_ENC_H264_PROFILE_MAIN
Definition: nvenc.h:126
@ NV_ENC_H264_PROFILE_HIGH
Definition: nvenc.h:127
@ NV_ENC_H264_PROFILE_HIGH_444P
Definition: nvenc.h:128
@ NV_ENC_H264_PROFILE_BASELINE
Definition: nvenc.h:125
@ NV_ENC_HEVC_PROFILE_REXT
Definition: nvenc.h:134
@ NV_ENC_HEVC_PROFILE_MAIN
Definition: nvenc.h:132
@ NV_ENC_HEVC_PROFILE_MAIN_10
Definition: nvenc.h:133
#define RC_MODE_DEPRECATED
Definition: nvenc.h:41
#define MAX_REGISTERED_FRAMES
Definition: nvenc.h:40
const char * av_get_pix_fmt_name(enum AVPixelFormat pix_fmt)
Return the short name for a pixel format, NULL in case pix_fmt is unknown.
Definition: pixdesc.c:2489
#define AV_PIX_FMT_0RGB32
Definition: pixfmt.h:376
@ AVCOL_RANGE_JPEG
Full range content.
Definition: pixfmt.h:586
#define AV_PIX_FMT_P010
Definition: pixfmt.h:448
#define AV_PIX_FMT_P016
Definition: pixfmt.h:449
AVPixelFormat
Pixel format.
Definition: pixfmt.h:64
@ AV_PIX_FMT_NV12
planar YUV 4:2:0, 12bpp, 1 plane for Y and 1 plane for the UV components, which are interleaved (firs...
Definition: pixfmt.h:89
@ AV_PIX_FMT_NONE
Definition: pixfmt.h:65
@ AV_PIX_FMT_YUV420P
planar YUV 4:2:0, 12bpp, (1 Cr & Cb sample per 2x2 Y samples)
Definition: pixfmt.h:66
@ AV_PIX_FMT_CUDA
HW acceleration through CUDA.
Definition: pixfmt.h:235
@ AV_PIX_FMT_YUV444P
planar YUV 4:4:4, 24bpp, (1 Cr & Cb sample per 1x1 Y samples)
Definition: pixfmt.h:71
@ AV_PIX_FMT_D3D11
Hardware surfaces for Direct3D11.
Definition: pixfmt.h:313
@ AV_PIX_FMT_YUVJ422P
planar YUV 4:2:2, 16bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV422P and setting col...
Definition: pixfmt.h:79
@ AV_PIX_FMT_YUVJ444P
planar YUV 4:4:4, 24bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV444P and setting col...
Definition: pixfmt.h:80
@ AV_PIX_FMT_YUVJ420P
planar YUV 4:2:0, 12bpp, full scale (JPEG), deprecated in favor of AV_PIX_FMT_YUV420P and setting col...
Definition: pixfmt.h:78
#define AV_PIX_FMT_YUV444P16
Definition: pixfmt.h:412
#define AV_PIX_FMT_0BGR32
Definition: pixfmt.h:377
const char * name
Definition: qsvenc.c:46
@ SEI_TYPE_TIME_CODE
Definition: sei.h:95
#define FF_ARRAY_ELEMS(a)
uint8_t * data
The data buffer.
Definition: buffer.h:92
This structure describes the bitrate properties of an encoded bitstream.
Definition: avcodec.h:453
int avg_bitrate
Average bitrate of the stream, in bits per second.
Definition: avcodec.h:477
int buffer_size
The size of the buffer to which the ratecontrol is applied, in bits.
Definition: avcodec.h:486
int max_bitrate
Maximum bitrate of the stream, in bits per second.
Definition: avcodec.h:459
This struct is allocated as AVHWDeviceContext.hwctx.
main external API structure.
Definition: avcodec.h:536
enum AVPixelFormat pix_fmt
Pixel format, see AV_PIX_FMT_xxx.
Definition: avcodec.h:746
int width
picture width / height.
Definition: avcodec.h:709
int rc_buffer_size
decoder bitstream buffer size
Definition: avcodec.h:1405
int global_quality
Global quality for codecs which cannot change it per frame.
Definition: avcodec.h:602
enum AVColorRange color_range
MPEG vs JPEG YUV range.
Definition: avcodec.h:1171
float b_quant_offset
qscale offset between IP and B-frames
Definition: avcodec.h:818
enum AVColorPrimaries color_primaries
Chromaticity coordinates of the source primaries.
Definition: avcodec.h:1150
AVBufferRef * hw_frames_ctx
A reference to the AVHWFramesContext describing the input (for encoding) or output (decoding) frames.
Definition: avcodec.h:2222
int max_b_frames
maximum number of B-frames between non-B-frames Note: The output will be delayed by max_b_frames+1 re...
Definition: avcodec.h:796
int qmin
minimum quantizer
Definition: avcodec.h:1384
float b_quant_factor
qscale factor between IP and B-frames If > 0 then the last P-frame quantizer will be used (q= lastp_q...
Definition: avcodec.h:805
AVRational framerate
Definition: avcodec.h:2075
AVRational sample_aspect_ratio
sample aspect ratio (0 if unknown) That is the width of a pixel divided by the height of the pixel.
Definition: avcodec.h:915
attribute_deprecated AVFrame * coded_frame
the picture in the bitstream
Definition: avcodec.h:1768
int ticks_per_frame
For some codecs, the time base is closer to the field rate than the frame rate.
Definition: avcodec.h:668
int has_b_frames
Size of the frame reordering buffer in the decoder.
Definition: avcodec.h:826
int64_t bit_rate
the average bitrate
Definition: avcodec.h:586
const struct AVCodec * codec
Definition: avcodec.h:545
int profile
profile
Definition: avcodec.h:1862
enum AVColorSpace colorspace
YUV colorspace type.
Definition: avcodec.h:1164
int gop_size
the number of pictures in a group of pictures, or 0 for intra_only
Definition: avcodec.h:731
int refs
number of reference frames
Definition: avcodec.h:1124
int64_t rc_max_rate
maximum bitrate
Definition: avcodec.h:1420
int qmax
maximum quantizer
Definition: avcodec.h:1391
enum AVColorTransferCharacteristic color_trc
Color Transfer Characteristic.
Definition: avcodec.h:1157
AVRational time_base
This is the fundamental unit of time (in seconds) in terms of which frame timestamps are represented.
Definition: avcodec.h:659
int flags
AV_CODEC_FLAG_*.
Definition: avcodec.h:616
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:637
AVBufferRef * hw_device_ctx
A reference to the AVHWDeviceContext describing the device which will be used by a hardware encoder/d...
Definition: avcodec.h:2274
int extradata_size
Definition: avcodec.h:638
float i_quant_factor
qscale factor between P- and I-frames If > 0 then the last P-frame quantizer will be used (q = lastp_...
Definition: avcodec.h:841
struct AVCodecInternal * internal
Private context used for internal data.
Definition: avcodec.h:571
void * priv_data
Definition: avcodec.h:563
float i_quant_offset
qscale offset between P and I-frames
Definition: avcodec.h:848
int draining
checks API usage: after codec draining, flush is required to resume operation
Definition: internal.h:185
enum AVCodecID id
Definition: codec.h:211
This struct is allocated as AVHWDeviceContext.hwctx.
ID3D11Device * device
Device used for texture creation and access.
int flags
Flags modifying the (de)muxer behaviour.
Definition: avformat.h:1363
This structure describes decoded (raw) audio or video data.
Definition: frame.h:318
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:411
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:332
AVBufferRef * hw_frames_ctx
For hwaccel-format frames, this should be a reference to the AVHWFramesContext describing the frame.
Definition: frame.h:657
AVBufferRef * buf[AV_NUM_DATA_POINTERS]
AVBuffer references backing the data for this frame.
Definition: frame.h:509
int top_field_first
If the content is interlaced, is top field displayed first.
Definition: frame.h:470
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:349
int format
format of the frame, -1 if unknown or unset Values correspond to enum AVPixelFormat for video frames,...
Definition: frame.h:391
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:401
This struct aggregates all the (hardware/vendor-specific) "high-level" state, i.e.
Definition: hwcontext.h:61
void * hwctx
The format-specific data, allocated and freed by libavutil along with this context.
Definition: hwcontext.h:92
enum AVHWDeviceType type
This field identifies the underlying API used for hardware access.
Definition: hwcontext.h:79
This struct describes a set or pool of "hardware" frames (i.e.
Definition: hwcontext.h:124
enum AVPixelFormat format
The pixel format identifying the underlying HW surface type.
Definition: hwcontext.h:209
enum AVPixelFormat sw_format
The pixel format identifying the actual data layout of the hardware frames.
Definition: hwcontext.h:222
AVHWDeviceContext * device_ctx
The parent AVHWDeviceContext.
Definition: hwcontext.h:149
This structure stores compressed data.
Definition: packet.h:346
int flags
A combination of AV_PKT_FLAG values.
Definition: packet.h:375
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: packet.h:362
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed.
Definition: packet.h:368
uint8_t * data
Definition: packet.h:369
int num
Numerator.
Definition: rational.h:59
int den
Denominator.
Definition: rational.h:60
const GUID guid
Definition: nvenc.c:153
int flags
Definition: nvenc.c:154
NvencFunctions * nvenc_dl
Definition: nvenc.h:94
int nvenc_device_count
Definition: nvenc.h:97
CudaFunctions * cuda_dl
Definition: nvenc.h:93
NV_ENCODE_API_FUNCTION_LIST nvenc_funcs
Definition: nvenc.h:96
NV_ENC_OUTPUT_PTR output_surface
Definition: nvenc.h:87
int width
Definition: nvenc.h:83
AVFrame * in_ref
Definition: nvenc.h:81
NV_ENC_BUFFER_FORMAT format
Definition: nvenc.h:88
int reg_idx
Definition: nvenc.h:82
int height
Definition: nvenc.h:84
NV_ENC_INPUT_PTR input_surface
Definition: nvenc.h:80
int pitch
Definition: nvenc.h:85
uint8_t level
Definition: svq3.c:206
#define av_free(p)
#define av_freep(p)
#define av_malloc(s)
#define av_log(a,...)
static void error(const char *err)
AVPacket * pkt
Definition: movenc.c:59
AVFormatContext * ctx
Definition: movenc.c:48
#define height
#define width
#define BD
if(ret< 0)
Definition: vf_mcdeint.c:282
static const Preset presets[]