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