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