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