blob: 409a7b785bba0cf6bea5c20b66dfd904533fd4d1 [file] [log] [blame]
Timo Rothenpieler2a428db2014-11-29 23:04:371/*
2 * H.264 hardware encoding using nvidia nvenc
3 * Copyright (c) 2014 Timo Rothenpieler <[email protected]>
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
Andrey Turkin7aa16d52016-05-25 13:04:2822#include "config.h"
23
Timo Rothenpieler1efdb0a2014-12-25 13:55:3124#if defined(_WIN32)
Timo Rothenpieler2a428db2014-11-29 23:04:3725#include <windows.h>
Andrey Turkin0d021cc2016-05-29 12:23:2626
27#define CUDA_LIBNAME TEXT("nvcuda.dll")
28#if ARCH_X86_64
29#define NVENC_LIBNAME TEXT("nvEncodeAPI64.dll")
Timo Rothenpieler2a428db2014-11-29 23:04:3730#else
Andrey Turkin0d021cc2016-05-29 12:23:2631#define NVENC_LIBNAME TEXT("nvEncodeAPI.dll")
Timo Rothenpieler2a428db2014-11-29 23:04:3732#endif
33
Andrey Turkin0d021cc2016-05-29 12:23:2634#define dlopen(filename, flags) LoadLibrary((filename))
35#define dlsym(handle, symbol) GetProcAddress(handle, symbol)
36#define dlclose(handle) FreeLibrary(handle)
37#else
38#include <dlfcn.h>
39
40#define CUDA_LIBNAME "libcuda.so"
41#define NVENC_LIBNAME "libnvidia-encode.so"
42#endif
43
44#include "libavutil/hwcontext.h"
Timo Rothenpieler2a428db2014-11-29 23:04:3745#include "libavutil/imgutils.h"
46#include "libavutil/avassert.h"
Timo Rothenpieler2a428db2014-11-29 23:04:3747#include "libavutil/mem.h"
Timo Rothenpieler2a428db2014-11-29 23:04:3748#include "internal.h"
Andrey Turkin7aa16d52016-05-25 13:04:2849#include "nvenc.h"
Andrey Turkina8cf25d2016-05-20 22:08:0650
Andrey Turkin0d021cc2016-05-29 12:23:2651#define NVENC_CAP 0x30
Andrey Turkinf84dfbc2016-05-25 16:39:5452#define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
53 rc == NV_ENC_PARAMS_RC_2_PASS_QUALITY || \
54 rc == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP)
55
Andrey Turkin0d021cc2016-05-29 12:23:2656#define LOAD_LIBRARY(l, path) \
57 do { \
58 if (!((l) = dlopen(path, RTLD_LAZY))) { \
59 av_log(avctx, AV_LOG_ERROR, \
60 "Cannot load %s\n", \
61 path); \
62 return AVERROR_UNKNOWN; \
63 } \
64 } while (0)
65
66#define LOAD_SYMBOL(fun, lib, symbol) \
67 do { \
68 if (!((fun) = dlsym(lib, symbol))) { \
69 av_log(avctx, AV_LOG_ERROR, \
70 "Cannot load %s\n", \
71 symbol); \
72 return AVERROR_UNKNOWN; \
73 } \
74 } while (0)
Timo Rothenpieler2a428db2014-11-29 23:04:3775
Andrey Turkin7aa16d52016-05-25 13:04:2876const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
77 AV_PIX_FMT_YUV420P,
78 AV_PIX_FMT_NV12,
79 AV_PIX_FMT_YUV444P,
80#if CONFIG_CUDA
81 AV_PIX_FMT_CUDA,
82#endif
83 AV_PIX_FMT_NONE
84};
Timo Rothenpieler2a428db2014-11-29 23:04:3785
Andrey Turkine1691c42016-05-20 15:37:0086static const struct {
87 NVENCSTATUS nverr;
88 int averr;
89 const char *desc;
90} nvenc_errors[] = {
91 { NV_ENC_SUCCESS, 0, "success" },
92 { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
93 { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
94 { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
95 { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
96 { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
97 { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
98 { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
99 { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
100 { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
101 { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
102 { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
103 { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
104 { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
105 { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR(ENOBUFS), "not enough buffer" },
106 { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
107 { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
108 { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
109 { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
110 { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
111 { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
112 { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
113 { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
114 { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
115 { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
116 { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
117};
118
119static int nvenc_map_error(NVENCSTATUS err, const char **desc)
120{
121 int i;
122 for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
123 if (nvenc_errors[i].nverr == err) {
124 if (desc)
125 *desc = nvenc_errors[i].desc;
126 return nvenc_errors[i].averr;
127 }
128 }
129 if (desc)
130 *desc = "unknown error";
131 return AVERROR_UNKNOWN;
132}
133
134static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
135 const char *error_string)
136{
137 const char *desc;
138 int ret;
139 ret = nvenc_map_error(err, &desc);
140 av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
141 return ret;
142}
143
Andrey Turkin0d021cc2016-05-29 12:23:26144static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
Timo Rothenpieler2a428db2014-11-29 23:04:37145{
146 NvencContext *ctx = avctx->priv_data;
147 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
Andrey Turkin0d021cc2016-05-29 12:23:26148 PNVENCODEAPICREATEINSTANCE nvenc_create_instance;
149 NVENCSTATUS err;
Timo Rothenpieler2a428db2014-11-29 23:04:37150
Andrey Turkina8cf25d2016-05-20 22:08:06151#if CONFIG_CUDA
152 dl_fn->cu_init = cuInit;
153 dl_fn->cu_device_get_count = cuDeviceGetCount;
154 dl_fn->cu_device_get = cuDeviceGet;
155 dl_fn->cu_device_get_name = cuDeviceGetName;
156 dl_fn->cu_device_compute_capability = cuDeviceComputeCapability;
157 dl_fn->cu_ctx_create = cuCtxCreate_v2;
158 dl_fn->cu_ctx_pop_current = cuCtxPopCurrent_v2;
159 dl_fn->cu_ctx_destroy = cuCtxDestroy_v2;
Andrey Turkina8cf25d2016-05-20 22:08:06160#else
Andrey Turkin0d021cc2016-05-29 12:23:26161 LOAD_LIBRARY(dl_fn->cuda, CUDA_LIBNAME);
Timo Rothenpieler2a428db2014-11-29 23:04:37162
Andrey Turkin0d021cc2016-05-29 12:23:26163 LOAD_SYMBOL(dl_fn->cu_init, dl_fn->cuda, "cuInit");
164 LOAD_SYMBOL(dl_fn->cu_device_get_count, dl_fn->cuda, "cuDeviceGetCount");
165 LOAD_SYMBOL(dl_fn->cu_device_get, dl_fn->cuda, "cuDeviceGet");
166 LOAD_SYMBOL(dl_fn->cu_device_get_name, dl_fn->cuda, "cuDeviceGetName");
167 LOAD_SYMBOL(dl_fn->cu_device_compute_capability, dl_fn->cuda,
168 "cuDeviceComputeCapability");
169 LOAD_SYMBOL(dl_fn->cu_ctx_create, dl_fn->cuda, "cuCtxCreate_v2");
170 LOAD_SYMBOL(dl_fn->cu_ctx_pop_current, dl_fn->cuda, "cuCtxPopCurrent_v2");
171 LOAD_SYMBOL(dl_fn->cu_ctx_destroy, dl_fn->cuda, "cuCtxDestroy_v2");
Timo Rothenpieler2a428db2014-11-29 23:04:37172#endif
173
Andrey Turkin0d021cc2016-05-29 12:23:26174 LOAD_LIBRARY(dl_fn->nvenc, NVENC_LIBNAME);
Timo Rothenpieler2a428db2014-11-29 23:04:37175
Andrey Turkin0d021cc2016-05-29 12:23:26176 LOAD_SYMBOL(nvenc_create_instance, dl_fn->nvenc,
177 "NvEncodeAPICreateInstance");
Timo Rothenpieler2a428db2014-11-29 23:04:37178
179 dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
180
Andrey Turkin0d021cc2016-05-29 12:23:26181 err = nvenc_create_instance(&dl_fn->nvenc_funcs);
182 if (err != NV_ENC_SUCCESS)
183 return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
Timo Rothenpieler2a428db2014-11-29 23:04:37184
185 av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
186
Andrey Turkin0d021cc2016-05-29 12:23:26187 return 0;
188}
Timo Rothenpieler2a428db2014-11-29 23:04:37189
Andrey Turkin0d021cc2016-05-29 12:23:26190static av_cold int nvenc_open_session(AVCodecContext *avctx)
191{
192 NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
193 NvencContext *ctx = avctx->priv_data;
194 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
195 NVENCSTATUS ret;
Timo Rothenpieler2a428db2014-11-29 23:04:37196
Andrey Turkin0d021cc2016-05-29 12:23:26197 params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
198 params.apiVersion = NVENCAPI_VERSION;
199 params.device = ctx->cu_context;
200 params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
201
202 ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
203 if (ret != NV_ENC_SUCCESS) {
204 ctx->nvencoder = NULL;
205 return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
206 }
Timo Rothenpieler2a428db2014-11-29 23:04:37207
208 return 0;
209}
210
Andrey Turkin0d021cc2016-05-29 12:23:26211static int nvenc_check_codec_support(AVCodecContext *avctx)
212{
213 NvencContext *ctx = avctx->priv_data;
214 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
215 int i, ret, count = 0;
216 GUID *guids = NULL;
217
218 ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
219
220 if (ret != NV_ENC_SUCCESS || !count)
221 return AVERROR(ENOSYS);
222
223 guids = av_malloc(count * sizeof(GUID));
224 if (!guids)
225 return AVERROR(ENOMEM);
226
227 ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
228 if (ret != NV_ENC_SUCCESS) {
229 ret = AVERROR(ENOSYS);
230 goto fail;
231 }
232
233 ret = AVERROR(ENOSYS);
234 for (i = 0; i < count; i++) {
235 if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
236 ret = 0;
237 break;
238 }
239 }
240
241fail:
242 av_free(guids);
243
244 return ret;
245}
246
247static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
248{
249 NvencContext *ctx = avctx->priv_data;
250 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
251 NV_ENC_CAPS_PARAM params = { 0 };
252 int ret, val = 0;
253
254 params.version = NV_ENC_CAPS_PARAM_VER;
255 params.capsToQuery = cap;
256
257 ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
258
259 if (ret == NV_ENC_SUCCESS)
260 return val;
261 return 0;
262}
263
264static int nvenc_check_capabilities(AVCodecContext *avctx)
265{
266 NvencContext *ctx = avctx->priv_data;
267 int ret;
268
269 ret = nvenc_check_codec_support(avctx);
270 if (ret < 0) {
271 av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
272 return ret;
273 }
274
275 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
276 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P && ret <= 0) {
277 av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
278 return AVERROR(ENOSYS);
279 }
280
281 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
282 if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
283 av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
284 return AVERROR(ENOSYS);
285 }
286
287 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
288 if (ret < avctx->width) {
289 av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
290 avctx->width, ret);
291 return AVERROR(ENOSYS);
292 }
293
294 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
295 if (ret < avctx->height) {
296 av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
297 avctx->height, ret);
298 return AVERROR(ENOSYS);
299 }
300
301 ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
302 if (ret < avctx->max_b_frames) {
303 av_log(avctx, AV_LOG_VERBOSE, "Max b-frames %d exceed %d\n",
304 avctx->max_b_frames, ret);
305
306 return AVERROR(ENOSYS);
307 }
308
309 return 0;
310}
311
312static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
313{
314 NvencContext *ctx = avctx->priv_data;
315 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
316 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
317 char name[128] = { 0};
318 int major, minor, ret;
319 CUresult cu_res;
320 CUdevice cu_device;
321 CUcontext dummy;
322 int loglevel = AV_LOG_VERBOSE;
323
324 if (ctx->device == LIST_DEVICES)
325 loglevel = AV_LOG_INFO;
326
327 cu_res = dl_fn->cu_device_get(&cu_device, idx);
328 if (cu_res != CUDA_SUCCESS) {
329 av_log(avctx, AV_LOG_ERROR,
330 "Cannot access the CUDA device %d\n",
331 idx);
332 return -1;
333 }
334
335 cu_res = dl_fn->cu_device_get_name(name, sizeof(name), cu_device);
336 if (cu_res != CUDA_SUCCESS)
337 return -1;
338
339 cu_res = dl_fn->cu_device_compute_capability(&major, &minor, cu_device);
340 if (cu_res != CUDA_SUCCESS)
341 return -1;
342
343 av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
344 if (((major << 4) | minor) < NVENC_CAP) {
345 av_log(avctx, loglevel, "does not support NVENC\n");
346 goto fail;
347 }
348
349 cu_res = dl_fn->cu_ctx_create(&ctx->cu_context_internal, 0, cu_device);
350 if (cu_res != CUDA_SUCCESS) {
351 av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
352 goto fail;
353 }
354
355 ctx->cu_context = ctx->cu_context_internal;
356
357 cu_res = dl_fn->cu_ctx_pop_current(&dummy);
358 if (cu_res != CUDA_SUCCESS) {
359 av_log(avctx, AV_LOG_FATAL, "Failed popping CUDA context: 0x%x\n", (int)cu_res);
360 goto fail2;
361 }
362
363 if ((ret = nvenc_open_session(avctx)) < 0)
364 goto fail2;
365
366 if ((ret = nvenc_check_capabilities(avctx)) < 0)
367 goto fail3;
368
369 av_log(avctx, loglevel, "supports NVENC\n");
370
371 dl_fn->nvenc_device_count++;
372
373 if (ctx->device == dl_fn->nvenc_device_count - 1 || ctx->device == ANY_DEVICE)
374 return 0;
375
376fail3:
377 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
378 ctx->nvencoder = NULL;
379
380fail2:
381 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
382 ctx->cu_context_internal = NULL;
383
384fail:
385 return AVERROR(ENOSYS);
386}
387
Andrey Turkin82d705e2016-05-20 14:49:24388static av_cold int nvenc_setup_device(AVCodecContext *avctx)
Timo Rothenpieler2a428db2014-11-29 23:04:37389{
Timo Rothenpieler2a428db2014-11-29 23:04:37390 NvencContext *ctx = avctx->priv_data;
391 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
Timo Rothenpieler2a428db2014-11-29 23:04:37392
Andrey Turkinfaffff82016-05-25 14:05:50393 switch (avctx->codec->id) {
394 case AV_CODEC_ID_H264:
395 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
396 break;
397 case AV_CODEC_ID_HEVC:
398 ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
399 break;
400 default:
401 return AVERROR_BUG;
402 }
403
Andrey Turkina8cf25d2016-05-20 22:08:06404 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
Andrey Turkin0d021cc2016-05-29 12:23:26405#if CONFIG_CUDA
406 AVHWFramesContext *frames_ctx;
Andrey Turkina8cf25d2016-05-20 22:08:06407 AVCUDADeviceContext *device_hwctx;
Andrey Turkin0d021cc2016-05-29 12:23:26408 int ret;
Andrey Turkina8cf25d2016-05-20 22:08:06409
Andrey Turkin0d021cc2016-05-29 12:23:26410 if (!avctx->hw_frames_ctx)
Andrey Turkina8cf25d2016-05-20 22:08:06411 return AVERROR(EINVAL);
Andrey Turkin0d021cc2016-05-29 12:23:26412
413 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
414 device_hwctx = frames_ctx->device_ctx->hwctx;
415
416 ctx->cu_context = device_hwctx->cuda_ctx;
417
418 ret = nvenc_open_session(avctx);
419 if (ret < 0)
420 return ret;
421
422 ret = nvenc_check_capabilities(avctx);
423 if (ret < 0) {
424 av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
425 return ret;
426 }
427#else
428 return AVERROR_BUG;
429#endif
430 } else {
431 int i, nb_devices = 0;
432
433 if ((dl_fn->cu_init(0)) != CUDA_SUCCESS) {
434 av_log(avctx, AV_LOG_ERROR,
435 "Cannot init CUDA\n");
436 return AVERROR_UNKNOWN;
Andrey Turkina8cf25d2016-05-20 22:08:06437 }
438
Andrey Turkin0d021cc2016-05-29 12:23:26439 if ((dl_fn->cu_device_get_count(&nb_devices)) != CUDA_SUCCESS) {
440 av_log(avctx, AV_LOG_ERROR,
441 "Cannot enumerate the CUDA devices\n");
442 return AVERROR_UNKNOWN;
443 }
Andrey Turkina8cf25d2016-05-20 22:08:06444
Andrey Turkin0d021cc2016-05-29 12:23:26445 if (!nb_devices) {
446 av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
447 return AVERROR_EXTERNAL;
448 }
449
450 av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
451
452 dl_fn->nvenc_device_count = 0;
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 if (!dl_fn->nvenc_device_count) {
462 av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
463 return AVERROR_EXTERNAL;
464 }
465
466 av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, dl_fn->nvenc_device_count);
Andrey Turkin82d705e2016-05-20 14:49:24467 return AVERROR(EINVAL);
Timo Rothenpieler2a428db2014-11-29 23:04:37468 }
469
Andrey Turkin82d705e2016-05-20 14:49:24470 return 0;
471}
472
Andrey Turkinfaffff82016-05-25 14:05:50473typedef struct GUIDTuple {
474 const GUID guid;
475 int flags;
476} GUIDTuple;
477
478static void nvenc_map_preset(NvencContext *ctx)
479{
480 GUIDTuple presets[] = {
481 { NV_ENC_PRESET_DEFAULT_GUID },
482 { NV_ENC_PRESET_HQ_GUID, NVENC_TWO_PASSES }, /* slow */
483 { NV_ENC_PRESET_HQ_GUID, NVENC_ONE_PASS }, /* medium */
484 { NV_ENC_PRESET_HP_GUID, NVENC_ONE_PASS }, /* fast */
485 { NV_ENC_PRESET_HP_GUID },
486 { NV_ENC_PRESET_HQ_GUID },
487 { NV_ENC_PRESET_BD_GUID },
488 { NV_ENC_PRESET_LOW_LATENCY_DEFAULT_GUID, NVENC_LOWLATENCY },
489 { NV_ENC_PRESET_LOW_LATENCY_HQ_GUID, NVENC_LOWLATENCY },
490 { NV_ENC_PRESET_LOW_LATENCY_HP_GUID, NVENC_LOWLATENCY },
491 { NV_ENC_PRESET_LOSSLESS_DEFAULT_GUID, NVENC_LOSSLESS },
492 { NV_ENC_PRESET_LOSSLESS_HP_GUID, NVENC_LOSSLESS },
493 };
494
495 GUIDTuple *t = &presets[ctx->preset];
496
497 ctx->init_encode_params.presetGUID = t->guid;
498 ctx->flags = t->flags;
499}
500
Andrey Turkin82d705e2016-05-20 14:49:24501static av_cold void set_constqp(AVCodecContext *avctx)
502{
503 NvencContext *ctx = avctx->priv_data;
Andrey Turkinf84dfbc2016-05-25 16:39:54504 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
Andrey Turkin82d705e2016-05-20 14:49:24505
Andrey Turkinf84dfbc2016-05-25 16:39:54506 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
507 rc->constQP.qpInterB = avctx->global_quality;
508 rc->constQP.qpInterP = avctx->global_quality;
509 rc->constQP.qpIntra = avctx->global_quality;
510
511 avctx->qmin = -1;
512 avctx->qmax = -1;
Andrey Turkin82d705e2016-05-20 14:49:24513}
514
515static av_cold void set_vbr(AVCodecContext *avctx)
516{
517 NvencContext *ctx = avctx->priv_data;
Andrey Turkinf84dfbc2016-05-25 16:39:54518 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
519 int qp_inter_p;
Andrey Turkin82d705e2016-05-20 14:49:24520
Andrey Turkinf84dfbc2016-05-25 16:39:54521 if (avctx->qmin >= 0 && avctx->qmax >= 0) {
522 rc->enableMinQP = 1;
523 rc->enableMaxQP = 1;
Andrey Turkin82d705e2016-05-20 14:49:24524
Andrey Turkinf84dfbc2016-05-25 16:39:54525 rc->minQP.qpInterB = avctx->qmin;
526 rc->minQP.qpInterP = avctx->qmin;
527 rc->minQP.qpIntra = avctx->qmin;
Andrey Turkin82d705e2016-05-20 14:49:24528
Andrey Turkinf84dfbc2016-05-25 16:39:54529 rc->maxQP.qpInterB = avctx->qmax;
530 rc->maxQP.qpInterP = avctx->qmax;
531 rc->maxQP.qpIntra = avctx->qmax;
532
533 qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
Timo Rothenpieler971351b2016-05-31 15:00:07534 } else if (avctx->qmin >= 0) {
535 rc->enableMinQP = 1;
536
537 rc->minQP.qpInterB = avctx->qmin;
538 rc->minQP.qpInterP = avctx->qmin;
539 rc->minQP.qpIntra = avctx->qmin;
540
541 qp_inter_p = avctx->qmin;
Andrey Turkinf84dfbc2016-05-25 16:39:54542 } else {
543 qp_inter_p = 26; // default to 26
544 }
545
546 rc->enableInitialRCQP = 1;
547 rc->initialRCQP.qpInterP = qp_inter_p;
548
549 if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
550 rc->initialRCQP.qpIntra = av_clip(
551 qp_inter_p * fabs(avctx->i_quant_factor) + avctx->i_quant_offset, 0, 51);
552 rc->initialRCQP.qpInterB = av_clip(
553 qp_inter_p * fabs(avctx->b_quant_factor) + avctx->b_quant_offset, 0, 51);
554 } else {
555 rc->initialRCQP.qpIntra = qp_inter_p;
556 rc->initialRCQP.qpInterB = qp_inter_p;
557 }
Andrey Turkin82d705e2016-05-20 14:49:24558}
559
560static av_cold void set_lossless(AVCodecContext *avctx)
561{
562 NvencContext *ctx = avctx->priv_data;
Andrey Turkinf84dfbc2016-05-25 16:39:54563 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
Andrey Turkin82d705e2016-05-20 14:49:24564
Andrey Turkinf84dfbc2016-05-25 16:39:54565 rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
566 rc->constQP.qpInterB = 0;
567 rc->constQP.qpInterP = 0;
568 rc->constQP.qpIntra = 0;
569
570 avctx->qmin = -1;
571 avctx->qmax = -1;
572}
573
574static void nvenc_override_rate_control(AVCodecContext *avctx)
575{
576 NvencContext *ctx = avctx->priv_data;
577 NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
578
579 switch (ctx->rc) {
580 case NV_ENC_PARAMS_RC_CONSTQP:
581 if (avctx->global_quality <= 0) {
582 av_log(avctx, AV_LOG_WARNING,
583 "The constant quality rate-control requires "
584 "the 'global_quality' option set.\n");
585 return;
586 }
587 set_constqp(avctx);
588 return;
589 case NV_ENC_PARAMS_RC_2_PASS_VBR:
590 case NV_ENC_PARAMS_RC_VBR:
591 if (avctx->qmin < 0 && avctx->qmax < 0) {
592 av_log(avctx, AV_LOG_WARNING,
593 "The variable bitrate rate-control requires "
594 "the 'qmin' and/or 'qmax' option set.\n");
595 set_vbr(avctx);
596 return;
597 }
598 case NV_ENC_PARAMS_RC_VBR_MINQP:
599 if (avctx->qmin < 0) {
600 av_log(avctx, AV_LOG_WARNING,
601 "The variable bitrate rate-control requires "
602 "the 'qmin' option set.\n");
603 set_vbr(avctx);
604 return;
605 }
606 set_vbr(avctx);
607 break;
608 case NV_ENC_PARAMS_RC_CBR:
Andrey Turkinf84dfbc2016-05-25 16:39:54609 case NV_ENC_PARAMS_RC_2_PASS_QUALITY:
610 case NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP:
Timo Rothenpielereae4eba2016-05-31 14:55:24611 break;
Andrey Turkinf84dfbc2016-05-25 16:39:54612 }
613
614 rc->rateControlMode = ctx->rc;
Andrey Turkin82d705e2016-05-20 14:49:24615}
616
Andrey Turkinfaffff82016-05-25 14:05:50617static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
Andrey Turkin82d705e2016-05-20 14:49:24618{
619 NvencContext *ctx = avctx->priv_data;
620
Andrey Turkin82d705e2016-05-20 14:49:24621 if (avctx->bit_rate > 0) {
622 ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
623 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
624 ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
625 }
626
627 if (avctx->rc_max_rate > 0)
628 ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
629
Andrey Turkinf84dfbc2016-05-25 16:39:54630 if (ctx->rc < 0) {
631 if (ctx->flags & NVENC_ONE_PASS)
632 ctx->twopass = 0;
633 if (ctx->flags & NVENC_TWO_PASSES)
634 ctx->twopass = 1;
635
636 if (ctx->twopass < 0)
637 ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
638
639 if (ctx->cbr) {
640 if (ctx->twopass) {
641 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_QUALITY;
642 } else {
643 ctx->rc = NV_ENC_PARAMS_RC_CBR;
644 }
645 } else if (avctx->global_quality > 0) {
646 ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
647 } else if (ctx->twopass) {
648 ctx->rc = NV_ENC_PARAMS_RC_2_PASS_VBR;
649 } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
650 ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
651 }
652 }
653
Andrey Turkinfaffff82016-05-25 14:05:50654 if (ctx->flags & NVENC_LOSSLESS) {
Andrey Turkin82d705e2016-05-20 14:49:24655 set_lossless(avctx);
Timo Rothenpieler1330a0f2016-05-31 14:53:38656 } else if (ctx->rc >= 0) {
Andrey Turkinf84dfbc2016-05-25 16:39:54657 nvenc_override_rate_control(avctx);
Andrey Turkin82d705e2016-05-20 14:49:24658 } else {
Andrey Turkinf84dfbc2016-05-25 16:39:54659 ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
660 set_vbr(avctx);
Andrey Turkin82d705e2016-05-20 14:49:24661 }
662
663 if (avctx->rc_buffer_size > 0) {
664 ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
665 } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
666 ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
667 }
668}
669
Andrey Turkinfaffff82016-05-25 14:05:50670static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
Andrey Turkin82d705e2016-05-20 14:49:24671{
Andrey Turkinfaffff82016-05-25 14:05:50672 NvencContext *ctx = avctx->priv_data;
673 NV_ENC_CONFIG *cc = &ctx->encode_config;
674 NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
675 NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
Andrey Turkin82d705e2016-05-20 14:49:24676
Andrey Turkinfaffff82016-05-25 14:05:50677 vui->colourMatrix = avctx->colorspace;
678 vui->colourPrimaries = avctx->color_primaries;
679 vui->transferCharacteristics = avctx->color_trc;
680 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
Andrey Turkina8cf25d2016-05-20 22:08:06681 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
Andrey Turkin82d705e2016-05-20 14:49:24682
Andrey Turkinfaffff82016-05-25 14:05:50683 vui->colourDescriptionPresentFlag =
Andrey Turkin82d705e2016-05-20 14:49:24684 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
685
Andrey Turkinfaffff82016-05-25 14:05:50686 vui->videoSignalTypePresentFlag =
687 (vui->colourDescriptionPresentFlag
688 || vui->videoFormat != 5
689 || vui->videoFullRangeFlag != 0);
Andrey Turkin82d705e2016-05-20 14:49:24690
Andrey Turkinfaffff82016-05-25 14:05:50691 h264->sliceMode = 3;
692 h264->sliceModeData = 1;
Andrey Turkin82d705e2016-05-20 14:49:24693
Andrey Turkinfaffff82016-05-25 14:05:50694 h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
Andrey Turkinf84dfbc2016-05-25 16:39:54695 h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
696 h264->outputAUD = 1;
Andrey Turkin82d705e2016-05-20 14:49:24697
Andrey Turkinf84dfbc2016-05-25 16:39:54698 if (avctx->refs >= 0) {
699 /* 0 means "let the hardware decide" */
700 h264->maxNumRefFrames = avctx->refs;
701 }
702 if (avctx->gop_size >= 0) {
703 h264->idrPeriod = cc->gopLength;
704 }
705
706 if (IS_CBR(cc->rcParams.rateControlMode)) {
707 h264->outputBufferingPeriodSEI = 1;
708 h264->outputPictureTimingSEI = 1;
709 }
710
711 if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_QUALITY ||
712 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_FRAMESIZE_CAP ||
713 cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_2_PASS_VBR) {
714 h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
715 h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
716 }
Andrey Turkin82d705e2016-05-20 14:49:24717
Andrey Turkin98243212016-05-25 14:26:25718 if (ctx->flags & NVENC_LOSSLESS) {
719 h264->qpPrimeYZeroTransformBypassFlag = 1;
720 } else {
721 switch(ctx->profile) {
722 case NV_ENC_H264_PROFILE_BASELINE:
Andrey Turkinfaffff82016-05-25 14:05:50723 cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
Andrey Turkin82d705e2016-05-20 14:49:24724 avctx->profile = FF_PROFILE_H264_BASELINE;
Andrey Turkin98243212016-05-25 14:26:25725 break;
726 case NV_ENC_H264_PROFILE_MAIN:
727 cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
728 avctx->profile = FF_PROFILE_H264_MAIN;
729 break;
730 case NV_ENC_H264_PROFILE_HIGH:
731 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
732 avctx->profile = FF_PROFILE_H264_HIGH;
733 break;
734 case NV_ENC_H264_PROFILE_HIGH_444P:
Andrey Turkinfaffff82016-05-25 14:05:50735 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
Andrey Turkin82d705e2016-05-20 14:49:24736 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
Andrey Turkin98243212016-05-25 14:26:25737 break;
Andrey Turkin82d705e2016-05-20 14:49:24738 }
739 }
740
741 // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
Andrey Turkina8cf25d2016-05-20 22:08:06742 if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
Andrey Turkinfaffff82016-05-25 14:05:50743 cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
Andrey Turkin82d705e2016-05-20 14:49:24744 avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
745 }
746
Andrey Turkinfaffff82016-05-25 14:05:50747 h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
Andrey Turkin82d705e2016-05-20 14:49:24748
Andrey Turkinb0172872016-05-25 15:00:52749 h264->level = ctx->level;
Andrey Turkin82d705e2016-05-20 14:49:24750
751 return 0;
752}
753
754static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
755{
Andrey Turkinfaffff82016-05-25 14:05:50756 NvencContext *ctx = avctx->priv_data;
757 NV_ENC_CONFIG *cc = &ctx->encode_config;
758 NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
759 NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
Andrey Turkin82d705e2016-05-20 14:49:24760
Andrey Turkinfaffff82016-05-25 14:05:50761 vui->colourMatrix = avctx->colorspace;
762 vui->colourPrimaries = avctx->color_primaries;
763 vui->transferCharacteristics = avctx->color_trc;
764 vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
Andrey Turkina8cf25d2016-05-20 22:08:06765 || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
Andrey Turkin82d705e2016-05-20 14:49:24766
Andrey Turkinfaffff82016-05-25 14:05:50767 vui->colourDescriptionPresentFlag =
Andrey Turkin82d705e2016-05-20 14:49:24768 (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
769
Andrey Turkinfaffff82016-05-25 14:05:50770 vui->videoSignalTypePresentFlag =
771 (vui->colourDescriptionPresentFlag
772 || vui->videoFormat != 5
773 || vui->videoFullRangeFlag != 0);
Andrey Turkin82d705e2016-05-20 14:49:24774
Andrey Turkinfaffff82016-05-25 14:05:50775 hevc->sliceMode = 3;
776 hevc->sliceModeData = 1;
Andrey Turkin82d705e2016-05-20 14:49:24777
Andrey Turkinfaffff82016-05-25 14:05:50778 hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
Andrey Turkinf84dfbc2016-05-25 16:39:54779 hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
780 hevc->outputAUD = 1;
Andrey Turkin82d705e2016-05-20 14:49:24781
Andrey Turkinf84dfbc2016-05-25 16:39:54782 if (avctx->refs >= 0) {
783 /* 0 means "let the hardware decide" */
784 hevc->maxNumRefFramesInDPB = avctx->refs;
785 }
786 if (avctx->gop_size >= 0) {
787 hevc->idrPeriod = cc->gopLength;
788 }
789
790 if (IS_CBR(cc->rcParams.rateControlMode)) {
791 hevc->outputBufferingPeriodSEI = 1;
792 hevc->outputPictureTimingSEI = 1;
793 }
Andrey Turkin82d705e2016-05-20 14:49:24794
795 /* No other profile is supported in the current SDK version 5 */
Andrey Turkinfaffff82016-05-25 14:05:50796 cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
Andrey Turkin82d705e2016-05-20 14:49:24797 avctx->profile = FF_PROFILE_HEVC_MAIN;
798
Andrey Turkinb0172872016-05-25 15:00:52799 hevc->level = ctx->level;
Andrey Turkin82d705e2016-05-20 14:49:24800
Andrey Turkin40df4682016-05-25 15:06:02801 hevc->tier = ctx->tier;
Andrey Turkin82d705e2016-05-20 14:49:24802
803 return 0;
804}
805
Andrey Turkinfaffff82016-05-25 14:05:50806static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
Andrey Turkin82d705e2016-05-20 14:49:24807{
808 switch (avctx->codec->id) {
809 case AV_CODEC_ID_H264:
Andrey Turkinfaffff82016-05-25 14:05:50810 return nvenc_setup_h264_config(avctx);
811 case AV_CODEC_ID_HEVC:
Andrey Turkin82d705e2016-05-20 14:49:24812 return nvenc_setup_hevc_config(avctx);
813 /* Earlier switch/case will return if unknown codec is passed. */
814 }
815
816 return 0;
817}
818
819static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
820{
821 NvencContext *ctx = avctx->priv_data;
822 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
823 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
824
825 NV_ENC_PRESET_CONFIG preset_config = { 0 };
Andrey Turkin82d705e2016-05-20 14:49:24826 NVENCSTATUS nv_status = NV_ENC_SUCCESS;
827 AVCPBProperties *cpb_props;
Andrey Turkin82d705e2016-05-20 14:49:24828 int res = 0;
829 int dw, dh;
830
831 ctx->last_dts = AV_NOPTS_VALUE;
832
833 ctx->encode_config.version = NV_ENC_CONFIG_VER;
834 ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
Andrey Turkinfaffff82016-05-25 14:05:50835
836 ctx->init_encode_params.encodeHeight = avctx->height;
837 ctx->init_encode_params.encodeWidth = avctx->width;
838
839 ctx->init_encode_params.encodeConfig = &ctx->encode_config;
840
841 nvenc_map_preset(ctx);
842
Andrey Turkin82d705e2016-05-20 14:49:24843 preset_config.version = NV_ENC_PRESET_CONFIG_VER;
844 preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
845
Andrey Turkinfaffff82016-05-25 14:05:50846 nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
847 ctx->init_encode_params.encodeGUID,
848 ctx->init_encode_params.presetGUID,
849 &preset_config);
850 if (nv_status != NV_ENC_SUCCESS)
851 return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
Timo Rothenpieler2a428db2014-11-29 23:04:37852
Andrey Turkinfaffff82016-05-25 14:05:50853 memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
Agatha Hu49046582015-09-11 09:07:10854
Andrey Turkinfaffff82016-05-25 14:05:50855 ctx->encode_config.version = NV_ENC_CONFIG_VER;
Timo Rothenpielerfb34c582015-01-26 12:28:22856
857 if (avctx->sample_aspect_ratio.num && avctx->sample_aspect_ratio.den &&
858 (avctx->sample_aspect_ratio.num != 1 || avctx->sample_aspect_ratio.num != 1)) {
859 av_reduce(&dw, &dh,
860 avctx->width * avctx->sample_aspect_ratio.num,
861 avctx->height * avctx->sample_aspect_ratio.den,
862 1024 * 1024);
863 ctx->init_encode_params.darHeight = dh;
864 ctx->init_encode_params.darWidth = dw;
865 } else {
866 ctx->init_encode_params.darHeight = avctx->height;
867 ctx->init_encode_params.darWidth = avctx->width;
868 }
869
Philip Langdaled20df262015-01-28 17:05:53870 // De-compensate for hardware, dubiously, trying to compensate for
871 // playback at 704 pixel width.
872 if (avctx->width == 720 &&
873 (avctx->height == 480 || avctx->height == 576)) {
874 av_reduce(&dw, &dh,
875 ctx->init_encode_params.darWidth * 44,
876 ctx->init_encode_params.darHeight * 45,
Philip Langdale7ae805d2015-05-27 01:35:15877 1024 * 1024);
Philip Langdaled20df262015-01-28 17:05:53878 ctx->init_encode_params.darHeight = dh;
879 ctx->init_encode_params.darWidth = dw;
880 }
881
Timo Rothenpieler2a428db2014-11-29 23:04:37882 ctx->init_encode_params.frameRateNum = avctx->time_base.den;
883 ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
884
Timo Rothenpieler2a428db2014-11-29 23:04:37885 ctx->init_encode_params.enableEncodeAsync = 0;
886 ctx->init_encode_params.enablePTD = 1;
887
Timo Rothenpieler914fd422015-01-26 12:28:21888 if (avctx->gop_size > 0) {
889 if (avctx->max_b_frames >= 0) {
890 /* 0 is intra-only, 1 is I/P only, 2 is one B Frame, 3 two B frames, and so on. */
891 ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
892 }
893
Timo Rothenpieler2a428db2014-11-29 23:04:37894 ctx->encode_config.gopLength = avctx->gop_size;
Timo Rothenpieler914fd422015-01-26 12:28:21895 } else if (avctx->gop_size == 0) {
896 ctx->encode_config.frameIntervalP = 0;
897 ctx->encode_config.gopLength = 1;
Timo Rothenpieler2a428db2014-11-29 23:04:37898 }
899
Timo Rothenpieler914fd422015-01-26 12:28:21900 /* when there're b frames, set dts offset */
901 if (ctx->encode_config.frameIntervalP >= 2)
902 ctx->last_dts = -2;
903
Andrey Turkinfaffff82016-05-25 14:05:50904 nvenc_setup_rate_control(avctx);
Timo Rothenpieler2a428db2014-11-29 23:04:37905
Vittorio Giovara7c6eb0a2015-06-29 19:59:37906 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
Timo Rothenpieler2a428db2014-11-29 23:04:37907 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
908 } else {
909 ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
910 }
911
Andrey Turkinfaffff82016-05-25 14:05:50912 res = nvenc_setup_codec_config(avctx);
Andrey Turkin82d705e2016-05-20 14:49:24913 if (res)
914 return res;
Timo Rothenpieler2a428db2014-11-29 23:04:37915
916 nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
917 if (nv_status != NV_ENC_SUCCESS) {
Andrey Turkine1691c42016-05-20 15:37:00918 return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
Timo Rothenpieler2a428db2014-11-29 23:04:37919 }
920
921 if (ctx->encode_config.frameIntervalP > 1)
922 avctx->has_b_frames = 2;
923
924 if (ctx->encode_config.rcParams.averageBitRate > 0)
925 avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
926
Anton Khirnov1520c6f2015-10-03 13:19:10927 cpb_props = ff_add_cpb_side_data(avctx);
928 if (!cpb_props)
929 return AVERROR(ENOMEM);
Hendrik Leppkes5fc17ed2015-12-17 12:41:29930 cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
Anton Khirnov1520c6f2015-10-03 13:19:10931 cpb_props->avg_bitrate = avctx->bit_rate;
Hendrik Leppkes5fc17ed2015-12-17 12:41:29932 cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
Anton Khirnov1520c6f2015-10-03 13:19:10933
Timo Rothenpieler2a428db2014-11-29 23:04:37934 return 0;
Andrey Turkin82d705e2016-05-20 14:49:24935}
936
937static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
938{
939 NvencContext *ctx = avctx->priv_data;
940 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
941 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
942
943 NVENCSTATUS nv_status;
Andrey Turkin82d705e2016-05-20 14:49:24944 NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
Andrey Turkin82d705e2016-05-20 14:49:24945 allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
946
Andrey Turkina8cf25d2016-05-20 22:08:06947 switch (ctx->data_pix_fmt) {
Andrey Turkin82d705e2016-05-20 14:49:24948 case AV_PIX_FMT_YUV420P:
Andrey Turkina8cf25d2016-05-20 22:08:06949 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
Andrey Turkin82d705e2016-05-20 14:49:24950 break;
951
952 case AV_PIX_FMT_NV12:
Andrey Turkina8cf25d2016-05-20 22:08:06953 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
Andrey Turkin82d705e2016-05-20 14:49:24954 break;
955
956 case AV_PIX_FMT_YUV444P:
Andrey Turkina8cf25d2016-05-20 22:08:06957 ctx->surfaces[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
Andrey Turkin82d705e2016-05-20 14:49:24958 break;
959
960 default:
961 av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format\n");
962 return AVERROR(EINVAL);
963 }
964
Andrey Turkina8cf25d2016-05-20 22:08:06965 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
966 ctx->surfaces[idx].in_ref = av_frame_alloc();
967 if (!ctx->surfaces[idx].in_ref)
968 return AVERROR(ENOMEM);
969 } else {
970 NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
971 allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
972 allocSurf.width = (avctx->width + 31) & ~31;
973 allocSurf.height = (avctx->height + 31) & ~31;
974 allocSurf.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
975 allocSurf.bufferFmt = ctx->surfaces[idx].format;
976
977 nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
978 if (nv_status != NV_ENC_SUCCESS) {
979 return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
980 }
981
982 ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
983 ctx->surfaces[idx].width = allocSurf.width;
984 ctx->surfaces[idx].height = allocSurf.height;
Andrey Turkin82d705e2016-05-20 14:49:24985 }
986
Andrey Turkine1691c42016-05-20 15:37:00987 ctx->surfaces[idx].lockCount = 0;
Andrey Turkin82d705e2016-05-20 14:49:24988
989 /* 1MB is large enough to hold most output frames. NVENC increases this automaticaly if it's not enough. */
990 allocOut.size = 1024 * 1024;
991
992 allocOut.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_CACHED;
993
994 nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
995 if (nv_status != NV_ENC_SUCCESS) {
Andrey Turkine1691c42016-05-20 15:37:00996 int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
Andrey Turkina8cf25d2016-05-20 22:08:06997 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
998 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
999 av_frame_free(&ctx->surfaces[idx].in_ref);
Andrey Turkine1691c42016-05-20 15:37:001000 return err;
Andrey Turkin82d705e2016-05-20 14:49:241001 }
1002
Andrey Turkine1691c42016-05-20 15:37:001003 ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
1004 ctx->surfaces[idx].size = allocOut.size;
Andrey Turkin82d705e2016-05-20 14:49:241005
1006 return 0;
1007}
1008
Andrey Turkinb6933532016-05-25 16:57:111009static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
Andrey Turkin82d705e2016-05-20 14:49:241010{
Andrey Turkin82d705e2016-05-20 14:49:241011 NvencContext *ctx = avctx->priv_data;
Andrey Turkinb6933532016-05-25 16:57:111012 int i, res;
Andrey Turkinf052ef32016-05-29 10:07:341013 int num_mbs = ((avctx->width + 15) >> 4) * ((avctx->height + 15) >> 4);
1014 ctx->nb_surfaces = FFMAX((num_mbs >= 8160) ? 32 : 48,
1015 ctx->nb_surfaces);
1016 ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
Andrey Turkin82d705e2016-05-20 14:49:241017
Andrey Turkin82d705e2016-05-20 14:49:241018
Andrey Turkinf052ef32016-05-29 10:07:341019 ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
1020 if (!ctx->surfaces)
Andrey Turkin82d705e2016-05-20 14:49:241021 return AVERROR(ENOMEM);
Andrey Turkin82d705e2016-05-20 14:49:241022
Andrey Turkinf052ef32016-05-29 10:07:341023 ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
Andrey Turkincfb49fc2016-05-20 16:13:201024 if (!ctx->timestamp_list)
1025 return AVERROR(ENOMEM);
Andrey Turkinf052ef32016-05-29 10:07:341026 ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
Andrey Turkincfb49fc2016-05-20 16:13:201027 if (!ctx->output_surface_queue)
1028 return AVERROR(ENOMEM);
Andrey Turkinf052ef32016-05-29 10:07:341029 ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
Andrey Turkincfb49fc2016-05-20 16:13:201030 if (!ctx->output_surface_ready_queue)
1031 return AVERROR(ENOMEM);
1032
Andrey Turkinf052ef32016-05-29 10:07:341033 for (i = 0; i < ctx->nb_surfaces; i++) {
Andrey Turkinb6933532016-05-25 16:57:111034 if ((res = nvenc_alloc_surface(avctx, i)) < 0)
Andrey Turkin82d705e2016-05-20 14:49:241035 return res;
1036 }
1037
1038 return 0;
1039}
1040
1041static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
1042{
1043 NvencContext *ctx = avctx->priv_data;
1044 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1045 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1046
1047 NVENCSTATUS nv_status;
1048 uint32_t outSize = 0;
1049 char tmpHeader[256];
1050 NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
1051 payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
1052
1053 payload.spsppsBuffer = tmpHeader;
1054 payload.inBufferSize = sizeof(tmpHeader);
1055 payload.outSPSPPSPayloadSize = &outSize;
1056
1057 nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
1058 if (nv_status != NV_ENC_SUCCESS) {
Andrey Turkine1691c42016-05-20 15:37:001059 return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
Andrey Turkin82d705e2016-05-20 14:49:241060 }
1061
1062 avctx->extradata_size = outSize;
1063 avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
1064
1065 if (!avctx->extradata) {
1066 return AVERROR(ENOMEM);
1067 }
1068
1069 memcpy(avctx->extradata, tmpHeader, outSize);
1070
1071 return 0;
1072}
1073
Andrey Turkin7aa16d52016-05-25 13:04:281074av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
Timo Rothenpieler2a428db2014-11-29 23:04:371075{
Andrey Turkinb6933532016-05-25 16:57:111076 NvencContext *ctx = avctx->priv_data;
Timo Rothenpieler2a428db2014-11-29 23:04:371077 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1078 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1079 int i;
1080
Andrey Turkinb6933532016-05-25 16:57:111081 /* the encoder has to be flushed before it can be closed */
1082 if (ctx->nvencoder) {
1083 NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
1084 .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
1085
1086 p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
1087 }
1088
Andrey Turkincfb49fc2016-05-20 16:13:201089 av_fifo_freep(&ctx->timestamp_list);
1090 av_fifo_freep(&ctx->output_surface_ready_queue);
1091 av_fifo_freep(&ctx->output_surface_queue);
Timo Rothenpieler2a428db2014-11-29 23:04:371092
Andrey Turkinb6933532016-05-25 16:57:111093 if (ctx->surfaces && avctx->pix_fmt == AV_PIX_FMT_CUDA) {
Andrey Turkinf052ef32016-05-29 10:07:341094 for (i = 0; i < ctx->nb_surfaces; ++i) {
Andrey Turkina8cf25d2016-05-20 22:08:061095 if (ctx->surfaces[i].input_surface) {
1096 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->surfaces[i].in_map.mappedResource);
1097 }
1098 }
1099 for (i = 0; i < ctx->nb_registered_frames; i++) {
1100 if (ctx->registered_frames[i].regptr)
1101 p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
1102 }
1103 ctx->nb_registered_frames = 0;
1104 }
1105
Andrey Turkinb6933532016-05-25 16:57:111106 if (ctx->surfaces) {
Andrey Turkinf052ef32016-05-29 10:07:341107 for (i = 0; i < ctx->nb_surfaces; ++i) {
Andrey Turkinb6933532016-05-25 16:57:111108 if (avctx->pix_fmt != AV_PIX_FMT_CUDA)
1109 p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
1110 av_frame_free(&ctx->surfaces[i].in_ref);
1111 p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
1112 }
Timo Rothenpieler2a428db2014-11-29 23:04:371113 }
Andrey Turkincfb49fc2016-05-20 16:13:201114 av_freep(&ctx->surfaces);
Andrey Turkinf052ef32016-05-29 10:07:341115 ctx->nb_surfaces = 0;
Timo Rothenpieler2a428db2014-11-29 23:04:371116
Andrey Turkinb6933532016-05-25 16:57:111117 if (ctx->nvencoder)
1118 p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
Timo Rothenpieler2a428db2014-11-29 23:04:371119 ctx->nvencoder = NULL;
1120
Andrey Turkina8cf25d2016-05-20 22:08:061121 if (ctx->cu_context_internal)
1122 dl_fn->cu_ctx_destroy(ctx->cu_context_internal);
1123 ctx->cu_context = ctx->cu_context_internal = NULL;
Timo Rothenpieler2a428db2014-11-29 23:04:371124
Andrey Turkin0d021cc2016-05-29 12:23:261125 if (dl_fn->nvenc)
1126 dlclose(dl_fn->nvenc);
1127 dl_fn->nvenc = NULL;
Andrey Turkinb6933532016-05-25 16:57:111128
1129 dl_fn->nvenc_device_count = 0;
1130
1131#if !CONFIG_CUDA
Andrey Turkin0d021cc2016-05-29 12:23:261132 if (dl_fn->cuda)
1133 dlclose(dl_fn->cuda);
1134 dl_fn->cuda = NULL;
Andrey Turkinb6933532016-05-25 16:57:111135#endif
1136
1137 dl_fn->cu_init = NULL;
1138 dl_fn->cu_device_get_count = NULL;
1139 dl_fn->cu_device_get = NULL;
1140 dl_fn->cu_device_get_name = NULL;
1141 dl_fn->cu_device_compute_capability = NULL;
1142 dl_fn->cu_ctx_create = NULL;
1143 dl_fn->cu_ctx_pop_current = NULL;
1144 dl_fn->cu_ctx_destroy = NULL;
1145
1146 av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
1147
1148 return 0;
1149}
1150
1151av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
1152{
Andrey Turkin0d021cc2016-05-29 12:23:261153 NvencContext *ctx = avctx->priv_data;
1154 int ret;
Andrey Turkinb6933532016-05-25 16:57:111155
Andrey Turkin0d021cc2016-05-29 12:23:261156 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1157 AVHWFramesContext *frames_ctx;
1158 if (!avctx->hw_frames_ctx) {
1159 av_log(avctx, AV_LOG_ERROR,
1160 "hw_frames_ctx must be set when using GPU frames as input\n");
1161 return AVERROR(EINVAL);
1162 }
1163 frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1164 ctx->data_pix_fmt = frames_ctx->sw_format;
1165 } else {
1166 ctx->data_pix_fmt = avctx->pix_fmt;
1167 }
Andrey Turkinb6933532016-05-25 16:57:111168
Andrey Turkin0d021cc2016-05-29 12:23:261169 if ((ret = nvenc_load_libraries(avctx)) < 0)
1170 return ret;
Andrey Turkinb6933532016-05-25 16:57:111171
Andrey Turkin0d021cc2016-05-29 12:23:261172 if ((ret = nvenc_setup_device(avctx)) < 0)
1173 return ret;
Andrey Turkinb6933532016-05-25 16:57:111174
Andrey Turkin0d021cc2016-05-29 12:23:261175 if ((ret = nvenc_setup_encoder(avctx)) < 0)
1176 return ret;
Andrey Turkinb6933532016-05-25 16:57:111177
Andrey Turkin0d021cc2016-05-29 12:23:261178 if ((ret = nvenc_setup_surfaces(avctx)) < 0)
1179 return ret;
Andrey Turkinb6933532016-05-25 16:57:111180
1181 if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
Andrey Turkin0d021cc2016-05-29 12:23:261182 if ((ret = nvenc_setup_extradata(avctx)) < 0)
1183 return ret;
Andrey Turkinb6933532016-05-25 16:57:111184 }
Timo Rothenpieler2a428db2014-11-29 23:04:371185
Timo Rothenpieler2a428db2014-11-29 23:04:371186 return 0;
1187}
1188
Andrey Turkine1691c42016-05-20 15:37:001189static NvencSurface *get_free_frame(NvencContext *ctx)
Andrey Turkin82d705e2016-05-20 14:49:241190{
1191 int i;
1192
Andrey Turkinf052ef32016-05-29 10:07:341193 for (i = 0; i < ctx->nb_surfaces; ++i) {
Andrey Turkine1691c42016-05-20 15:37:001194 if (!ctx->surfaces[i].lockCount) {
1195 ctx->surfaces[i].lockCount = 1;
1196 return &ctx->surfaces[i];
Andrey Turkin82d705e2016-05-20 14:49:241197 }
1198 }
1199
1200 return NULL;
1201}
1202
Andrey Turkine1691c42016-05-20 15:37:001203static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *inSurf,
Andrey Turkin82d705e2016-05-20 14:49:241204 NV_ENC_LOCK_INPUT_BUFFER *lockBufferParams, const AVFrame *frame)
1205{
1206 uint8_t *buf = lockBufferParams->bufferDataPtr;
1207 int off = inSurf->height * lockBufferParams->pitch;
1208
Andrey Turkina8cf25d2016-05-20 22:08:061209 if (frame->format == AV_PIX_FMT_YUV420P) {
Andrey Turkin82d705e2016-05-20 14:49:241210 av_image_copy_plane(buf, lockBufferParams->pitch,
1211 frame->data[0], frame->linesize[0],
1212 avctx->width, avctx->height);
1213
1214 buf += off;
1215
1216 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1217 frame->data[2], frame->linesize[2],
1218 avctx->width >> 1, avctx->height >> 1);
1219
1220 buf += off >> 2;
1221
1222 av_image_copy_plane(buf, lockBufferParams->pitch >> 1,
1223 frame->data[1], frame->linesize[1],
1224 avctx->width >> 1, avctx->height >> 1);
Andrey Turkina8cf25d2016-05-20 22:08:061225 } else if (frame->format == AV_PIX_FMT_NV12) {
Andrey Turkin82d705e2016-05-20 14:49:241226 av_image_copy_plane(buf, lockBufferParams->pitch,
1227 frame->data[0], frame->linesize[0],
1228 avctx->width, avctx->height);
1229
1230 buf += off;
1231
1232 av_image_copy_plane(buf, lockBufferParams->pitch,
1233 frame->data[1], frame->linesize[1],
1234 avctx->width, avctx->height >> 1);
Andrey Turkina8cf25d2016-05-20 22:08:061235 } else if (frame->format == AV_PIX_FMT_YUV444P) {
Andrey Turkin82d705e2016-05-20 14:49:241236 av_image_copy_plane(buf, lockBufferParams->pitch,
1237 frame->data[0], frame->linesize[0],
1238 avctx->width, avctx->height);
1239
1240 buf += off;
1241
1242 av_image_copy_plane(buf, lockBufferParams->pitch,
1243 frame->data[1], frame->linesize[1],
1244 avctx->width, avctx->height);
1245
1246 buf += off;
1247
1248 av_image_copy_plane(buf, lockBufferParams->pitch,
1249 frame->data[2], frame->linesize[2],
1250 avctx->width, avctx->height);
1251 } else {
1252 av_log(avctx, AV_LOG_FATAL, "Invalid pixel format!\n");
1253 return AVERROR(EINVAL);
1254 }
1255
1256 return 0;
1257}
1258
Andrey Turkina8cf25d2016-05-20 22:08:061259static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
1260{
1261 NvencContext *ctx = avctx->priv_data;
1262 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1263 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1264
1265 int i;
1266
1267 if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
1268 for (i = 0; i < ctx->nb_registered_frames; i++) {
1269 if (!ctx->registered_frames[i].mapped) {
1270 if (ctx->registered_frames[i].regptr) {
1271 p_nvenc->nvEncUnregisterResource(ctx->nvencoder,
1272 ctx->registered_frames[i].regptr);
1273 ctx->registered_frames[i].regptr = NULL;
1274 }
1275 return i;
1276 }
1277 }
1278 } else {
1279 return ctx->nb_registered_frames++;
1280 }
1281
1282 av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
1283 return AVERROR(ENOMEM);
1284}
1285
1286static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
1287{
1288 NvencContext *ctx = avctx->priv_data;
1289 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1290 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1291
1292 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
1293 NV_ENC_REGISTER_RESOURCE reg;
1294 int i, idx, ret;
1295
1296 for (i = 0; i < ctx->nb_registered_frames; i++) {
1297 if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
1298 return i;
1299 }
1300
1301 idx = nvenc_find_free_reg_resource(avctx);
1302 if (idx < 0)
1303 return idx;
1304
1305 reg.version = NV_ENC_REGISTER_RESOURCE_VER;
1306 reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
1307 reg.width = frames_ctx->width;
1308 reg.height = frames_ctx->height;
1309 reg.bufferFormat = ctx->surfaces[0].format;
1310 reg.pitch = frame->linesize[0];
1311 reg.resourceToRegister = frame->data[0];
1312
1313 ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
1314 if (ret != NV_ENC_SUCCESS) {
1315 nvenc_print_error(avctx, ret, "Error registering an input resource");
1316 return AVERROR_UNKNOWN;
1317 }
1318
1319 ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
1320 ctx->registered_frames[idx].regptr = reg.registeredResource;
1321 return idx;
1322}
1323
Andrey Turkin82d705e2016-05-20 14:49:241324static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
Andrey Turkine1691c42016-05-20 15:37:001325 NvencSurface *nvenc_frame)
Andrey Turkin82d705e2016-05-20 14:49:241326{
1327 NvencContext *ctx = avctx->priv_data;
1328 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1329 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1330
1331 int res;
1332 NVENCSTATUS nv_status;
Andrey Turkin82d705e2016-05-20 14:49:241333
Andrey Turkina8cf25d2016-05-20 22:08:061334 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1335 int reg_idx = nvenc_register_frame(avctx, frame);
1336 if (reg_idx < 0) {
1337 av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
1338 return reg_idx;
1339 }
Andrey Turkin82d705e2016-05-20 14:49:241340
Andrey Turkina8cf25d2016-05-20 22:08:061341 res = av_frame_ref(nvenc_frame->in_ref, frame);
1342 if (res < 0)
1343 return res;
1344
1345 nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
1346 nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
1347 nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &nvenc_frame->in_map);
1348 if (nv_status != NV_ENC_SUCCESS) {
1349 av_frame_unref(nvenc_frame->in_ref);
1350 return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
1351 }
1352
1353 ctx->registered_frames[reg_idx].mapped = 1;
1354 nvenc_frame->reg_idx = reg_idx;
1355 nvenc_frame->input_surface = nvenc_frame->in_map.mappedResource;
1356 return 0;
1357 } else {
1358 NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
1359
1360 lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
1361 lockBufferParams.inputBuffer = nvenc_frame->input_surface;
1362
1363 nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
1364 if (nv_status != NV_ENC_SUCCESS) {
1365 return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
1366 }
1367
1368 res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
1369
1370 nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
1371 if (nv_status != NV_ENC_SUCCESS) {
1372 return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
1373 }
1374
1375 return res;
Andrey Turkin82d705e2016-05-20 14:49:241376 }
Andrey Turkin82d705e2016-05-20 14:49:241377}
1378
1379static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
Andrey Turkin2f53b5b2016-05-29 12:50:061380 NV_ENC_PIC_PARAMS *params)
Andrey Turkin82d705e2016-05-20 14:49:241381{
1382 NvencContext *ctx = avctx->priv_data;
1383
1384 switch (avctx->codec->id) {
1385 case AV_CODEC_ID_H264:
Andrey Turkin2f53b5b2016-05-29 12:50:061386 params->codecPicParams.h264PicParams.sliceMode =
1387 ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
1388 params->codecPicParams.h264PicParams.sliceModeData =
1389 ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
Andrey Turkin82d705e2016-05-20 14:49:241390 break;
Andrey Turkin2f53b5b2016-05-29 12:50:061391 case AV_CODEC_ID_HEVC:
1392 params->codecPicParams.hevcPicParams.sliceMode =
1393 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
1394 params->codecPicParams.hevcPicParams.sliceModeData =
1395 ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1396 break;
Andrey Turkin82d705e2016-05-20 14:49:241397 }
1398}
1399
Andrey Turkin2f53b5b2016-05-29 12:50:061400static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
1401{
1402 av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
1403}
1404
1405static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
1406{
1407 int64_t timestamp = AV_NOPTS_VALUE;
1408 if (av_fifo_size(queue) > 0)
1409 av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
1410
1411 return timestamp;
1412}
1413
Andrey Turkind3463912016-05-29 12:34:381414static int nvenc_set_timestamp(AVCodecContext *avctx,
1415 NV_ENC_LOCK_BITSTREAM *params,
1416 AVPacket *pkt)
1417{
1418 NvencContext *ctx = avctx->priv_data;
1419
1420 pkt->pts = params->outputTimeStamp;
1421 pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
1422
1423 /* when there're b frame(s), set dts offset */
1424 if (ctx->encode_config.frameIntervalP >= 2)
1425 pkt->dts -= 1;
1426
1427 if (pkt->dts > pkt->pts)
1428 pkt->dts = pkt->pts;
1429
1430 if (ctx->last_dts != AV_NOPTS_VALUE && pkt->dts <= ctx->last_dts)
1431 pkt->dts = ctx->last_dts + 1;
1432
1433 ctx->last_dts = pkt->dts;
1434 return 0;
1435}
1436
Andrey Turkine1691c42016-05-20 15:37:001437static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
Timo Rothenpieler2a428db2014-11-29 23:04:371438{
1439 NvencContext *ctx = avctx->priv_data;
1440 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1441 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1442
Philip Langdale21175d82015-03-24 04:34:591443 uint32_t slice_mode_data;
1444 uint32_t *slice_offsets;
Timo Rothenpieler2a428db2014-11-29 23:04:371445 NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
1446 NVENCSTATUS nv_status;
1447 int res = 0;
1448
Lucas Cooperfd554702016-03-07 23:47:561449 enum AVPictureType pict_type;
1450
Philip Langdale21175d82015-03-24 04:34:591451 switch (avctx->codec->id) {
1452 case AV_CODEC_ID_H264:
1453 slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
1454 break;
1455 case AV_CODEC_ID_H265:
1456 slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
1457 break;
1458 default:
Agatha Hu49046582015-09-11 09:07:101459 av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
Philip Langdale21175d82015-03-24 04:34:591460 res = AVERROR(EINVAL);
1461 goto error;
1462 }
1463 slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
1464
Timo Rothenpieler2a428db2014-11-29 23:04:371465 if (!slice_offsets)
Andrey Turkind3463912016-05-29 12:34:381466 goto error;
Timo Rothenpieler2a428db2014-11-29 23:04:371467
1468 lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
1469
1470 lock_params.doNotWait = 0;
1471 lock_params.outputBitstream = tmpoutsurf->output_surface;
1472 lock_params.sliceOffsets = slice_offsets;
1473
1474 nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
1475 if (nv_status != NV_ENC_SUCCESS) {
Andrey Turkine1691c42016-05-20 15:37:001476 res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
Timo Rothenpieler2a428db2014-11-29 23:04:371477 goto error;
1478 }
1479
Agatha Hu49046582015-09-11 09:07:101480 if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
Timo Rothenpieler2a428db2014-11-29 23:04:371481 p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1482 goto error;
1483 }
1484
1485 memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
1486
1487 nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
1488 if (nv_status != NV_ENC_SUCCESS)
Andrey Turkine1691c42016-05-20 15:37:001489 nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
Timo Rothenpieler2a428db2014-11-29 23:04:371490
Andrey Turkina8cf25d2016-05-20 22:08:061491
1492 if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
1493 p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, tmpoutsurf->in_map.mappedResource);
1494 av_frame_unref(tmpoutsurf->in_ref);
1495 ctx->registered_frames[tmpoutsurf->reg_idx].mapped = 0;
1496
1497 tmpoutsurf->input_surface = NULL;
1498 }
1499
Timo Rothenpieler2a428db2014-11-29 23:04:371500 switch (lock_params.pictureType) {
1501 case NV_ENC_PIC_TYPE_IDR:
1502 pkt->flags |= AV_PKT_FLAG_KEY;
1503 case NV_ENC_PIC_TYPE_I:
Lucas Cooperfd554702016-03-07 23:47:561504 pict_type = AV_PICTURE_TYPE_I;
Timo Rothenpieler2a428db2014-11-29 23:04:371505 break;
1506 case NV_ENC_PIC_TYPE_P:
Lucas Cooperfd554702016-03-07 23:47:561507 pict_type = AV_PICTURE_TYPE_P;
Timo Rothenpieler2a428db2014-11-29 23:04:371508 break;
1509 case NV_ENC_PIC_TYPE_B:
Lucas Cooperfd554702016-03-07 23:47:561510 pict_type = AV_PICTURE_TYPE_B;
Timo Rothenpieler2a428db2014-11-29 23:04:371511 break;
1512 case NV_ENC_PIC_TYPE_BI:
Lucas Cooperfd554702016-03-07 23:47:561513 pict_type = AV_PICTURE_TYPE_BI;
Timo Rothenpieler2a428db2014-11-29 23:04:371514 break;
1515 default:
1516 av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
1517 av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
1518 res = AVERROR_EXTERNAL;
1519 goto error;
Lucas Cooperfd554702016-03-07 23:47:561520 }
1521
1522#if FF_API_CODED_FRAME
1523FF_DISABLE_DEPRECATION_WARNINGS
1524 avctx->coded_frame->pict_type = pict_type;
Vittorio Giovara40cf1bb2015-07-15 17:41:221525FF_ENABLE_DEPRECATION_WARNINGS
1526#endif
Lucas Cooperfd554702016-03-07 23:47:561527
1528 ff_side_data_set_encoder_stats(pkt,
1529 (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
Timo Rothenpieler2a428db2014-11-29 23:04:371530
Andrey Turkind3463912016-05-29 12:34:381531 res = nvenc_set_timestamp(avctx, &lock_params, pkt);
1532 if (res < 0)
1533 goto error2;
Timo Rothenpieler2a428db2014-11-29 23:04:371534
1535 av_free(slice_offsets);
1536
1537 return 0;
1538
1539error:
Andrey Turkincfb49fc2016-05-20 16:13:201540 timestamp_queue_dequeue(ctx->timestamp_list);
Timo Rothenpieler2a428db2014-11-29 23:04:371541
Andrey Turkind3463912016-05-29 12:34:381542error2:
1543 av_free(slice_offsets);
1544
Timo Rothenpieler2a428db2014-11-29 23:04:371545 return res;
1546}
1547
Andrey Turkin2f53b5b2016-05-29 12:50:061548static int output_ready(AVCodecContext *avctx, int flush)
Andrey Turkincfb49fc2016-05-20 16:13:201549{
Andrey Turkin2f53b5b2016-05-29 12:50:061550 NvencContext *ctx = avctx->priv_data;
Andrey Turkincfb49fc2016-05-20 16:13:201551 int nb_ready, nb_pending;
1552
1553 nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
1554 nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
Andrey Turkin2f53b5b2016-05-29 12:50:061555 if (flush)
1556 return nb_ready > 0;
1557 return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
Andrey Turkincfb49fc2016-05-20 16:13:201558}
1559
Andrey Turkin7aa16d52016-05-25 13:04:281560int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
Andrey Turkin2f53b5b2016-05-29 12:50:061561 const AVFrame *frame, int *got_packet)
Timo Rothenpieler2a428db2014-11-29 23:04:371562{
1563 NVENCSTATUS nv_status;
Andrey Turkine1691c42016-05-20 15:37:001564 NvencSurface *tmpoutsurf, *inSurf;
1565 int res;
Timo Rothenpieler2a428db2014-11-29 23:04:371566
1567 NvencContext *ctx = avctx->priv_data;
1568 NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
1569 NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
1570
1571 NV_ENC_PIC_PARAMS pic_params = { 0 };
1572 pic_params.version = NV_ENC_PIC_PARAMS_VER;
1573
1574 if (frame) {
Andrey Turkin82d705e2016-05-20 14:49:241575 inSurf = get_free_frame(ctx);
Andrey Turkin2f53b5b2016-05-29 12:50:061576 if (!inSurf) {
1577 av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
1578 return AVERROR_BUG;
1579 }
Timo Rothenpieler2a428db2014-11-29 23:04:371580
Andrey Turkin82d705e2016-05-20 14:49:241581 res = nvenc_upload_frame(avctx, frame, inSurf);
1582 if (res) {
1583 inSurf->lockCount = 0;
1584 return res;
Timo Rothenpieler2a428db2014-11-29 23:04:371585 }
1586
Timo Rothenpieler2a428db2014-11-29 23:04:371587 pic_params.inputBuffer = inSurf->input_surface;
1588 pic_params.bufferFmt = inSurf->format;
1589 pic_params.inputWidth = avctx->width;
1590 pic_params.inputHeight = avctx->height;
Andrey Turkine1691c42016-05-20 15:37:001591 pic_params.outputBitstream = inSurf->output_surface;
Timo Rothenpieler2a428db2014-11-29 23:04:371592
Michael Niedermayer94d68a42015-07-27 19:14:311593 if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
Andrey Turkin2f53b5b2016-05-29 12:50:061594 if (frame->top_field_first)
Timo Rothenpieler2a428db2014-11-29 23:04:371595 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
Andrey Turkin2f53b5b2016-05-29 12:50:061596 else
Timo Rothenpieler2a428db2014-11-29 23:04:371597 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
Timo Rothenpieler2a428db2014-11-29 23:04:371598 } else {
1599 pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
1600 }
1601
1602 pic_params.encodePicFlags = 0;
1603 pic_params.inputTimeStamp = frame->pts;
1604 pic_params.inputDuration = 0;
Andrey Turkin82d705e2016-05-20 14:49:241605
1606 nvenc_codec_specific_pic_params(avctx, &pic_params);
Timo Rothenpieler2a428db2014-11-29 23:04:371607 } else {
1608 pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
1609 }
1610
1611 nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
Andrey Turkin2f53b5b2016-05-29 12:50:061612 if (nv_status != NV_ENC_SUCCESS &&
1613 nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
1614 return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
Timo Rothenpieler2a428db2014-11-29 23:04:371615
Andrey Turkin58c6dcb2016-05-29 12:51:361616 if (frame) {
Andrey Turkincfb49fc2016-05-20 16:13:201617 av_fifo_generic_write(ctx->output_surface_queue, &inSurf, sizeof(inSurf), NULL);
Andrey Turkin58c6dcb2016-05-29 12:51:361618 timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
1619 }
Timo Rothenpieler2a428db2014-11-29 23:04:371620
Andrey Turkin2f53b5b2016-05-29 12:50:061621 /* all the pending buffers are now ready for output */
1622 if (nv_status == NV_ENC_SUCCESS) {
Andrey Turkincfb49fc2016-05-20 16:13:201623 while (av_fifo_size(ctx->output_surface_queue) > 0) {
1624 av_fifo_generic_read(ctx->output_surface_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
1625 av_fifo_generic_write(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
Timo Rothenpieler2a428db2014-11-29 23:04:371626 }
Timo Rothenpieler2a428db2014-11-29 23:04:371627 }
1628
Andrey Turkin2f53b5b2016-05-29 12:50:061629 if (output_ready(avctx, !frame)) {
Andrey Turkincfb49fc2016-05-20 16:13:201630 av_fifo_generic_read(ctx->output_surface_ready_queue, &tmpoutsurf, sizeof(tmpoutsurf), NULL);
Timo Rothenpieler2a428db2014-11-29 23:04:371631
Timo Rothenpieler15cd2f82015-07-25 21:26:421632 res = process_output_surface(avctx, pkt, tmpoutsurf);
Timo Rothenpieler2a428db2014-11-29 23:04:371633
1634 if (res)
1635 return res;
1636
Andrey Turkine1691c42016-05-20 15:37:001637 av_assert0(tmpoutsurf->lockCount);
1638 tmpoutsurf->lockCount--;
Timo Rothenpieler2a428db2014-11-29 23:04:371639
1640 *got_packet = 1;
1641 } else {
1642 *got_packet = 0;
1643 }
1644
1645 return 0;
1646}