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