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