]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
avutil/hwcontext_cuda: Define and use common CHECK_CU()
[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     return 0;
1074 }
1075
1076 static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
1077 {
1078     switch (avctx->codec->id) {
1079     case AV_CODEC_ID_H264:
1080         return nvenc_setup_h264_config(avctx);
1081     case AV_CODEC_ID_HEVC:
1082         return nvenc_setup_hevc_config(avctx);
1083     /* Earlier switch/case will return if unknown codec is passed. */
1084     }
1085
1086     return 0;
1087 }
1088
1089 static void compute_dar(AVCodecContext *avctx, int *dw, int *dh) {
1090     int sw, sh;
1091
1092     sw = avctx->width;
1093     sh = avctx->height;
1094
1095     if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
1096         sw *= avctx->sample_aspect_ratio.num;
1097         sh *= avctx->sample_aspect_ratio.den;
1098     }
1099
1100     av_reduce(dw, dh, sw, sh, 1024 * 1024);
1101 }
1102
1103 static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
1104 {
1105     NvencContext *ctx = avctx->priv_data;
1106     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1107     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1108
1109     NV_ENC_PRESET_CONFIG preset_config = { 0 };
1110     NVENCSTATUS nv_status = NV_ENC_SUCCESS;
1111     AVCPBProperties *cpb_props;
1112     int res = 0;
1113     int dw, dh;
1114
1115     ctx->encode_config.version = NV_ENC_CONFIG_VER;
1116     ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
1117
1118     ctx->init_encode_params.encodeHeight = avctx->height;
1119     ctx->init_encode_params.encodeWidth = avctx->width;
1120
1121     ctx->init_encode_params.encodeConfig = &ctx->encode_config;
1122
1123     nvenc_map_preset(ctx);
1124
1125     preset_config.version = NV_ENC_PRESET_CONFIG_VER;
1126     preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
1127
1128     nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
1129                                                     ctx->init_encode_params.encodeGUID,
1130                                                     ctx->init_encode_params.presetGUID,
1131                                                     &preset_config);
1132     if (nv_status != NV_ENC_SUCCESS)
1133         return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
1134
1135     memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
1136
1137     ctx->encode_config.version = NV_ENC_CONFIG_VER;
1138
1139     compute_dar(avctx, &dw, &dh);
1140     ctx->init_encode_params.darHeight = dh;
1141     ctx->init_encode_params.darWidth = dw;
1142
1143     ctx->init_encode_params.frameRateNum = avctx->time_base.den;
1144     ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
1145
1146     ctx->init_encode_params.enableEncodeAsync = 0;
1147     ctx->init_encode_params.enablePTD = 1;
1148
1149     if (ctx->weighted_pred == 1)
1150         ctx->init_encode_params.enableWeightedPrediction = 1;
1151
1152     if (ctx->bluray_compat) {
1153         ctx->aud = 1;
1154         avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
1155         avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
1156         switch (avctx->codec->id) {
1157         case AV_CODEC_ID_H264:
1158             /* maximum level depends on used resolution */
1159             break;
1160         case AV_CODEC_ID_HEVC:
1161             ctx->level = NV_ENC_LEVEL_HEVC_51;
1162             ctx->tier = NV_ENC_TIER_HEVC_HIGH;
1163             break;
1164         }
1165     }
1166
1167     if (avctx->gop_size > 0) {
1168         if (avctx->max_b_frames >= 0) {
1169             /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
1170             ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
1171         }
1172
1173         ctx->encode_config.gopLength = avctx->gop_size;
1174     } else if (avctx->gop_size == 0) {
1175         ctx->encode_config.frameIntervalP = 0;
1176         ctx->encode_config.gopLength = 1;
1177     }
1178
1179     ctx->initial_pts[0] = AV_NOPTS_VALUE;
1180     ctx->initial_pts[1] = AV_NOPTS_VALUE;
1181
1182     nvenc_recalc_surfaces(avctx);
1183
1184     nvenc_setup_rate_control(avctx);
1185
1186     if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
1187         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
1188     } else {
1189         ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
1190     }
1191
1192     res = nvenc_setup_codec_config(avctx);
1193     if (res)
1194         return res;
1195
1196     res = nvenc_push_context(avctx);
1197     if (res < 0)
1198         return res;
1199
1200     nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
1201
1202     res = nvenc_pop_context(avctx);
1203     if (res < 0)
1204         return res;
1205
1206     if (nv_status != NV_ENC_SUCCESS) {
1207         return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
1208     }
1209
1210     if (ctx->encode_config.frameIntervalP > 1)
1211         avctx->has_b_frames = 2;
1212
1213     if (ctx->encode_config.rcParams.averageBitRate > 0)
1214         avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
1215
1216     cpb_props = ff_add_cpb_side_data(avctx);
1217     if (!cpb_props)
1218         return AVERROR(ENOMEM);
1219     cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
1220     cpb_props->avg_bitrate = avctx->bit_rate;
1221     cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
1222
1223     return 0;
1224 }
1225
1226 static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
1227 {
1228     switch (pix_fmt) {
1229     case AV_PIX_FMT_YUV420P:
1230         return NV_ENC_BUFFER_FORMAT_YV12_PL;
1231     case AV_PIX_FMT_NV12:
1232         return NV_ENC_BUFFER_FORMAT_NV12_PL;
1233     case AV_PIX_FMT_P010:
1234     case AV_PIX_FMT_P016:
1235         return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
1236     case AV_PIX_FMT_YUV444P:
1237         return NV_ENC_BUFFER_FORMAT_YUV444_PL;
1238     case AV_PIX_FMT_YUV444P16:
1239         return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
1240     case AV_PIX_FMT_0RGB32:
1241         return NV_ENC_BUFFER_FORMAT_ARGB;
1242     case AV_PIX_FMT_0BGR32:
1243         return NV_ENC_BUFFER_FORMAT_ABGR;
1244     default:
1245         return NV_ENC_BUFFER_FORMAT_UNDEFINED;
1246     }
1247 }
1248
1249 static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
1250 {
1251     NvencContext *ctx = avctx->priv_data;
1252     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1253     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1254     NvencSurface* tmp_surface = &ctx->surfaces[idx];
1255
1256     NVENCSTATUS nv_status;
1257     NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
1258     allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
1259
1260     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1261         ctx->surfaces[idx].in_ref = av_frame_alloc();
1262         if (!ctx->surfaces[idx].in_ref)
1263             return AVERROR(ENOMEM);
1264     } else {
1265         NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
1266
1267         ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
1268         if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1269             av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1270                    av_get_pix_fmt_name(ctx->data_pix_fmt));
1271             return AVERROR(EINVAL);
1272         }
1273
1274         allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
1275         allocSurf.width = avctx->width;
1276         allocSurf.height = avctx->height;
1277         allocSurf.bufferFmt = ctx->surfaces[idx].format;
1278
1279         nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
1280         if (nv_status != NV_ENC_SUCCESS) {
1281             return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
1282         }
1283
1284         ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
1285         ctx->surfaces[idx].width = allocSurf.width;
1286         ctx->surfaces[idx].height = allocSurf.height;
1287     }
1288
1289     nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
1290     if (nv_status != NV_ENC_SUCCESS) {
1291         int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
1292         if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1293             p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
1294         av_frame_free(&ctx->surfaces[idx].in_ref);
1295         return err;
1296     }
1297
1298     ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1299     ctx->surfaces[idx].size = allocOut.size;
1300
1301     av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
1302
1303     return 0;
1304 }
1305
1306 static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
1307 {
1308     NvencContext *ctx = avctx->priv_data;
1309     int i, res = 0, res2;
1310
1311     ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1312     if (!ctx->surfaces)
1313         return AVERROR(ENOMEM);
1314
1315     ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1316     if (!ctx->timestamp_list)
1317         return AVERROR(ENOMEM);
1318
1319     ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1320     if (!ctx->unused_surface_queue)
1321         return AVERROR(ENOMEM);
1322
1323     ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1324     if (!ctx->output_surface_queue)
1325         return AVERROR(ENOMEM);
1326     ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
1327     if (!ctx->output_surface_ready_queue)
1328         return AVERROR(ENOMEM);
1329
1330     res = nvenc_push_context(avctx);
1331     if (res < 0)
1332         return res;
1333
1334     for (i = 0; i < ctx->nb_surfaces; i++) {
1335         if ((res = nvenc_alloc_surface(avctx, i)) < 0)
1336             goto fail;
1337     }
1338
1339 fail:
1340     res2 = nvenc_pop_context(avctx);
1341     if (res2 < 0)
1342         return res2;
1343
1344     return res;
1345 }
1346
1347 static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1348 {
1349     NvencContext *ctx = avctx->priv_data;
1350     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1351     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1352
1353     NVENCSTATUS nv_status;
1354     uint32_t outSize = 0;
1355     char tmpHeader[256];
1356     NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1357     payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1358
1359     payload.spsppsBuffer = tmpHeader;
1360     payload.inBufferSize = sizeof(tmpHeader);
1361     payload.outSPSPPSPayloadSize = &outSize;
1362
1363     nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1364     if (nv_status != NV_ENC_SUCCESS) {
1365         return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
1366     }
1367
1368     avctx->extradata_size = outSize;
1369     avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1370
1371     if (!avctx->extradata) {
1372         return AVERROR(ENOMEM);
1373     }
1374
1375     memcpy(avctx->extradata, tmpHeader, outSize);
1376
1377     return 0;
1378 }
1379
1380 av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1381 {
1382     NvencContext *ctx               = avctx->priv_data;
1383     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1384     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1385     int i, res;
1386
1387     /* the encoder has to be flushed before it can be closed */
1388     if (ctx->nvencoder) {
1389         NV_ENC_PIC_PARAMS params        = { .version        = NV_ENC_PIC_PARAMS_VER,
1390                                             .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1391
1392         res = nvenc_push_context(avctx);
1393         if (res < 0)
1394             return res;
1395
1396         p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
1397     }
1398
1399     av_fifo_freep(&ctx->timestamp_list);
1400     av_fifo_freep(&ctx->output_surface_ready_queue);
1401     av_fifo_freep(&ctx->output_surface_queue);
1402     av_fifo_freep(&ctx->unused_surface_queue);
1403
1404     if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
1405         for (i = 0; i < ctx->nb_registered_frames; i++) {
1406             if (ctx->registered_frames[i].mapped)
1407                 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
1408             if (ctx->registered_frames[i].regptr)
1409                 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1410         }
1411         ctx->nb_registered_frames = 0;
1412     }
1413
1414     if (ctx->surfaces) {
1415         for (i = 0; i < ctx->nb_surfaces; ++i) {
1416             if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
1417                 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1418             av_frame_free(&ctx->surfaces[i].in_ref);
1419             p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1420         }
1421     }
1422     av_freep(&ctx->surfaces);
1423     ctx->nb_surfaces = 0;
1424
1425     if (ctx->nvencoder) {
1426         p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
1427
1428         res = nvenc_pop_context(avctx);
1429         if (res < 0)
1430             return res;
1431     }
1432     ctx->nvencoder = NULL;
1433
1434     if (ctx->cu_context_internal)
1435         CHECK_CU(dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal));
1436     ctx->cu_context = ctx->cu_context_internal = NULL;
1437
1438 #if CONFIG_D3D11VA
1439     if (ctx->d3d11_device) {
1440         ID3D11Device_Release(ctx->d3d11_device);
1441         ctx->d3d11_device = NULL;
1442     }
1443 #endif
1444
1445     nvenc_free_functions(&dl_fn->nvenc_dl);
1446     cuda_free_functions(&dl_fn->cuda_dl);
1447
1448     dl_fn->nvenc_device_count = 0;
1449
1450     av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1451
1452     return 0;
1453 }
1454
1455 av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1456 {
1457     NvencContext *ctx = avctx->priv_data;
1458     int ret;
1459
1460     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1461         AVHWFramesContext *frames_ctx;
1462         if (!avctx->hw_frames_ctx) {
1463             av_log(avctx, AV_LOG_ERROR,
1464                    "hw_frames_ctx must be set when using GPU frames as input\n");
1465             return AVERROR(EINVAL);
1466         }
1467         frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1468         if (frames_ctx->format != avctx->pix_fmt) {
1469             av_log(avctx, AV_LOG_ERROR,
1470                    "hw_frames_ctx must match the GPU frame type\n");
1471             return AVERROR(EINVAL);
1472         }
1473         ctx->data_pix_fmt = frames_ctx->sw_format;
1474     } else {
1475         ctx->data_pix_fmt = avctx->pix_fmt;
1476     }
1477
1478     if ((ret = nvenc_load_libraries(avctx)) < 0)
1479         return ret;
1480
1481     if ((ret = nvenc_setup_device(avctx)) < 0)
1482         return ret;
1483
1484     if ((ret = nvenc_setup_encoder(avctx)) < 0)
1485         return ret;
1486
1487     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1488         return ret;
1489
1490     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1491         if ((ret = nvenc_setup_extradata(avctx)) < 0)
1492             return ret;
1493     }
1494
1495     return 0;
1496 }
1497
1498 static NvencSurface *get_free_frame(NvencContext *ctx)
1499 {
1500     NvencSurface *tmp_surf;
1501
1502     if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1503         // queue empty
1504         return NULL;
1505
1506     av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1507     return tmp_surf;
1508 }
1509
1510 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1511             NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1512 {
1513     int dst_linesize[4] = {
1514         lock_buffer_params->pitch,
1515         lock_buffer_params->pitch,
1516         lock_buffer_params->pitch,
1517         lock_buffer_params->pitch
1518     };
1519     uint8_t *dst_data[4];
1520     int ret;
1521
1522     if (frame->format == AV_PIX_FMT_YUV420P)
1523         dst_linesize[1] = dst_linesize[2] >>= 1;
1524
1525     ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1526                                  lock_buffer_params->bufferDataPtr, dst_linesize);
1527     if (ret < 0)
1528         return ret;
1529
1530     if (frame->format == AV_PIX_FMT_YUV420P)
1531         FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1532
1533     av_image_copy(dst_data, dst_linesize,
1534                   (const uint8_t**)frame->data, frame->linesize, frame->format,
1535                   avctx->width, avctx->height);
1536
1537     return 0;
1538 }
1539
1540 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1541 {
1542     NvencContext *ctx = avctx->priv_data;
1543     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1544     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1545     NVENCSTATUS nv_status;
1546
1547     int i;
1548
1549     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1550         for (i = 0; i < ctx->nb_registered_frames; i++) {
1551             if (!ctx->registered_frames[i].mapped) {
1552                 if (ctx->registered_frames[i].regptr) {
1553                     nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1554                     if (nv_status != NV_ENC_SUCCESS)
1555                         return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1556                     ctx->registered_frames[i].ptr = NULL;
1557                     ctx->registered_frames[i].regptr = NULL;
1558                 }
1559                 return i;
1560             }
1561         }
1562     } else {
1563         return ctx->nb_registered_frames++;
1564     }
1565
1566     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1567     return AVERROR(ENOMEM);
1568 }
1569
1570 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1571 {
1572     NvencContext *ctx = avctx->priv_data;
1573     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1574     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1575
1576     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1577     NV_ENC_REGISTER_RESOURCE reg;
1578     int i, idx, ret;
1579
1580     for (i = 0; i < ctx->nb_registered_frames; i++) {
1581         if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1582             return i;
1583         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])
1584             return i;
1585     }
1586
1587     idx = nvenc_find_free_reg_resource(avctx);
1588     if (idx < 0)
1589         return idx;
1590
1591     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1592     reg.width              = frames_ctx->width;
1593     reg.height             = frames_ctx->height;
1594     reg.pitch              = frame->linesize[0];
1595     reg.resourceToRegister = frame->data[0];
1596
1597     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1598         reg.resourceType   = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1599     }
1600     else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1601         reg.resourceType     = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1602         reg.subResourceIndex = (intptr_t)frame->data[1];
1603     }
1604
1605     reg.bufferFormat       = nvenc_map_buffer_format(frames_ctx->sw_format);
1606     if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1607         av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1608                av_get_pix_fmt_name(frames_ctx->sw_format));
1609         return AVERROR(EINVAL);
1610     }
1611
1612     ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1613     if (ret != NV_ENC_SUCCESS) {
1614         nvenc_print_error(avctx, ret, "Error registering an input resource");
1615         return AVERROR_UNKNOWN;
1616     }
1617
1618     ctx->registered_frames[idx].ptr       = frame->data[0];
1619     ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1620     ctx->registered_frames[idx].regptr    = reg.registeredResource;
1621     return idx;
1622 }
1623
1624 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1625                                       NvencSurface *nvenc_frame)
1626 {
1627     NvencContext *ctx = avctx->priv_data;
1628     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1629     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1630
1631     int res;
1632     NVENCSTATUS nv_status;
1633
1634     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1635         int reg_idx = nvenc_register_frame(avctx, frame);
1636         if (reg_idx < 0) {
1637             av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1638             return reg_idx;
1639         }
1640
1641         res = av_frame_ref(nvenc_frame->in_ref, frame);
1642         if (res < 0)
1643             return res;
1644
1645         if (!ctx->registered_frames[reg_idx].mapped) {
1646             ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1647             ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1648             nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1649             if (nv_status != NV_ENC_SUCCESS) {
1650                 av_frame_unref(nvenc_frame->in_ref);
1651                 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1652             }
1653         }
1654
1655         ctx->registered_frames[reg_idx].mapped += 1;
1656
1657         nvenc_frame->reg_idx                   = reg_idx;
1658         nvenc_frame->input_surface             = ctx->registered_frames[reg_idx].in_map.mappedResource;
1659         nvenc_frame->format                    = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1660         nvenc_frame->pitch                     = frame->linesize[0];
1661
1662         return 0;
1663     } else {
1664         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1665
1666         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1667         lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1668
1669         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1670         if (nv_status != NV_ENC_SUCCESS) {
1671             return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1672         }
1673
1674         nvenc_frame->pitch = lockBufferParams.pitch;
1675         res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1676
1677         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1678         if (nv_status != NV_ENC_SUCCESS) {
1679             return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1680         }
1681
1682         return res;
1683     }
1684 }
1685
1686 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1687                                             NV_ENC_PIC_PARAMS *params,
1688                                             NV_ENC_SEI_PAYLOAD *sei_data)
1689 {
1690     NvencContext *ctx = avctx->priv_data;
1691
1692     switch (avctx->codec->id) {
1693     case AV_CODEC_ID_H264:
1694         params->codecPicParams.h264PicParams.sliceMode =
1695             ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1696         params->codecPicParams.h264PicParams.sliceModeData =
1697             ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1698         if (sei_data) {
1699             params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1700             params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1701         }
1702
1703       break;
1704     case AV_CODEC_ID_HEVC:
1705         params->codecPicParams.hevcPicParams.sliceMode =
1706             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1707         params->codecPicParams.hevcPicParams.sliceModeData =
1708             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1709         if (sei_data) {
1710             params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1711             params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1712         }
1713
1714         break;
1715     }
1716 }
1717
1718 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1719 {
1720     av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
1721 }
1722
1723 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1724 {
1725     int64_t timestamp = AV_NOPTS_VALUE;
1726     if (av_fifo_size(queue) > 0)
1727         av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
1728
1729     return timestamp;
1730 }
1731
1732 static int nvenc_set_timestamp(AVCodecContext *avctx,
1733                                NV_ENC_LOCK_BITSTREAM *params,
1734                                AVPacket *pkt)
1735 {
1736     NvencContext *ctx = avctx->priv_data;
1737
1738     pkt->pts = params->outputTimeStamp;
1739
1740     /* generate the first dts by linearly extrapolating the
1741      * first two pts values to the past */
1742     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1743         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1744         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1745         int64_t delta;
1746
1747         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1748             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1749             return AVERROR(ERANGE);
1750         delta = ts1 - ts0;
1751
1752         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1753             (delta > 0 && ts0 < INT64_MIN + delta))
1754             return AVERROR(ERANGE);
1755         pkt->dts = ts0 - delta;
1756
1757         ctx->first_packet_output = 1;
1758         return 0;
1759     }
1760
1761     pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1762
1763     return 0;
1764 }
1765
1766 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1767 {
1768     NvencContext *ctx = avctx->priv_data;
1769     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1770     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1771
1772     uint32_t slice_mode_data;
1773     uint32_t *slice_offsets = NULL;
1774     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1775     NVENCSTATUS nv_status;
1776     int res = 0;
1777
1778     enum AVPictureType pict_type;
1779
1780     switch (avctx->codec->id) {
1781     case AV_CODEC_ID_H264:
1782       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1783       break;
1784     case AV_CODEC_ID_H265:
1785       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1786       break;
1787     default:
1788       av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1789       res = AVERROR(EINVAL);
1790       goto error;
1791     }
1792     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1793
1794     if (!slice_offsets) {
1795         res = AVERROR(ENOMEM);
1796         goto error;
1797     }
1798
1799     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1800
1801     lock_params.doNotWait = 0;
1802     lock_params.outputBitstream = tmpoutsurf->output_surface;
1803     lock_params.sliceOffsets = slice_offsets;
1804
1805     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1806     if (nv_status != NV_ENC_SUCCESS) {
1807         res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1808         goto error;
1809     }
1810
1811     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1812         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1813         goto error;
1814     }
1815
1816     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1817
1818     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1819     if (nv_status != NV_ENC_SUCCESS) {
1820         res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1821         goto error;
1822     }
1823
1824
1825     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1826         ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1827         if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1828             nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1829             if (nv_status != NV_ENC_SUCCESS) {
1830                 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1831                 goto error;
1832             }
1833             nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1834             if (nv_status != NV_ENC_SUCCESS) {
1835                 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1836                 goto error;
1837             }
1838             ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1839             ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1840         } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1841             res = AVERROR_BUG;
1842             goto error;
1843         }
1844
1845         av_frame_unref(tmpoutsurf->in_ref);
1846
1847         tmpoutsurf->input_surface = NULL;
1848     }
1849
1850     switch (lock_params.pictureType) {
1851     case NV_ENC_PIC_TYPE_IDR:
1852         pkt->flags |= AV_PKT_FLAG_KEY;
1853     case NV_ENC_PIC_TYPE_I:
1854         pict_type = AV_PICTURE_TYPE_I;
1855         break;
1856     case NV_ENC_PIC_TYPE_P:
1857         pict_type = AV_PICTURE_TYPE_P;
1858         break;
1859     case NV_ENC_PIC_TYPE_B:
1860         pict_type = AV_PICTURE_TYPE_B;
1861         break;
1862     case NV_ENC_PIC_TYPE_BI:
1863         pict_type = AV_PICTURE_TYPE_BI;
1864         break;
1865     default:
1866         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1867         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1868         res = AVERROR_EXTERNAL;
1869         goto error;
1870     }
1871
1872 #if FF_API_CODED_FRAME
1873 FF_DISABLE_DEPRECATION_WARNINGS
1874     avctx->coded_frame->pict_type = pict_type;
1875 FF_ENABLE_DEPRECATION_WARNINGS
1876 #endif
1877
1878     ff_side_data_set_encoder_stats(pkt,
1879         (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1880
1881     res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1882     if (res < 0)
1883         goto error2;
1884
1885     av_free(slice_offsets);
1886
1887     return 0;
1888
1889 error:
1890     timestamp_queue_dequeue(ctx->timestamp_list);
1891
1892 error2:
1893     av_free(slice_offsets);
1894
1895     return res;
1896 }
1897
1898 static int output_ready(AVCodecContext *avctx, int flush)
1899 {
1900     NvencContext *ctx = avctx->priv_data;
1901     int nb_ready, nb_pending;
1902
1903     /* when B-frames are enabled, we wait for two initial timestamps to
1904      * calculate the first dts */
1905     if (!flush && avctx->max_b_frames > 0 &&
1906         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1907         return 0;
1908
1909     nb_ready   = av_fifo_size(ctx->output_surface_ready_queue)   / sizeof(NvencSurface*);
1910     nb_pending = av_fifo_size(ctx->output_surface_queue)         / sizeof(NvencSurface*);
1911     if (flush)
1912         return nb_ready > 0;
1913     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1914 }
1915
1916 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1917 {
1918     NvencContext *ctx = avctx->priv_data;
1919     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1920     NVENCSTATUS ret;
1921
1922     NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1923     int needs_reconfig = 0;
1924     int needs_encode_config = 0;
1925     int reconfig_bitrate = 0, reconfig_dar = 0;
1926     int dw, dh;
1927
1928     params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1929     params.reInitEncodeParams = ctx->init_encode_params;
1930
1931     compute_dar(avctx, &dw, &dh);
1932     if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
1933         av_log(avctx, AV_LOG_VERBOSE,
1934                "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1935                ctx->init_encode_params.darWidth,
1936                ctx->init_encode_params.darHeight, dw, dh);
1937
1938         params.reInitEncodeParams.darHeight = dh;
1939         params.reInitEncodeParams.darWidth = dw;
1940
1941         needs_reconfig = 1;
1942         reconfig_dar = 1;
1943     }
1944
1945     if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
1946         if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
1947             av_log(avctx, AV_LOG_VERBOSE,
1948                    "avg bitrate change: %d -> %d\n",
1949                    params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1950                    (uint32_t)avctx->bit_rate);
1951
1952             params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
1953             reconfig_bitrate = 1;
1954         }
1955
1956         if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
1957             av_log(avctx, AV_LOG_VERBOSE,
1958                    "max bitrate change: %d -> %d\n",
1959                    params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
1960                    (uint32_t)avctx->rc_max_rate);
1961
1962             params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
1963             reconfig_bitrate = 1;
1964         }
1965
1966         if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
1967             av_log(avctx, AV_LOG_VERBOSE,
1968                    "vbv buffer size change: %d -> %d\n",
1969                    params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
1970                    avctx->rc_buffer_size);
1971
1972             params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
1973             reconfig_bitrate = 1;
1974         }
1975
1976         if (reconfig_bitrate) {
1977             params.resetEncoder = 1;
1978             params.forceIDR = 1;
1979
1980             needs_encode_config = 1;
1981             needs_reconfig = 1;
1982         }
1983     }
1984
1985     if (!needs_encode_config)
1986         params.reInitEncodeParams.encodeConfig = NULL;
1987
1988     if (needs_reconfig) {
1989         ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, &params);
1990         if (ret != NV_ENC_SUCCESS) {
1991             nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
1992         } else {
1993             if (reconfig_dar) {
1994                 ctx->init_encode_params.darHeight = dh;
1995                 ctx->init_encode_params.darWidth = dw;
1996             }
1997
1998             if (reconfig_bitrate) {
1999                 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2000                 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2001                 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2002             }
2003
2004         }
2005     }
2006 }
2007
2008 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2009 {
2010     NVENCSTATUS nv_status;
2011     NvencSurface *tmp_out_surf, *in_surf;
2012     int res, res2;
2013     NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2014     size_t sei_size;
2015
2016     NvencContext *ctx = avctx->priv_data;
2017     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2018     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2019
2020     NV_ENC_PIC_PARAMS pic_params = { 0 };
2021     pic_params.version = NV_ENC_PIC_PARAMS_VER;
2022
2023     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2024         return AVERROR(EINVAL);
2025
2026     if (ctx->encoder_flushing) {
2027         if (avctx->internal->draining)
2028             return AVERROR_EOF;
2029
2030         ctx->encoder_flushing = 0;
2031         ctx->first_packet_output = 0;
2032         ctx->initial_pts[0] = AV_NOPTS_VALUE;
2033         ctx->initial_pts[1] = AV_NOPTS_VALUE;
2034         av_fifo_reset(ctx->timestamp_list);
2035     }
2036
2037     if (frame) {
2038         in_surf = get_free_frame(ctx);
2039         if (!in_surf)
2040             return AVERROR(EAGAIN);
2041
2042         res = nvenc_push_context(avctx);
2043         if (res < 0)
2044             return res;
2045
2046         reconfig_encoder(avctx, frame);
2047
2048         res = nvenc_upload_frame(avctx, frame, in_surf);
2049
2050         res2 = nvenc_pop_context(avctx);
2051         if (res2 < 0)
2052             return res2;
2053
2054         if (res)
2055             return res;
2056
2057         pic_params.inputBuffer = in_surf->input_surface;
2058         pic_params.bufferFmt = in_surf->format;
2059         pic_params.inputWidth = in_surf->width;
2060         pic_params.inputHeight = in_surf->height;
2061         pic_params.inputPitch = in_surf->pitch;
2062         pic_params.outputBitstream = in_surf->output_surface;
2063
2064         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2065             if (frame->top_field_first)
2066                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2067             else
2068                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2069         } else {
2070             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2071         }
2072
2073         if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2074             pic_params.encodePicFlags =
2075                 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2076         } else {
2077             pic_params.encodePicFlags = 0;
2078         }
2079
2080         pic_params.inputTimeStamp = frame->pts;
2081
2082         if (ctx->a53_cc && av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2083             if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2084                 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2085             }
2086
2087             if (sei_data) {
2088                 sei_data->payloadSize = (uint32_t)sei_size;
2089                 sei_data->payloadType = 4;
2090                 sei_data->payload = (uint8_t*)(sei_data + 1);
2091             }
2092         }
2093
2094         nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2095     } else {
2096         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2097         ctx->encoder_flushing = 1;
2098     }
2099
2100     res = nvenc_push_context(avctx);
2101     if (res < 0)
2102         return res;
2103
2104     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2105     av_free(sei_data);
2106
2107     res = nvenc_pop_context(avctx);
2108     if (res < 0)
2109         return res;
2110
2111     if (nv_status != NV_ENC_SUCCESS &&
2112         nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2113         return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2114
2115     if (frame) {
2116         av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2117         timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2118
2119         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2120             ctx->initial_pts[0] = frame->pts;
2121         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2122             ctx->initial_pts[1] = frame->pts;
2123     }
2124
2125     /* all the pending buffers are now ready for output */
2126     if (nv_status == NV_ENC_SUCCESS) {
2127         while (av_fifo_size(ctx->output_surface_queue) > 0) {
2128             av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2129             av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2130         }
2131     }
2132
2133     return 0;
2134 }
2135
2136 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2137 {
2138     NvencSurface *tmp_out_surf;
2139     int res, res2;
2140
2141     NvencContext *ctx = avctx->priv_data;
2142
2143     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2144         return AVERROR(EINVAL);
2145
2146     if (output_ready(avctx, ctx->encoder_flushing)) {
2147         av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2148
2149         res = nvenc_push_context(avctx);
2150         if (res < 0)
2151             return res;
2152
2153         res = process_output_surface(avctx, pkt, tmp_out_surf);
2154
2155         res2 = nvenc_pop_context(avctx);
2156         if (res2 < 0)
2157             return res2;
2158
2159         if (res)
2160             return res;
2161
2162         av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2163     } else if (ctx->encoder_flushing) {
2164         return AVERROR_EOF;
2165     } else {
2166         return AVERROR(EAGAIN);
2167     }
2168
2169     return 0;
2170 }
2171
2172 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2173                           const AVFrame *frame, int *got_packet)
2174 {
2175     NvencContext *ctx = avctx->priv_data;
2176     int res;
2177
2178     if (!ctx->encoder_flushing) {
2179         res = ff_nvenc_send_frame(avctx, frame);
2180         if (res < 0)
2181             return res;
2182     }
2183
2184     res = ff_nvenc_receive_packet(avctx, pkt);
2185     if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2186         *got_packet = 0;
2187     } else if (res < 0) {
2188         return res;
2189     } else {
2190         *got_packet = 1;
2191     }
2192
2193     return 0;
2194 }