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