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