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