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