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