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