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.

1598 lines
51KB

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