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