]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvenc.c
d61955c03ac3d4f3ade6653b7f2056ac083c66a4
[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         if (avctx->hw_frames_ctx) {
1490             AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1491             if (frames_ctx->format != avctx->pix_fmt) {
1492                 av_log(avctx, AV_LOG_ERROR,
1493                        "hw_frames_ctx must match the GPU frame type\n");
1494                 return AVERROR(EINVAL);
1495             }
1496             ctx->data_pix_fmt = frames_ctx->sw_format;
1497         } else if (avctx->sw_pix_fmt && avctx->sw_pix_fmt != AV_PIX_FMT_NONE) {
1498             ctx->data_pix_fmt = avctx->sw_pix_fmt;
1499         } else {
1500             av_log(avctx, AV_LOG_ERROR,
1501                    "either hw_frames_ctx or sw_pix_fmt is required for hw frame input\n");
1502             return AVERROR(EINVAL);
1503         }
1504     } else {
1505         ctx->data_pix_fmt = avctx->pix_fmt;
1506     }
1507
1508     if ((ret = nvenc_load_libraries(avctx)) < 0)
1509         return ret;
1510
1511     if ((ret = nvenc_setup_device(avctx)) < 0)
1512         return ret;
1513
1514     if ((ret = nvenc_setup_encoder(avctx)) < 0)
1515         return ret;
1516
1517     if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1518         return ret;
1519
1520     if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
1521         if ((ret = nvenc_setup_extradata(avctx)) < 0)
1522             return ret;
1523     }
1524
1525     return 0;
1526 }
1527
1528 static NvencSurface *get_free_frame(NvencContext *ctx)
1529 {
1530     NvencSurface *tmp_surf;
1531
1532     if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
1533         // queue empty
1534         return NULL;
1535
1536     av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
1537     return tmp_surf;
1538 }
1539
1540 static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
1541             NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
1542 {
1543     int dst_linesize[4] = {
1544         lock_buffer_params->pitch,
1545         lock_buffer_params->pitch,
1546         lock_buffer_params->pitch,
1547         lock_buffer_params->pitch
1548     };
1549     uint8_t *dst_data[4];
1550     int ret;
1551
1552     if (frame->format == AV_PIX_FMT_YUV420P)
1553         dst_linesize[1] = dst_linesize[2] >>= 1;
1554
1555     ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
1556                                  lock_buffer_params->bufferDataPtr, dst_linesize);
1557     if (ret < 0)
1558         return ret;
1559
1560     if (frame->format == AV_PIX_FMT_YUV420P)
1561         FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
1562
1563     av_image_copy(dst_data, dst_linesize,
1564                   (const uint8_t**)frame->data, frame->linesize, frame->format,
1565                   avctx->width, avctx->height);
1566
1567     return 0;
1568 }
1569
1570 static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
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     NVENCSTATUS nv_status;
1576
1577     int i;
1578
1579     if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1580         for (i = 0; i < ctx->nb_registered_frames; i++) {
1581             if (!ctx->registered_frames[i].mapped) {
1582                 if (ctx->registered_frames[i].regptr) {
1583                     nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1584                     if (nv_status != NV_ENC_SUCCESS)
1585                         return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
1586                     ctx->registered_frames[i].ptr = NULL;
1587                     ctx->registered_frames[i].regptr = NULL;
1588                 }
1589                 return i;
1590             }
1591         }
1592     } else {
1593         return ctx->nb_registered_frames++;
1594     }
1595
1596     av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1597     return AVERROR(ENOMEM);
1598 }
1599
1600 static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1601 {
1602     NvencContext *ctx = avctx->priv_data;
1603     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1604     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1605
1606     enum AVPixelFormat sw_format = ctx->data_pix_fmt;
1607     NV_ENC_REGISTER_RESOURCE reg;
1608     int i, idx, ret;
1609
1610     if (frame->hw_frames_ctx) {
1611         AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
1612         sw_format = frames_ctx->sw_format;
1613     }
1614
1615     for (i = 0; i < ctx->nb_registered_frames; i++) {
1616         if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
1617             return i;
1618         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])
1619             return i;
1620     }
1621
1622     idx = nvenc_find_free_reg_resource(avctx);
1623     if (idx < 0)
1624         return idx;
1625
1626     reg.version            = NV_ENC_REGISTER_RESOURCE_VER;
1627     reg.width              = frame->width;
1628     reg.height             = frame->height;
1629     reg.pitch              = frame->linesize[0];
1630     reg.resourceToRegister = frame->data[0];
1631
1632     if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1633         reg.resourceType   = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1634     }
1635     else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1636         reg.resourceType     = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
1637         reg.subResourceIndex = (intptr_t)frame->data[1];
1638     }
1639
1640     reg.bufferFormat       = nvenc_map_buffer_format(sw_format);
1641     if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
1642         av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
1643                av_get_pix_fmt_name(sw_format));
1644         return AVERROR(EINVAL);
1645     }
1646
1647     ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1648     if (ret != NV_ENC_SUCCESS) {
1649         nvenc_print_error(avctx, ret, "Error registering an input resource");
1650         return AVERROR_UNKNOWN;
1651     }
1652
1653     ctx->registered_frames[idx].ptr       = frame->data[0];
1654     ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
1655     ctx->registered_frames[idx].regptr    = reg.registeredResource;
1656     return idx;
1657 }
1658
1659 static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1660                                       NvencSurface *nvenc_frame)
1661 {
1662     NvencContext *ctx = avctx->priv_data;
1663     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1664     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1665
1666     int res;
1667     NVENCSTATUS nv_status;
1668
1669     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1670         int reg_idx = nvenc_register_frame(avctx, frame);
1671         if (reg_idx < 0) {
1672             av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
1673             return reg_idx;
1674         }
1675
1676         res = av_frame_ref(nvenc_frame->in_ref, frame);
1677         if (res < 0)
1678             return res;
1679
1680         if (!ctx->registered_frames[reg_idx].mapped) {
1681             ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1682             ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1683             nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
1684             if (nv_status != NV_ENC_SUCCESS) {
1685                 av_frame_unref(nvenc_frame->in_ref);
1686                 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1687             }
1688         }
1689
1690         ctx->registered_frames[reg_idx].mapped += 1;
1691
1692         nvenc_frame->reg_idx                   = reg_idx;
1693         nvenc_frame->input_surface             = ctx->registered_frames[reg_idx].in_map.mappedResource;
1694         nvenc_frame->format                    = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
1695         nvenc_frame->pitch                     = frame->linesize[0];
1696
1697         return 0;
1698     } else {
1699         NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1700
1701         lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1702         lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1703
1704         nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1705         if (nv_status != NV_ENC_SUCCESS) {
1706             return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1707         }
1708
1709         nvenc_frame->pitch = lockBufferParams.pitch;
1710         res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1711
1712         nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1713         if (nv_status != NV_ENC_SUCCESS) {
1714             return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1715         }
1716
1717         return res;
1718     }
1719 }
1720
1721 static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1722                                             NV_ENC_PIC_PARAMS *params,
1723                                             NV_ENC_SEI_PAYLOAD *sei_data)
1724 {
1725     NvencContext *ctx = avctx->priv_data;
1726
1727     switch (avctx->codec->id) {
1728     case AV_CODEC_ID_H264:
1729         params->codecPicParams.h264PicParams.sliceMode =
1730             ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1731         params->codecPicParams.h264PicParams.sliceModeData =
1732             ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1733         if (sei_data) {
1734             params->codecPicParams.h264PicParams.seiPayloadArray = sei_data;
1735             params->codecPicParams.h264PicParams.seiPayloadArrayCnt = 1;
1736         }
1737
1738       break;
1739     case AV_CODEC_ID_HEVC:
1740         params->codecPicParams.hevcPicParams.sliceMode =
1741             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1742         params->codecPicParams.hevcPicParams.sliceModeData =
1743             ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1744         if (sei_data) {
1745             params->codecPicParams.hevcPicParams.seiPayloadArray = sei_data;
1746             params->codecPicParams.hevcPicParams.seiPayloadArrayCnt = 1;
1747         }
1748
1749         break;
1750     }
1751 }
1752
1753 static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1754 {
1755     av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
1756 }
1757
1758 static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1759 {
1760     int64_t timestamp = AV_NOPTS_VALUE;
1761     if (av_fifo_size(queue) > 0)
1762         av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
1763
1764     return timestamp;
1765 }
1766
1767 static int nvenc_set_timestamp(AVCodecContext *avctx,
1768                                NV_ENC_LOCK_BITSTREAM *params,
1769                                AVPacket *pkt)
1770 {
1771     NvencContext *ctx = avctx->priv_data;
1772
1773     pkt->pts = params->outputTimeStamp;
1774
1775     /* generate the first dts by linearly extrapolating the
1776      * first two pts values to the past */
1777     if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1778         ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1779         int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1780         int64_t delta;
1781
1782         if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1783             (ts0 > 0 && ts1 < INT64_MIN + ts0))
1784             return AVERROR(ERANGE);
1785         delta = ts1 - ts0;
1786
1787         if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1788             (delta > 0 && ts0 < INT64_MIN + delta))
1789             return AVERROR(ERANGE);
1790         pkt->dts = ts0 - delta;
1791
1792         ctx->first_packet_output = 1;
1793         return 0;
1794     }
1795
1796     pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1797
1798     return 0;
1799 }
1800
1801 static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
1802 {
1803     NvencContext *ctx = avctx->priv_data;
1804     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1805     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1806
1807     uint32_t slice_mode_data;
1808     uint32_t *slice_offsets = NULL;
1809     NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1810     NVENCSTATUS nv_status;
1811     int res = 0;
1812
1813     enum AVPictureType pict_type;
1814
1815     switch (avctx->codec->id) {
1816     case AV_CODEC_ID_H264:
1817       slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1818       break;
1819     case AV_CODEC_ID_H265:
1820       slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1821       break;
1822     default:
1823       av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
1824       res = AVERROR(EINVAL);
1825       goto error;
1826     }
1827     slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1828
1829     if (!slice_offsets) {
1830         res = AVERROR(ENOMEM);
1831         goto error;
1832     }
1833
1834     lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1835
1836     lock_params.doNotWait = 0;
1837     lock_params.outputBitstream = tmpoutsurf->output_surface;
1838     lock_params.sliceOffsets = slice_offsets;
1839
1840     nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1841     if (nv_status != NV_ENC_SUCCESS) {
1842         res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
1843         goto error;
1844     }
1845
1846     if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
1847         p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1848         goto error;
1849     }
1850
1851     memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1852
1853     nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1854     if (nv_status != NV_ENC_SUCCESS) {
1855         res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
1856         goto error;
1857     }
1858
1859
1860     if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
1861         ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
1862         if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
1863             nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
1864             if (nv_status != NV_ENC_SUCCESS) {
1865                 res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
1866                 goto error;
1867             }
1868             nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
1869             if (nv_status != NV_ENC_SUCCESS) {
1870                 res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
1871                 goto error;
1872             }
1873             ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
1874             ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
1875         } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
1876             res = AVERROR_BUG;
1877             goto error;
1878         }
1879
1880         av_frame_unref(tmpoutsurf->in_ref);
1881
1882         tmpoutsurf->input_surface = NULL;
1883     }
1884
1885     switch (lock_params.pictureType) {
1886     case NV_ENC_PIC_TYPE_IDR:
1887         pkt->flags |= AV_PKT_FLAG_KEY;
1888     case NV_ENC_PIC_TYPE_I:
1889         pict_type = AV_PICTURE_TYPE_I;
1890         break;
1891     case NV_ENC_PIC_TYPE_P:
1892         pict_type = AV_PICTURE_TYPE_P;
1893         break;
1894     case NV_ENC_PIC_TYPE_B:
1895         pict_type = AV_PICTURE_TYPE_B;
1896         break;
1897     case NV_ENC_PIC_TYPE_BI:
1898         pict_type = AV_PICTURE_TYPE_BI;
1899         break;
1900     default:
1901         av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1902         av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1903         res = AVERROR_EXTERNAL;
1904         goto error;
1905     }
1906
1907 #if FF_API_CODED_FRAME
1908 FF_DISABLE_DEPRECATION_WARNINGS
1909     avctx->coded_frame->pict_type = pict_type;
1910 FF_ENABLE_DEPRECATION_WARNINGS
1911 #endif
1912
1913     ff_side_data_set_encoder_stats(pkt,
1914         (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
1915
1916     res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1917     if (res < 0)
1918         goto error2;
1919
1920     av_free(slice_offsets);
1921
1922     return 0;
1923
1924 error:
1925     timestamp_queue_dequeue(ctx->timestamp_list);
1926
1927 error2:
1928     av_free(slice_offsets);
1929
1930     return res;
1931 }
1932
1933 static int output_ready(AVCodecContext *avctx, int flush)
1934 {
1935     NvencContext *ctx = avctx->priv_data;
1936     int nb_ready, nb_pending;
1937
1938     /* when B-frames are enabled, we wait for two initial timestamps to
1939      * calculate the first dts */
1940     if (!flush && avctx->max_b_frames > 0 &&
1941         (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1942         return 0;
1943
1944     nb_ready   = av_fifo_size(ctx->output_surface_ready_queue)   / sizeof(NvencSurface*);
1945     nb_pending = av_fifo_size(ctx->output_surface_queue)         / sizeof(NvencSurface*);
1946     if (flush)
1947         return nb_ready > 0;
1948     return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
1949 }
1950
1951 static void reconfig_encoder(AVCodecContext *avctx, const AVFrame *frame)
1952 {
1953     NvencContext *ctx = avctx->priv_data;
1954     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
1955     NVENCSTATUS ret;
1956
1957     NV_ENC_RECONFIGURE_PARAMS params = { 0 };
1958     int needs_reconfig = 0;
1959     int needs_encode_config = 0;
1960     int reconfig_bitrate = 0, reconfig_dar = 0;
1961     int dw, dh;
1962
1963     params.version = NV_ENC_RECONFIGURE_PARAMS_VER;
1964     params.reInitEncodeParams = ctx->init_encode_params;
1965
1966     compute_dar(avctx, &dw, &dh);
1967     if (dw != ctx->init_encode_params.darWidth || dh != ctx->init_encode_params.darHeight) {
1968         av_log(avctx, AV_LOG_VERBOSE,
1969                "aspect ratio change (DAR): %d:%d -> %d:%d\n",
1970                ctx->init_encode_params.darWidth,
1971                ctx->init_encode_params.darHeight, dw, dh);
1972
1973         params.reInitEncodeParams.darHeight = dh;
1974         params.reInitEncodeParams.darWidth = dw;
1975
1976         needs_reconfig = 1;
1977         reconfig_dar = 1;
1978     }
1979
1980     if (ctx->rc != NV_ENC_PARAMS_RC_CONSTQP && ctx->support_dyn_bitrate) {
1981         if (avctx->bit_rate > 0 && params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate != avctx->bit_rate) {
1982             av_log(avctx, AV_LOG_VERBOSE,
1983                    "avg bitrate change: %d -> %d\n",
1984                    params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate,
1985                    (uint32_t)avctx->bit_rate);
1986
1987             params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate = avctx->bit_rate;
1988             reconfig_bitrate = 1;
1989         }
1990
1991         if (avctx->rc_max_rate > 0 && ctx->encode_config.rcParams.maxBitRate != avctx->rc_max_rate) {
1992             av_log(avctx, AV_LOG_VERBOSE,
1993                    "max bitrate change: %d -> %d\n",
1994                    params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate,
1995                    (uint32_t)avctx->rc_max_rate);
1996
1997             params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate = avctx->rc_max_rate;
1998             reconfig_bitrate = 1;
1999         }
2000
2001         if (avctx->rc_buffer_size > 0 && ctx->encode_config.rcParams.vbvBufferSize != avctx->rc_buffer_size) {
2002             av_log(avctx, AV_LOG_VERBOSE,
2003                    "vbv buffer size change: %d -> %d\n",
2004                    params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize,
2005                    avctx->rc_buffer_size);
2006
2007             params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize = avctx->rc_buffer_size;
2008             reconfig_bitrate = 1;
2009         }
2010
2011         if (reconfig_bitrate) {
2012             params.resetEncoder = 1;
2013             params.forceIDR = 1;
2014
2015             needs_encode_config = 1;
2016             needs_reconfig = 1;
2017         }
2018     }
2019
2020     if (!needs_encode_config)
2021         params.reInitEncodeParams.encodeConfig = NULL;
2022
2023     if (needs_reconfig) {
2024         ret = p_nvenc->nvEncReconfigureEncoder(ctx->nvencoder, &params);
2025         if (ret != NV_ENC_SUCCESS) {
2026             nvenc_print_error(avctx, ret, "failed to reconfigure nvenc");
2027         } else {
2028             if (reconfig_dar) {
2029                 ctx->init_encode_params.darHeight = dh;
2030                 ctx->init_encode_params.darWidth = dw;
2031             }
2032
2033             if (reconfig_bitrate) {
2034                 ctx->encode_config.rcParams.averageBitRate = params.reInitEncodeParams.encodeConfig->rcParams.averageBitRate;
2035                 ctx->encode_config.rcParams.maxBitRate = params.reInitEncodeParams.encodeConfig->rcParams.maxBitRate;
2036                 ctx->encode_config.rcParams.vbvBufferSize = params.reInitEncodeParams.encodeConfig->rcParams.vbvBufferSize;
2037             }
2038
2039         }
2040     }
2041 }
2042
2043 int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
2044 {
2045     NVENCSTATUS nv_status;
2046     NvencSurface *tmp_out_surf, *in_surf;
2047     int res, res2;
2048     NV_ENC_SEI_PAYLOAD *sei_data = NULL;
2049     size_t sei_size;
2050
2051     NvencContext *ctx = avctx->priv_data;
2052     NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
2053     NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
2054
2055     NV_ENC_PIC_PARAMS pic_params = { 0 };
2056     pic_params.version = NV_ENC_PIC_PARAMS_VER;
2057
2058     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2059         return AVERROR(EINVAL);
2060
2061     if (ctx->encoder_flushing)
2062         return AVERROR_EOF;
2063
2064     if (frame) {
2065         in_surf = get_free_frame(ctx);
2066         if (!in_surf)
2067             return AVERROR(EAGAIN);
2068
2069         res = nvenc_push_context(avctx);
2070         if (res < 0)
2071             return res;
2072
2073         reconfig_encoder(avctx, frame);
2074
2075         res = nvenc_upload_frame(avctx, frame, in_surf);
2076
2077         res2 = nvenc_pop_context(avctx);
2078         if (res2 < 0)
2079             return res2;
2080
2081         if (res)
2082             return res;
2083
2084         pic_params.inputBuffer = in_surf->input_surface;
2085         pic_params.bufferFmt = in_surf->format;
2086         pic_params.inputWidth = in_surf->width;
2087         pic_params.inputHeight = in_surf->height;
2088         pic_params.inputPitch = in_surf->pitch;
2089         pic_params.outputBitstream = in_surf->output_surface;
2090
2091         if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
2092             if (frame->top_field_first)
2093                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
2094             else
2095                 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
2096         } else {
2097             pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
2098         }
2099
2100         if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
2101             pic_params.encodePicFlags =
2102                 ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
2103         } else {
2104             pic_params.encodePicFlags = 0;
2105         }
2106
2107         pic_params.inputTimeStamp = frame->pts;
2108
2109         if (av_frame_get_side_data(frame, AV_FRAME_DATA_A53_CC)) {
2110             if (ff_alloc_a53_sei(frame, sizeof(NV_ENC_SEI_PAYLOAD), (void**)&sei_data, &sei_size) < 0) {
2111                 av_log(ctx, AV_LOG_ERROR, "Not enough memory for closed captions, skipping\n");
2112             }
2113
2114             if (sei_data) {
2115                 sei_data->payloadSize = (uint32_t)sei_size;
2116                 sei_data->payloadType = 4;
2117                 sei_data->payload = (uint8_t*)(sei_data + 1);
2118             }
2119         }
2120
2121         nvenc_codec_specific_pic_params(avctx, &pic_params, sei_data);
2122     } else {
2123         pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
2124         ctx->encoder_flushing = 1;
2125     }
2126
2127     res = nvenc_push_context(avctx);
2128     if (res < 0)
2129         return res;
2130
2131     nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
2132     av_free(sei_data);
2133
2134     res = nvenc_pop_context(avctx);
2135     if (res < 0)
2136         return res;
2137
2138     if (nv_status != NV_ENC_SUCCESS &&
2139         nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
2140         return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
2141
2142     if (frame) {
2143         av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
2144         timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
2145
2146         if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
2147             ctx->initial_pts[0] = frame->pts;
2148         else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
2149             ctx->initial_pts[1] = frame->pts;
2150     }
2151
2152     /* all the pending buffers are now ready for output */
2153     if (nv_status == NV_ENC_SUCCESS) {
2154         while (av_fifo_size(ctx->output_surface_queue) > 0) {
2155             av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2156             av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2157         }
2158     }
2159
2160     return 0;
2161 }
2162
2163 int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
2164 {
2165     NvencSurface *tmp_out_surf;
2166     int res, res2;
2167
2168     NvencContext *ctx = avctx->priv_data;
2169
2170     if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
2171         return AVERROR(EINVAL);
2172
2173     if (output_ready(avctx, ctx->encoder_flushing)) {
2174         av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2175
2176         res = nvenc_push_context(avctx);
2177         if (res < 0)
2178             return res;
2179
2180         res = process_output_surface(avctx, pkt, tmp_out_surf);
2181
2182         res2 = nvenc_pop_context(avctx);
2183         if (res2 < 0)
2184             return res2;
2185
2186         if (res)
2187             return res;
2188
2189         av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
2190     } else if (ctx->encoder_flushing) {
2191         return AVERROR_EOF;
2192     } else {
2193         return AVERROR(EAGAIN);
2194     }
2195
2196     return 0;
2197 }
2198
2199 int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
2200                           const AVFrame *frame, int *got_packet)
2201 {
2202     NvencContext *ctx = avctx->priv_data;
2203     int res;
2204
2205     if (!ctx->encoder_flushing) {
2206         res = ff_nvenc_send_frame(avctx, frame);
2207         if (res < 0)
2208             return res;
2209     }
2210
2211     res = ff_nvenc_receive_packet(avctx, pkt);
2212     if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
2213         *got_packet = 0;
2214     } else if (res < 0) {
2215         return res;
2216     } else {
2217         *got_packet = 1;
2218     }
2219
2220     return 0;
2221 }