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