nvenc: Remove qmin and qmax constraints for nvenc vbr
[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),
d8f36a6a 498 PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS)
b08caa87
LB
499 };
500
501 GUIDTuple *t = &presets[ctx->preset];
502
503 ctx->params.presetGUID = t->guid;
504 ctx->flags = t->flags;
505
506 return AVERROR(EINVAL);
507}
508
352741b5 509#undef PRESET
e02e2515 510#undef PRESET_ALIAS
352741b5 511
b08caa87
LB
512static void set_constqp(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
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
520static void set_vbr(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
521{
522 if (avctx->qmin >= 0) {
523 rc->enableMinQP = 1;
524 rc->minQP.qpInterB = avctx->qmin;
525 rc->minQP.qpInterP = avctx->qmin;
526 rc->minQP.qpIntra = avctx->qmin;
527 }
528
529 if (avctx->qmax >= 0) {
530 rc->enableMaxQP = 1;
531 rc->maxQP.qpInterB = avctx->qmax;
532 rc->maxQP.qpInterP = avctx->qmax;
533 rc->maxQP.qpIntra = avctx->qmax;
534 }
535}
536
9427d92f
AK
537static void set_lossless(AVCodecContext *avctx, NV_ENC_RC_PARAMS *rc)
538{
539 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
540 rc->constQP.qpInterB = 0;
541 rc->constQP.qpInterP = 0;
542 rc->constQP.qpIntra = 0;
543}
544
b08caa87
LB
545static void nvenc_override_rate_control(AVCodecContext *avctx,
546 NV_ENC_RC_PARAMS *rc)
547{
548 NVENCContext *ctx = avctx->priv_data;
549
550 switch (ctx->rc) {
551 case NV_ENC_PARAMS_RC_CONSTQP:
552 if (avctx->global_quality < 0) {
553 av_log(avctx, AV_LOG_WARNING,
554 "The constant quality rate-control requires "
555 "the 'global_quality' option set.\n");
556 return;
557 }
558 set_constqp(avctx, rc);
559 return;
560 case NV_ENC_PARAMS_RC_2_PASS_VBR:
561 case NV_ENC_PARAMS_RC_VBR:
3303f864
GK
562 set_vbr(avctx, rc);
563 break;
b08caa87
LB
564 case NV_ENC_PARAMS_RC_VBR_MINQP:
565 if (avctx->qmin < 0) {
566 av_log(avctx, AV_LOG_WARNING,
567 "The variable bitrate rate-control requires "
568 "the 'qmin' option set.\n");
569 return;
570 }
571 set_vbr(avctx, rc);
572 break;
573 case NV_ENC_PARAMS_RC_CBR:
574 break;
575 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
576 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
577 if (!(ctx->flags & NVENC_LOWLATENCY)) {
578 av_log(avctx, AV_LOG_WARNING,
579 "The multipass rate-control requires "
580 "a low-latency preset.\n");
581 return;
582 }
583 }
584
585 rc->rateControlMode = ctx->rc;
586}
587
588static void nvenc_setup_rate_control(AVCodecContext *avctx)
589{
590 NVENCContext *ctx = avctx->priv_data;
591 NV_ENC_RC_PARAMS *rc = &ctx->config.rcParams;
592
593 if (avctx->bit_rate > 0)
594 rc->averageBitRate = avctx->bit_rate;
595
596 if (avctx->rc_max_rate > 0)
597 rc->maxBitRate = avctx->rc_max_rate;
598
599 if (ctx->rc > 0) {
600 nvenc_override_rate_control(avctx, rc);
9427d92f
AK
601 } else if (ctx->flags & NVENC_LOSSLESS) {
602 set_lossless(avctx, rc);
b08caa87
LB
603 } else if (avctx->global_quality > 0) {
604 set_constqp(avctx, rc);
3303f864
GK
605 } else {
606 if (ctx->flags & NVENC_TWO_PASSES)
607 rc->rateControlMode = NV_ENC_PARAMS_RC_2_PASS_VBR;
608 else
609 rc->rateControlMode = NV_ENC_PARAMS_RC_VBR;
b08caa87
LB
610 set_vbr(avctx, rc);
611 }
612
613 if (avctx->rc_buffer_size > 0)
614 rc->vbvBufferSize = avctx->rc_buffer_size;
615
616 if (rc->averageBitRate > 0)
617 avctx->bit_rate = rc->averageBitRate;
70de2ea4
YG
618
619#if NVENCAPI_MAJOR_VERSION >= 7
620 if (ctx->aq) {
621 ctx->config.rcParams.enableAQ = 1;
622 ctx->config.rcParams.aqStrength = ctx->aq_strength;
623 av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
624 }
625
626 if (ctx->temporal_aq) {
627 ctx->config.rcParams.enableTemporalAQ = 1;
628 av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
629 }
630
5b26d3b7 631 if (ctx->rc_lookahead > 0) {
70de2ea4
YG
632 int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
633 ctx->config.frameIntervalP - 4;
634
635 if (lkd_bound < 0) {
636 av_log(avctx, AV_LOG_WARNING,
637 "Lookahead not enabled. Increase buffer delay (-delay).\n");
638 } else {
639 ctx->config.rcParams.enableLookahead = 1;
640 ctx->config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
641 ctx->config.rcParams.disableIadapt = ctx->no_scenecut;
642 ctx->config.rcParams.disableBadapt = !ctx->b_adapt;
643 av_log(avctx, AV_LOG_VERBOSE,
644 "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
645 ctx->config.rcParams.lookaheadDepth,
646 ctx->config.rcParams.disableIadapt ? "disabled" : "enabled",
647 ctx->config.rcParams.disableBadapt ? "disabled" : "enabled");
648 }
649 }
650
651 if (ctx->strict_gop) {
652 ctx->config.rcParams.strictGOPTarget = 1;
653 av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
654 }
655
656 if (ctx->nonref_p)
657 ctx->config.rcParams.enableNonRefP = 1;
658
659 if (ctx->zerolatency)
660 ctx->config.rcParams.zeroReorderDelay = 1;
661
662 if (ctx->quality)
663 ctx->config.rcParams.targetQuality = ctx->quality;
664#endif /* NVENCAPI_MAJOR_VERSION >= 7 */
b08caa87
LB
665}
666
667static int nvenc_setup_h264_config(AVCodecContext *avctx)
668{
669 NVENCContext *ctx = avctx->priv_data;
670 NV_ENC_CONFIG *cc = &ctx->config;
671 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
672 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
673
a1df7865
AK
674 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
675 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
676 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
b08caa87
LB
677
678 vui->colourMatrix = avctx->colorspace;
679 vui->colourPrimaries = avctx->color_primaries;
680 vui->transferCharacteristics = avctx->color_trc;
681
682 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
683
a1df7865
AK
684 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
685 vui->videoFullRangeFlag;
686
7c6eb0a1
VG
687 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
688 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
795329dd 689 h264->outputAUD = 1;
b08caa87
LB
690
691 h264->maxNumRefFrames = avctx->refs;
692 h264->idrPeriod = cc->gopLength;
693
3399a26d
AK
694 h264->sliceMode = 3;
695 h264->sliceModeData = FFMAX(avctx->slices, 1);
696
9427d92f
AK
697 if (ctx->flags & NVENC_LOSSLESS)
698 h264->qpPrimeYZeroTransformBypassFlag = 1;
699
cea1fb85
TR
700 if (IS_CBR(cc->rcParams.rateControlMode)) {
701 h264->outputBufferingPeriodSEI = 1;
702 h264->outputPictureTimingSEI = 1;
703 }
704
b08caa87
LB
705 if (ctx->profile)
706 avctx->profile = ctx->profile;
707
871d0930 708 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P)
b08caa87
LB
709 h264->chromaFormatIDC = 3;
710 else
711 h264->chromaFormatIDC = 1;
712
713 switch (ctx->profile) {
714 case NV_ENC_H264_PROFILE_BASELINE:
715 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
716 break;
717 case NV_ENC_H264_PROFILE_MAIN:
718 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
719 break;
720 case NV_ENC_H264_PROFILE_HIGH:
721 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
722 break;
723 case NV_ENC_H264_PROFILE_HIGH_444:
724 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
725 break;
726 case NV_ENC_H264_PROFILE_CONSTRAINED_HIGH:
727 cc->profileGUID = NV_ENC_H264_PROFILE_CONSTRAINED_HIGH_GUID;
728 break;
729 }
730
da284837
YG
731 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
732 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
733 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
734 }
735
b08caa87
LB
736 h264->level = ctx->level;
737
738 return 0;
739}
740
741static int nvenc_setup_hevc_config(AVCodecContext *avctx)
742{
743 NVENCContext *ctx = avctx->priv_data;
744 NV_ENC_CONFIG *cc = &ctx->config;
745 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
2156c4c3
AK
746 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
747
748 vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
749 avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
750 avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
751
752 vui->colourMatrix = avctx->colorspace;
753 vui->colourPrimaries = avctx->color_primaries;
754 vui->transferCharacteristics = avctx->color_trc;
755
756 vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
757
758 vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
759 vui->videoFullRangeFlag;
b08caa87 760
7c6eb0a1
VG
761 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
762 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
795329dd 763 hevc->outputAUD = 1;
b08caa87
LB
764
765 hevc->maxNumRefFramesInDPB = avctx->refs;
766 hevc->idrPeriod = cc->gopLength;
767
cea1fb85
TR
768 if (IS_CBR(cc->rcParams.rateControlMode)) {
769 hevc->outputBufferingPeriodSEI = 1;
770 hevc->outputPictureTimingSEI = 1;
771 }
772
358c887a
YG
773 switch (ctx->profile) {
774 case NV_ENC_HEVC_PROFILE_MAIN:
775 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
776 avctx->profile = FF_PROFILE_HEVC_MAIN;
777 break;
778#if NVENCAPI_MAJOR_VERSION >= 7
779 case NV_ENC_HEVC_PROFILE_MAIN_10:
780 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
781 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
782 break;
783 case NV_ENC_HEVC_PROFILE_REXT:
784 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
785 avctx->profile = FF_PROFILE_HEVC_REXT;
786 break;
787#endif /* NVENCAPI_MAJOR_VERSION >= 7 */
788 }
789
790 // force setting profile for various input formats
791 switch (ctx->data_pix_fmt) {
792 case AV_PIX_FMT_YUV420P:
793 case AV_PIX_FMT_NV12:
794 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
795 avctx->profile = FF_PROFILE_HEVC_MAIN;
796 break;
797#if NVENCAPI_MAJOR_VERSION >= 7
798 case AV_PIX_FMT_P010:
799 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
800 avctx->profile = FF_PROFILE_HEVC_MAIN_10;
801 break;
802 case AV_PIX_FMT_YUV444P:
803 case AV_PIX_FMT_YUV444P16:
804 cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
805 avctx->profile = FF_PROFILE_HEVC_REXT;
806 break;
807#endif /* NVENCAPI_MAJOR_VERSION >= 7 */
808 }
809
810#if NVENCAPI_MAJOR_VERSION >= 7
811 hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
812 hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
813#endif /* NVENCAPI_MAJOR_VERSION >= 7 */
b08caa87 814
3399a26d
AK
815 hevc->sliceMode = 3;
816 hevc->sliceModeData = FFMAX(avctx->slices, 1);
817
b08caa87
LB
818 if (ctx->level) {
819 hevc->level = ctx->level;
820 } else {
821 hevc->level = NV_ENC_LEVEL_AUTOSELECT;
822 }
823
824 if (ctx->tier) {
825 hevc->tier = ctx->tier;
826 }
827
828 return 0;
829}
830static int nvenc_setup_codec_config(AVCodecContext *avctx)
831{
832 switch (avctx->codec->id) {
833 case AV_CODEC_ID_H264:
834 return nvenc_setup_h264_config(avctx);
835 case AV_CODEC_ID_HEVC:
836 return nvenc_setup_hevc_config(avctx);
837 }
838 return 0;
839}
840
841static int nvenc_setup_encoder(AVCodecContext *avctx)
842{
843 NVENCContext *ctx = avctx->priv_data;
844 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
845 NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
1520c6ff 846 AVCPBProperties *cpb_props;
b08caa87
LB
847 int ret;
848
849 ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
850
851 ctx->params.encodeHeight = avctx->height;
852 ctx->params.encodeWidth = avctx->width;
853
854 if (avctx->sample_aspect_ratio.num &&
855 avctx->sample_aspect_ratio.den &&
856 (avctx->sample_aspect_ratio.num != 1 ||
857 avctx->sample_aspect_ratio.den != 1)) {
858 av_reduce(&ctx->params.darWidth,
859 &ctx->params.darHeight,
860 avctx->width * avctx->sample_aspect_ratio.num,
861 avctx->height * avctx->sample_aspect_ratio.den,
862 INT_MAX / 8);
863 } else {
864 ctx->params.darHeight = avctx->height;
865 ctx->params.darWidth = avctx->width;
866 }
867
10545f84
PL
868 // De-compensate for hardware, dubiously, trying to compensate for
869 // playback at 704 pixel width.
870 if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
871 av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
872 ctx->params.darWidth * 44,
873 ctx->params.darHeight * 45,
874 1024 * 1024);
875 }
876
b08caa87
LB
877 ctx->params.frameRateNum = avctx->time_base.den;
878 ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
879
880 ctx->params.enableEncodeAsync = 0;
881 ctx->params.enablePTD = 1;
882
883 ctx->params.encodeConfig = &ctx->config;
884
00b160af 885 nvenc_map_preset(ctx);
b08caa87
LB
886
887 preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
888 preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
889
890 ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
891 ctx->params.encodeGUID,
892 ctx->params.presetGUID,
893 &preset_cfg);
39571e86
AK
894 if (ret != NV_ENC_SUCCESS)
895 return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
b08caa87
LB
896
897 memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
898
899 ctx->config.version = NV_ENC_CONFIG_VER;
900
901 if (avctx->gop_size > 0) {
902 if (avctx->max_b_frames > 0) {
b08caa87
LB
903 /* 0 is intra-only,
904 * 1 is I/P only,
41ed7ab4
VG
905 * 2 is one B-Frame,
906 * 3 two B-frames, and so on. */
b08caa87
LB
907 ctx->config.frameIntervalP = avctx->max_b_frames + 1;
908 } else if (avctx->max_b_frames == 0) {
909 ctx->config.frameIntervalP = 1;
910 }
911 ctx->config.gopLength = avctx->gop_size;
912 } else if (avctx->gop_size == 0) {
913 ctx->config.frameIntervalP = 0;
914 ctx->config.gopLength = 1;
915 }
916
917 if (ctx->config.frameIntervalP > 1)
918 avctx->max_b_frames = ctx->config.frameIntervalP - 1;
919
c59fec78
AK
920 ctx->initial_pts[0] = AV_NOPTS_VALUE;
921 ctx->initial_pts[1] = AV_NOPTS_VALUE;
922
b08caa87
LB
923 nvenc_setup_rate_control(avctx);
924
7c6eb0a1 925 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
b08caa87
LB
926 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
927 } else {
928 ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
929 }
930
931 if ((ret = nvenc_setup_codec_config(avctx)) < 0)
932 return ret;
933
934 ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
39571e86 935 if (ret != NV_ENC_SUCCESS)
cbd84b8a 936 return nvenc_print_error(avctx, ret, "InitializeEncoder failed");
b08caa87 937
1520c6ff
AK
938 cpb_props = ff_add_cpb_side_data(avctx);
939 if (!cpb_props)
940 return AVERROR(ENOMEM);
941 cpb_props->max_bitrate = avctx->rc_max_rate;
942 cpb_props->min_bitrate = avctx->rc_min_rate;
943 cpb_props->avg_bitrate = avctx->bit_rate;
944 cpb_props->buffer_size = avctx->rc_buffer_size;
945
b08caa87
LB
946 return 0;
947}
948
949static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
950{
951 NVENCContext *ctx = avctx->priv_data;
952 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
953 int ret;
b08caa87
LB
954 NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
955
871d0930 956 switch (ctx->data_pix_fmt) {
b08caa87 957 case AV_PIX_FMT_YUV420P:
871d0930 958 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
b08caa87
LB
959 break;
960 case AV_PIX_FMT_NV12:
871d0930 961 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
b08caa87
LB
962 break;
963 case AV_PIX_FMT_YUV444P:
871d0930 964 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
b08caa87 965 break;
358c887a
YG
966#if NVENCAPI_MAJOR_VERSION >= 7
967 case AV_PIX_FMT_P010:
968 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
969 break;
970 case AV_PIX_FMT_YUV444P16:
971 ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
972 break;
973#endif /* NVENCAPI_MAJOR_VERSION >= 7 */
b08caa87
LB
974 default:
975 return AVERROR_BUG;
976 }
977
871d0930
AK
978 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
979 ctx->frames[idx].in_ref = av_frame_alloc();
980 if (!ctx->frames[idx].in_ref)
981 return AVERROR(ENOMEM);
982 } else {
983 NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
984
985 in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
986
987 in_buffer.width = avctx->width;
988 in_buffer.height = avctx->height;
989
990 in_buffer.bufferFmt = ctx->frames[idx].format;
991 in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
992
993 ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
994 if (ret != NV_ENC_SUCCESS)
995 return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
b08caa87 996
871d0930
AK
997 ctx->frames[idx].in = in_buffer.inputBuffer;
998 }
b08caa87 999
871d0930 1000 out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
b08caa87 1001 /* 1MB is large enough to hold most output frames.
41ed7ab4 1002 * NVENC increases this automatically if it is not enough. */
b08caa87
LB
1003 out_buffer.size = BITSTREAM_BUFFER_SIZE;
1004
1005 out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
1006
1007 ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
39571e86
AK
1008 if (ret != NV_ENC_SUCCESS)
1009 return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
b08caa87 1010
118beda3 1011 ctx->frames[idx].out = out_buffer.bitstreamBuffer;
b08caa87
LB
1012
1013 return 0;
1014}
1015
1016static int nvenc_setup_surfaces(AVCodecContext *avctx)
1017{
1018 NVENCContext *ctx = avctx->priv_data;
1019 int i, ret;
1020
1021 ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
1022 ctx->nb_surfaces);
a1e215ea
TR
1023 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
1024
b08caa87 1025
118beda3
AK
1026 ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
1027 if (!ctx->frames)
b08caa87
LB
1028 return AVERROR(ENOMEM);
1029
1030 ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
1031 if (!ctx->timestamps)
1032 return AVERROR(ENOMEM);
118beda3 1033 ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
b08caa87
LB
1034 if (!ctx->pending)
1035 return AVERROR(ENOMEM);
118beda3 1036 ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
b08caa87
LB
1037 if (!ctx->ready)
1038 return AVERROR(ENOMEM);
1039
1040 for (i = 0; i < ctx->nb_surfaces; i++) {
1041 if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
1042 return ret;
1043 }
1044
1045 return 0;
1046}
1047
1048#define EXTRADATA_SIZE 512
1049
1050static int nvenc_setup_extradata(AVCodecContext *avctx)
1051{
1052 NVENCContext *ctx = avctx->priv_data;
1053 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1054 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1055 int ret;
1056
059a9348 1057 avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
b08caa87
LB
1058 if (!avctx->extradata)
1059 return AVERROR(ENOMEM);
1060
1061 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1062 payload.spsppsBuffer = avctx->extradata;
1063 payload.inBufferSize = EXTRADATA_SIZE;
1064 payload.outSPSPPSPayloadSize = &avctx->extradata_size;
1065
1066 ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
39571e86
AK
1067 if (ret != NV_ENC_SUCCESS)
1068 return nvenc_print_error(avctx, ret, "Cannot get the extradata");
b08caa87
LB
1069
1070 return 0;
1071}
1072
1073av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
1074{
1075 NVENCContext *ctx = avctx->priv_data;
1076 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1077 int i;
1078
aac7d6b2
AK
1079 /* the encoder has to be flushed before it can be closed */
1080 if (ctx->nvenc_ctx) {
1081 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1082 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1083
1084 nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
1085 }
1086
413d4e54
LB
1087 av_fifo_free(ctx->timestamps);
1088 av_fifo_free(ctx->pending);
1089 av_fifo_free(ctx->ready);
1090
118beda3 1091 if (ctx->frames) {
b08caa87 1092 for (i = 0; i < ctx->nb_surfaces; ++i) {
871d0930
AK
1093 if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
1094 nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
1095 } else if (ctx->frames[i].in) {
1096 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
1097 }
1098
1099 av_frame_free(&ctx->frames[i].in_ref);
118beda3 1100 nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
b08caa87
LB
1101 }
1102 }
871d0930
AK
1103 for (i = 0; i < ctx->nb_registered_frames; i++) {
1104 if (ctx->registered_frames[i].regptr)
1105 nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
1106 }
1107 ctx->nb_registered_frames = 0;
b08caa87 1108
118beda3 1109 av_freep(&ctx->frames);
b08caa87
LB
1110
1111 if (ctx->nvenc_ctx)
1112 nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
1113
871d0930
AK
1114 if (ctx->cu_context_internal)
1115 ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
b08caa87
LB
1116
1117 if (ctx->nvel.nvenc)
1118 dlclose(ctx->nvel.nvenc);
1119
c51b2c79 1120#if !CONFIG_CUDA
b08caa87
LB
1121 if (ctx->nvel.cuda)
1122 dlclose(ctx->nvel.cuda);
c51b2c79 1123#endif
b08caa87
LB
1124
1125 return 0;
1126}
1127
1128av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1129{
871d0930 1130 NVENCContext *ctx = avctx->priv_data;
b08caa87
LB
1131 int ret;
1132
871d0930
AK
1133 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1134 AVHWFramesContext *frames_ctx;
1135 if (!avctx->hw_frames_ctx) {
1136 av_log(avctx, AV_LOG_ERROR,
1137 "hw_frames_ctx must be set when using GPU frames as input\n");
1138 return AVERROR(EINVAL);
1139 }
1140 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1141 ctx->data_pix_fmt = frames_ctx->sw_format;
1142 } else {
1143 ctx->data_pix_fmt = avctx->pix_fmt;
1144 }
1145
b08caa87
LB
1146 if ((ret = nvenc_load_libraries(avctx)) < 0)
1147 return ret;
1148
1149 if ((ret = nvenc_setup_device(avctx)) < 0)
1150 return ret;
1151
1152 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1153 return ret;
1154
1155 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1156 return ret;
1157
7c6eb0a1 1158 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
b08caa87
LB
1159 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1160 return ret;
1161 }
1162
b08caa87
LB
1163 return 0;
1164}
1165
118beda3 1166static NVENCFrame *get_free_frame(NVENCContext *ctx)
b08caa87
LB
1167{
1168 int i;
1169
1170 for (i = 0; i < ctx->nb_surfaces; i++) {
118beda3
AK
1171 if (!ctx->frames[i].locked) {
1172 ctx->frames[i].locked = 1;
1173 return &ctx->frames[i];
b08caa87
LB
1174 }
1175 }
1176
1177 return NULL;
1178}
1179
1180static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
1181{
1182 uint8_t *buf = in->bufferDataPtr;
1183 int off = frame->height * in->pitch;
1184
1185 switch (frame->format) {
1186 case AV_PIX_FMT_YUV420P:
1187 av_image_copy_plane(buf, in->pitch,
1188 frame->data[0], frame->linesize[0],
1189 frame->width, frame->height);
1190 buf += off;
1191
1192 av_image_copy_plane(buf, in->pitch >> 1,
1193 frame->data[2], frame->linesize[2],
1194 frame->width >> 1, frame->height >> 1);
1195
1196 buf += off >> 2;
1197
1198 av_image_copy_plane(buf, in->pitch >> 1,
1199 frame->data[1], frame->linesize[1],
1200 frame->width >> 1, frame->height >> 1);
1201 break;
1202 case AV_PIX_FMT_NV12:
1203 av_image_copy_plane(buf, in->pitch,
1204 frame->data[0], frame->linesize[0],
1205 frame->width, frame->height);
1206 buf += off;
1207
92fdc80c 1208 av_image_copy_plane(buf, in->pitch,
b08caa87 1209 frame->data[1], frame->linesize[1],
92fdc80c 1210 frame->width, frame->height >> 1);
b08caa87 1211 break;
358c887a
YG
1212 case AV_PIX_FMT_P010:
1213 av_image_copy_plane(buf, in->pitch,
1214 frame->data[0], frame->linesize[0],
1215 frame->width << 1, frame->height);
1216 buf += off;
1217
1218 av_image_copy_plane(buf, in->pitch,
1219 frame->data[1], frame->linesize[1],
1220 frame->width << 1, frame->height >> 1);
1221 break;
b08caa87
LB
1222 case AV_PIX_FMT_YUV444P:
1223 av_image_copy_plane(buf, in->pitch,
1224 frame->data[0], frame->linesize[0],
1225 frame->width, frame->height);
1226 buf += off;
1227
1228 av_image_copy_plane(buf, in->pitch,
1229 frame->data[1], frame->linesize[1],
1230 frame->width, frame->height);
1231 buf += off;
1232
1233 av_image_copy_plane(buf, in->pitch,
1234 frame->data[2], frame->linesize[2],
1235 frame->width, frame->height);
1236 break;
358c887a
YG
1237 case AV_PIX_FMT_YUV444P16:
1238 av_image_copy_plane(buf, in->pitch,
1239 frame->data[0], frame->linesize[0],
1240 frame->width << 1, frame->height);
1241 buf += off;
1242
1243 av_image_copy_plane(buf, in->pitch,
1244 frame->data[1], frame->linesize[1],
1245 frame->width << 1, frame->height);
1246 buf += off;
1247
1248 av_image_copy_plane(buf, in->pitch,
1249 frame->data[2], frame->linesize[2],
1250 frame->width << 1, frame->height);
1251 break;
b08caa87
LB
1252 default:
1253 return AVERROR_BUG;
1254 }
1255
1256 return 0;
1257}
1258
871d0930
AK
1259static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1260{
1261 NVENCContext *ctx = avctx->priv_data;
1262 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1263 int i;
1264
1265 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1266 for (i = 0; i < ctx->nb_registered_frames; i++) {
1267 if (!ctx->registered_frames[i].mapped) {
1268 if (ctx->registered_frames[i].regptr) {
1269 nv->nvEncUnregisterResource(ctx->nvenc_ctx,
1270 ctx->registered_frames[i].regptr);
1271 ctx->registered_frames[i].regptr = NULL;
1272 }
1273 return i;
1274 }
1275 }
1276 } else {
1277 return ctx->nb_registered_frames++;
1278 }
1279
1280 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1281 return AVERROR(ENOMEM);
1282}
1283
1284static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1285{
1286 NVENCContext *ctx = avctx->priv_data;
1287 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1288 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1289 NV_ENC_REGISTER_RESOURCE reg;
1290 int i, idx, ret;
1291
1292 for (i = 0; i < ctx->nb_registered_frames; i++) {
1293 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1294 return i;
1295 }
1296
1297 idx = nvenc_find_free_reg_resource(avctx);
1298 if (idx < 0)
1299 return idx;
1300
1301 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1302 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1303 reg.width = frames_ctx->width;
1304 reg.height = frames_ctx->height;
1305 reg.bufferFormat = ctx->frames[0].format;
1306 reg.pitch = frame->linesize[0];
1307 reg.resourceToRegister = frame->data[0];
1308
1309 ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, &reg);
1310 if (ret != NV_ENC_SUCCESS) {
1311 nvenc_print_error(avctx, ret, "Error registering an input resource");
1312 return AVERROR_UNKNOWN;
1313 }
1314
1315 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1316 ctx->registered_frames[idx].regptr = reg.registeredResource;
1317 return idx;
1318}
1319
118beda3
AK
1320static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
1321 NVENCFrame *nvenc_frame)
b08caa87
LB
1322{
1323 NVENCContext *ctx = avctx->priv_data;
1324 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
b08caa87
LB
1325 int ret;
1326
871d0930
AK
1327 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1328 int reg_idx;
b08caa87 1329
871d0930
AK
1330 ret = nvenc_register_frame(avctx, frame);
1331 if (ret < 0) {
1332 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1333 return ret;
1334 }
1335 reg_idx = ret;
b08caa87 1336
871d0930
AK
1337 ret = av_frame_ref(nvenc_frame->in_ref, frame);
1338 if (ret < 0)
1339 return ret;
b08caa87 1340
871d0930
AK
1341 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1342 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
b08caa87 1343
871d0930
AK
1344 ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
1345 if (ret != NV_ENC_SUCCESS) {
1346 av_frame_unref(nvenc_frame->in_ref);
1347 return nvenc_print_error(avctx, ret, "Error mapping an input resource");
1348 }
b08caa87 1349
871d0930
AK
1350 ctx->registered_frames[reg_idx].mapped = 1;
1351 nvenc_frame->reg_idx = reg_idx;
1352 nvenc_frame->in = nvenc_frame->in_map.mappedResource;
1353 } else {
1354 NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
b08caa87 1355
871d0930
AK
1356 params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1357 params.inputBuffer = nvenc_frame->in;
b08caa87 1358
871d0930
AK
1359 ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
1360 if (ret != NV_ENC_SUCCESS)
1361 return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
1362
1363 ret = nvenc_copy_frame(&params, frame);
1364 if (ret < 0) {
1365 nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1366 return ret;
1367 }
1368
1369 ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
1370 if (ret != NV_ENC_SUCCESS)
1371 return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
1372 }
1373
1374 return 0;
b08caa87
LB
1375}
1376
1377static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
1378 NV_ENC_PIC_PARAMS *params)
1379{
1380 NVENCContext *ctx = avctx->priv_data;
1381
1382 switch (avctx->codec->id) {
1383 case AV_CODEC_ID_H264:
1384 params->codecPicParams.h264PicParams.sliceMode =
1385 ctx->config.encodeCodecConfig.h264Config.sliceMode;
1386 params->codecPicParams.h264PicParams.sliceModeData =
1387 ctx->config.encodeCodecConfig.h264Config.sliceModeData;
1388 break;
1389 case AV_CODEC_ID_HEVC:
1390 params->codecPicParams.hevcPicParams.sliceMode =
1391 ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
1392 params->codecPicParams.hevcPicParams.sliceModeData =
1393 ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
1394 break;
1395 }
1396}
1397
1398static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
1399{
1400 return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
1401}
1402
1403static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
1404{
1405 return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
1406}
1407
c59fec78 1408static int nvenc_set_timestamp(AVCodecContext *avctx,
b08caa87
LB
1409 NV_ENC_LOCK_BITSTREAM *params,
1410 AVPacket *pkt)
1411{
c59fec78
AK
1412 NVENCContext *ctx = avctx->priv_data;
1413
b08caa87
LB
1414 pkt->pts = params->outputTimeStamp;
1415 pkt->duration = params->outputDuration;
1416
c59fec78
AK
1417 /* generate the first dts by linearly extrapolating the
1418 * first two pts values to the past */
1419 if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
1420 ctx->initial_pts[1] != AV_NOPTS_VALUE) {
1421 int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
1422 int64_t delta;
1423
1424 if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
1425 (ts0 > 0 && ts1 < INT64_MIN + ts0))
1426 return AVERROR(ERANGE);
1427 delta = ts1 - ts0;
1428
1429 if ((delta < 0 && ts0 > INT64_MAX + delta) ||
1430 (delta > 0 && ts0 < INT64_MIN + delta))
1431 return AVERROR(ERANGE);
1432 pkt->dts = ts0 - delta;
1433
1434 ctx->first_packet_output = 1;
1435 return 0;
1436 }
b08caa87
LB
1437 return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
1438}
1439
d005ccc6 1440static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
b08caa87
LB
1441{
1442 NVENCContext *ctx = avctx->priv_data;
1443 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1444 NV_ENC_LOCK_BITSTREAM params = { 0 };
118beda3 1445 NVENCFrame *frame;
b08caa87
LB
1446 int ret;
1447
118beda3 1448 ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
b08caa87
LB
1449 if (ret)
1450 return ret;
1451
1452 params.version = NV_ENC_LOCK_BITSTREAM_VER;
118beda3 1453 params.outputBitstream = frame->out;
b08caa87
LB
1454
1455 ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
1456 if (ret < 0)
39571e86 1457 return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
b08caa87
LB
1458
1459 ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
1460 if (ret < 0)
1461 return ret;
1462
1463 memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
1464
118beda3 1465 ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
b08caa87 1466 if (ret < 0)
39571e86 1467 return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
b08caa87 1468
871d0930
AK
1469 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1470 nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
1471 av_frame_unref(frame->in_ref);
1472 ctx->registered_frames[frame->reg_idx].mapped = 0;
1473
1474 frame->in = NULL;
1475 }
1476
118beda3 1477 frame->locked = 0;
b08caa87 1478
c59fec78 1479 ret = nvenc_set_timestamp(avctx, &params, pkt);
b08caa87
LB
1480 if (ret < 0)
1481 return ret;
1482
1483 switch (params.pictureType) {
1484 case NV_ENC_PIC_TYPE_IDR:
1485 pkt->flags |= AV_PKT_FLAG_KEY;
40cf1bba
VG
1486#if FF_API_CODED_FRAME
1487FF_DISABLE_DEPRECATION_WARNINGS
b08caa87
LB
1488 case NV_ENC_PIC_TYPE_INTRA_REFRESH:
1489 case NV_ENC_PIC_TYPE_I:
1490 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
1491 break;
1492 case NV_ENC_PIC_TYPE_P:
1493 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
1494 break;
1495 case NV_ENC_PIC_TYPE_B:
1496 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
1497 break;
1498 case NV_ENC_PIC_TYPE_BI:
1499 avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
1500 break;
40cf1bba
VG
1501FF_ENABLE_DEPRECATION_WARNINGS
1502#endif
b08caa87
LB
1503 }
1504
1505 return 0;
1506}
1507
c59fec78
AK
1508static int output_ready(AVCodecContext *avctx, int flush)
1509{
1510 NVENCContext *ctx = avctx->priv_data;
a1e215ea 1511 int nb_ready, nb_pending;
c59fec78
AK
1512
1513 /* when B-frames are enabled, we wait for two initial timestamps to
1514 * calculate the first dts */
1515 if (!flush && avctx->max_b_frames > 0 &&
1516 (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
1517 return 0;
a1e215ea
TR
1518
1519 nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
1520 nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
1521 if (flush)
1522 return nb_ready > 0;
1523 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
c59fec78
AK
1524}
1525
b08caa87
LB
1526int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
1527 const AVFrame *frame, int *got_packet)
1528{
1529 NVENCContext *ctx = avctx->priv_data;
fb59f87c 1530 NVENCLibraryContext *nvel = &ctx->nvel;
b08caa87
LB
1531 NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
1532 NV_ENC_PIC_PARAMS params = { 0 };
118beda3 1533 NVENCFrame *nvenc_frame = NULL;
fb59f87c 1534 CUcontext dummy;
9d36cab4 1535 int enc_ret, ret;
b08caa87
LB
1536
1537 params.version = NV_ENC_PIC_PARAMS_VER;
1538
1539 if (frame) {
118beda3
AK
1540 nvenc_frame = get_free_frame(ctx);
1541 if (!nvenc_frame) {
1542 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
b08caa87 1543 return AVERROR_BUG;
118beda3 1544 }
b08caa87 1545
118beda3
AK
1546 ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
1547 if (ret < 0)
1548 return ret;
b08caa87 1549
118beda3
AK
1550 params.inputBuffer = nvenc_frame->in;
1551 params.bufferFmt = nvenc_frame->format;
b08caa87
LB
1552 params.inputWidth = frame->width;
1553 params.inputHeight = frame->height;
118beda3 1554 params.outputBitstream = nvenc_frame->out;
b08caa87
LB
1555 params.inputTimeStamp = frame->pts;
1556
7c6eb0a1 1557 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
b08caa87
LB
1558 if (frame->top_field_first)
1559 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
1560 else
1561 params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
1562 } else {
1563 params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1564 }
1565
1566 nvenc_codec_specific_pic_params(avctx, &params);
1567
1568 ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
1569 if (ret < 0)
1570 return ret;
c59fec78
AK
1571
1572 if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
1573 ctx->initial_pts[0] = frame->pts;
1574 else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
1575 ctx->initial_pts[1] = frame->pts;
b08caa87
LB
1576 } else {
1577 params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1578 }
1579
fb59f87c 1580 nvel->cu_ctx_push_current(ctx->cu_context);
9d36cab4 1581 enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
fb59f87c
LB
1582 nvel->cu_ctx_pop_current(&dummy);
1583
9d36cab4
AK
1584 if (enc_ret != NV_ENC_SUCCESS &&
1585 enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
1586 return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
b08caa87 1587
118beda3
AK
1588 if (nvenc_frame) {
1589 ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
b08caa87
LB
1590 if (ret < 0)
1591 return ret;
1592 }
1593
9d36cab4
AK
1594 /* all the pending buffers are now ready for output */
1595 if (enc_ret == NV_ENC_SUCCESS) {
1596 while (av_fifo_size(ctx->pending) > 0) {
118beda3
AK
1597 av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
1598 av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
9d36cab4
AK
1599 }
1600 }
1601
c59fec78 1602 if (output_ready(avctx, !frame)) {
d005ccc6 1603 ret = nvenc_get_output(avctx, pkt);
b08caa87
LB
1604 if (ret < 0)
1605 return ret;
1606 *got_packet = 1;
1607 } else {
1608 *got_packet = 0;
1609 }
1610
1611 return 0;
1612}