You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1610 lines
52KB

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