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