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