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