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