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.

1603 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_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. if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
  600. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  601. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  602. }
  603. h264->level = ctx->level;
  604. return 0;
  605. }
  606. static int nvenc_setup_hevc_config(AVCodecContext *avctx)
  607. {
  608. NVENCContext *ctx = avctx->priv_data;
  609. NV_ENC_CONFIG *cc = &ctx->config;
  610. NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
  611. NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
  612. vui->colourDescriptionPresentFlag = avctx->colorspace != AVCOL_SPC_UNSPECIFIED ||
  613. avctx->color_primaries != AVCOL_PRI_UNSPECIFIED ||
  614. avctx->color_trc != AVCOL_TRC_UNSPECIFIED;
  615. vui->colourMatrix = avctx->colorspace;
  616. vui->colourPrimaries = avctx->color_primaries;
  617. vui->transferCharacteristics = avctx->color_trc;
  618. vui->videoFullRangeFlag = avctx->color_range == AVCOL_RANGE_JPEG;
  619. vui->videoSignalTypePresentFlag = vui->colourDescriptionPresentFlag ||
  620. vui->videoFullRangeFlag;
  621. hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  622. hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  623. hevc->outputAUD = 1;
  624. hevc->maxNumRefFramesInDPB = avctx->refs;
  625. hevc->idrPeriod = cc->gopLength;
  626. if (IS_CBR(cc->rcParams.rateControlMode)) {
  627. hevc->outputBufferingPeriodSEI = 1;
  628. hevc->outputPictureTimingSEI = 1;
  629. }
  630. switch (ctx->profile) {
  631. case NV_ENC_HEVC_PROFILE_MAIN:
  632. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  633. avctx->profile = FF_PROFILE_HEVC_MAIN;
  634. break;
  635. #if NVENCAPI_MAJOR_VERSION >= 7
  636. case NV_ENC_HEVC_PROFILE_MAIN_10:
  637. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  638. avctx->profile = FF_PROFILE_HEVC_MAIN_10;
  639. break;
  640. case NV_ENC_HEVC_PROFILE_REXT:
  641. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  642. avctx->profile = FF_PROFILE_HEVC_REXT;
  643. break;
  644. #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
  645. }
  646. // force setting profile for various input formats
  647. switch (ctx->data_pix_fmt) {
  648. case AV_PIX_FMT_YUV420P:
  649. case AV_PIX_FMT_NV12:
  650. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  651. avctx->profile = FF_PROFILE_HEVC_MAIN;
  652. break;
  653. #if NVENCAPI_MAJOR_VERSION >= 7
  654. case AV_PIX_FMT_P010:
  655. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  656. avctx->profile = FF_PROFILE_HEVC_MAIN_10;
  657. break;
  658. case AV_PIX_FMT_YUV444P:
  659. case AV_PIX_FMT_YUV444P16:
  660. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  661. avctx->profile = FF_PROFILE_HEVC_REXT;
  662. break;
  663. #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
  664. }
  665. #if NVENCAPI_MAJOR_VERSION >= 7
  666. hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
  667. hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
  668. #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
  669. hevc->sliceMode = 3;
  670. hevc->sliceModeData = FFMAX(avctx->slices, 1);
  671. if (ctx->level) {
  672. hevc->level = ctx->level;
  673. } else {
  674. hevc->level = NV_ENC_LEVEL_AUTOSELECT;
  675. }
  676. if (ctx->tier) {
  677. hevc->tier = ctx->tier;
  678. }
  679. return 0;
  680. }
  681. static int nvenc_setup_codec_config(AVCodecContext *avctx)
  682. {
  683. switch (avctx->codec->id) {
  684. case AV_CODEC_ID_H264:
  685. return nvenc_setup_h264_config(avctx);
  686. case AV_CODEC_ID_HEVC:
  687. return nvenc_setup_hevc_config(avctx);
  688. }
  689. return 0;
  690. }
  691. static int nvenc_setup_encoder(AVCodecContext *avctx)
  692. {
  693. NVENCContext *ctx = avctx->priv_data;
  694. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  695. NV_ENC_PRESET_CONFIG preset_cfg = { 0 };
  696. AVCPBProperties *cpb_props;
  697. int ret;
  698. ctx->params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  699. ctx->params.encodeHeight = avctx->height;
  700. ctx->params.encodeWidth = avctx->width;
  701. if (avctx->sample_aspect_ratio.num &&
  702. avctx->sample_aspect_ratio.den &&
  703. (avctx->sample_aspect_ratio.num != 1 ||
  704. avctx->sample_aspect_ratio.den != 1)) {
  705. av_reduce(&ctx->params.darWidth,
  706. &ctx->params.darHeight,
  707. avctx->width * avctx->sample_aspect_ratio.num,
  708. avctx->height * avctx->sample_aspect_ratio.den,
  709. INT_MAX / 8);
  710. } else {
  711. ctx->params.darHeight = avctx->height;
  712. ctx->params.darWidth = avctx->width;
  713. }
  714. // De-compensate for hardware, dubiously, trying to compensate for
  715. // playback at 704 pixel width.
  716. if (avctx->width == 720 && (avctx->height == 480 || avctx->height == 576)) {
  717. av_reduce(&ctx->params.darWidth, &ctx->params.darHeight,
  718. ctx->params.darWidth * 44,
  719. ctx->params.darHeight * 45,
  720. 1024 * 1024);
  721. }
  722. ctx->params.frameRateNum = avctx->time_base.den;
  723. ctx->params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
  724. ctx->params.enableEncodeAsync = 0;
  725. ctx->params.enablePTD = 1;
  726. ctx->params.encodeConfig = &ctx->config;
  727. nvec_map_preset(ctx);
  728. preset_cfg.version = NV_ENC_PRESET_CONFIG_VER;
  729. preset_cfg.presetCfg.version = NV_ENC_CONFIG_VER;
  730. ret = nv->nvEncGetEncodePresetConfig(ctx->nvenc_ctx,
  731. ctx->params.encodeGUID,
  732. ctx->params.presetGUID,
  733. &preset_cfg);
  734. if (ret != NV_ENC_SUCCESS)
  735. return nvenc_print_error(avctx, ret, "Cannot get the preset configuration");
  736. memcpy(&ctx->config, &preset_cfg.presetCfg, sizeof(ctx->config));
  737. ctx->config.version = NV_ENC_CONFIG_VER;
  738. if (avctx->gop_size > 0) {
  739. if (avctx->max_b_frames > 0) {
  740. /* 0 is intra-only,
  741. * 1 is I/P only,
  742. * 2 is one B-Frame,
  743. * 3 two B-frames, and so on. */
  744. ctx->config.frameIntervalP = avctx->max_b_frames + 1;
  745. } else if (avctx->max_b_frames == 0) {
  746. ctx->config.frameIntervalP = 1;
  747. }
  748. ctx->config.gopLength = avctx->gop_size;
  749. } else if (avctx->gop_size == 0) {
  750. ctx->config.frameIntervalP = 0;
  751. ctx->config.gopLength = 1;
  752. }
  753. if (ctx->config.frameIntervalP > 1)
  754. avctx->max_b_frames = ctx->config.frameIntervalP - 1;
  755. ctx->initial_pts[0] = AV_NOPTS_VALUE;
  756. ctx->initial_pts[1] = AV_NOPTS_VALUE;
  757. nvenc_setup_rate_control(avctx);
  758. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  759. ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  760. } else {
  761. ctx->config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  762. }
  763. if ((ret = nvenc_setup_codec_config(avctx)) < 0)
  764. return ret;
  765. ret = nv->nvEncInitializeEncoder(ctx->nvenc_ctx, &ctx->params);
  766. if (ret != NV_ENC_SUCCESS)
  767. return nvenc_print_error(avctx, ret, "InitializeEncoder failed");
  768. cpb_props = ff_add_cpb_side_data(avctx);
  769. if (!cpb_props)
  770. return AVERROR(ENOMEM);
  771. cpb_props->max_bitrate = avctx->rc_max_rate;
  772. cpb_props->min_bitrate = avctx->rc_min_rate;
  773. cpb_props->avg_bitrate = avctx->bit_rate;
  774. cpb_props->buffer_size = avctx->rc_buffer_size;
  775. return 0;
  776. }
  777. static int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  778. {
  779. NVENCContext *ctx = avctx->priv_data;
  780. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  781. int ret;
  782. NV_ENC_CREATE_BITSTREAM_BUFFER out_buffer = { 0 };
  783. switch (ctx->data_pix_fmt) {
  784. case AV_PIX_FMT_YUV420P:
  785. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YV12_PL;
  786. break;
  787. case AV_PIX_FMT_NV12:
  788. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_NV12_PL;
  789. break;
  790. case AV_PIX_FMT_YUV444P:
  791. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_PL;
  792. break;
  793. #if NVENCAPI_MAJOR_VERSION >= 7
  794. case AV_PIX_FMT_P010:
  795. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
  796. break;
  797. case AV_PIX_FMT_YUV444P16:
  798. ctx->frames[idx].format = NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
  799. break;
  800. #endif /* NVENCAPI_MAJOR_VERSION >= 7 */
  801. default:
  802. return AVERROR_BUG;
  803. }
  804. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  805. ctx->frames[idx].in_ref = av_frame_alloc();
  806. if (!ctx->frames[idx].in_ref)
  807. return AVERROR(ENOMEM);
  808. } else {
  809. NV_ENC_CREATE_INPUT_BUFFER in_buffer = { 0 };
  810. in_buffer.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  811. in_buffer.width = avctx->width;
  812. in_buffer.height = avctx->height;
  813. in_buffer.bufferFmt = ctx->frames[idx].format;
  814. in_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
  815. ret = nv->nvEncCreateInputBuffer(ctx->nvenc_ctx, &in_buffer);
  816. if (ret != NV_ENC_SUCCESS)
  817. return nvenc_print_error(avctx, ret, "CreateInputBuffer failed");
  818. ctx->frames[idx].in = in_buffer.inputBuffer;
  819. }
  820. out_buffer.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  821. /* 1MB is large enough to hold most output frames.
  822. * NVENC increases this automatically if it is not enough. */
  823. out_buffer.size = BITSTREAM_BUFFER_SIZE;
  824. out_buffer.memoryHeap = NV_ENC_MEMORY_HEAP_SYSMEM_UNCACHED;
  825. ret = nv->nvEncCreateBitstreamBuffer(ctx->nvenc_ctx, &out_buffer);
  826. if (ret != NV_ENC_SUCCESS)
  827. return nvenc_print_error(avctx, ret, "CreateBitstreamBuffer failed");
  828. ctx->frames[idx].out = out_buffer.bitstreamBuffer;
  829. return 0;
  830. }
  831. static int nvenc_setup_surfaces(AVCodecContext *avctx)
  832. {
  833. NVENCContext *ctx = avctx->priv_data;
  834. int i, ret;
  835. ctx->nb_surfaces = FFMAX(4 + avctx->max_b_frames,
  836. ctx->nb_surfaces);
  837. ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
  838. ctx->frames = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->frames));
  839. if (!ctx->frames)
  840. return AVERROR(ENOMEM);
  841. ctx->timestamps = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
  842. if (!ctx->timestamps)
  843. return AVERROR(ENOMEM);
  844. ctx->pending = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
  845. if (!ctx->pending)
  846. return AVERROR(ENOMEM);
  847. ctx->ready = av_fifo_alloc(ctx->nb_surfaces * sizeof(*ctx->frames));
  848. if (!ctx->ready)
  849. return AVERROR(ENOMEM);
  850. for (i = 0; i < ctx->nb_surfaces; i++) {
  851. if ((ret = nvenc_alloc_surface(avctx, i)) < 0)
  852. return ret;
  853. }
  854. return 0;
  855. }
  856. #define EXTRADATA_SIZE 512
  857. static int nvenc_setup_extradata(AVCodecContext *avctx)
  858. {
  859. NVENCContext *ctx = avctx->priv_data;
  860. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  861. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  862. int ret;
  863. avctx->extradata = av_mallocz(EXTRADATA_SIZE + AV_INPUT_BUFFER_PADDING_SIZE);
  864. if (!avctx->extradata)
  865. return AVERROR(ENOMEM);
  866. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  867. payload.spsppsBuffer = avctx->extradata;
  868. payload.inBufferSize = EXTRADATA_SIZE;
  869. payload.outSPSPPSPayloadSize = &avctx->extradata_size;
  870. ret = nv->nvEncGetSequenceParams(ctx->nvenc_ctx, &payload);
  871. if (ret != NV_ENC_SUCCESS)
  872. return nvenc_print_error(avctx, ret, "Cannot get the extradata");
  873. return 0;
  874. }
  875. av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
  876. {
  877. NVENCContext *ctx = avctx->priv_data;
  878. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  879. int i;
  880. /* the encoder has to be flushed before it can be closed */
  881. if (ctx->nvenc_ctx) {
  882. NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
  883. .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
  884. nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
  885. }
  886. av_fifo_free(ctx->timestamps);
  887. av_fifo_free(ctx->pending);
  888. av_fifo_free(ctx->ready);
  889. if (ctx->frames) {
  890. for (i = 0; i < ctx->nb_surfaces; ++i) {
  891. if (avctx->pix_fmt != AV_PIX_FMT_CUDA) {
  892. nv->nvEncDestroyInputBuffer(ctx->nvenc_ctx, ctx->frames[i].in);
  893. } else if (ctx->frames[i].in) {
  894. nv->nvEncUnmapInputResource(ctx->nvenc_ctx, ctx->frames[i].in_map.mappedResource);
  895. }
  896. av_frame_free(&ctx->frames[i].in_ref);
  897. nv->nvEncDestroyBitstreamBuffer(ctx->nvenc_ctx, ctx->frames[i].out);
  898. }
  899. }
  900. for (i = 0; i < ctx->nb_registered_frames; i++) {
  901. if (ctx->registered_frames[i].regptr)
  902. nv->nvEncUnregisterResource(ctx->nvenc_ctx, ctx->registered_frames[i].regptr);
  903. }
  904. ctx->nb_registered_frames = 0;
  905. av_freep(&ctx->frames);
  906. if (ctx->nvenc_ctx)
  907. nv->nvEncDestroyEncoder(ctx->nvenc_ctx);
  908. if (ctx->cu_context_internal)
  909. ctx->nvel.cu_ctx_destroy(ctx->cu_context_internal);
  910. if (ctx->nvel.nvenc)
  911. dlclose(ctx->nvel.nvenc);
  912. #if !CONFIG_CUDA
  913. if (ctx->nvel.cuda)
  914. dlclose(ctx->nvel.cuda);
  915. #endif
  916. return 0;
  917. }
  918. av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
  919. {
  920. NVENCContext *ctx = avctx->priv_data;
  921. int ret;
  922. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  923. AVHWFramesContext *frames_ctx;
  924. if (!avctx->hw_frames_ctx) {
  925. av_log(avctx, AV_LOG_ERROR,
  926. "hw_frames_ctx must be set when using GPU frames as input\n");
  927. return AVERROR(EINVAL);
  928. }
  929. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  930. ctx->data_pix_fmt = frames_ctx->sw_format;
  931. } else {
  932. ctx->data_pix_fmt = avctx->pix_fmt;
  933. }
  934. if ((ret = nvenc_load_libraries(avctx)) < 0)
  935. return ret;
  936. if ((ret = nvenc_setup_device(avctx)) < 0)
  937. return ret;
  938. if ((ret = nvenc_setup_encoder(avctx)) < 0)
  939. return ret;
  940. if ((ret = nvenc_setup_surfaces(avctx)) < 0)
  941. return ret;
  942. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  943. if ((ret = nvenc_setup_extradata(avctx)) < 0)
  944. return ret;
  945. }
  946. return 0;
  947. }
  948. static NVENCFrame *get_free_frame(NVENCContext *ctx)
  949. {
  950. int i;
  951. for (i = 0; i < ctx->nb_surfaces; i++) {
  952. if (!ctx->frames[i].locked) {
  953. ctx->frames[i].locked = 1;
  954. return &ctx->frames[i];
  955. }
  956. }
  957. return NULL;
  958. }
  959. static int nvenc_copy_frame(NV_ENC_LOCK_INPUT_BUFFER *in, const AVFrame *frame)
  960. {
  961. uint8_t *buf = in->bufferDataPtr;
  962. int off = frame->height * in->pitch;
  963. switch (frame->format) {
  964. case AV_PIX_FMT_YUV420P:
  965. av_image_copy_plane(buf, in->pitch,
  966. frame->data[0], frame->linesize[0],
  967. frame->width, frame->height);
  968. buf += off;
  969. av_image_copy_plane(buf, in->pitch >> 1,
  970. frame->data[2], frame->linesize[2],
  971. frame->width >> 1, frame->height >> 1);
  972. buf += off >> 2;
  973. av_image_copy_plane(buf, in->pitch >> 1,
  974. frame->data[1], frame->linesize[1],
  975. frame->width >> 1, frame->height >> 1);
  976. break;
  977. case AV_PIX_FMT_NV12:
  978. av_image_copy_plane(buf, in->pitch,
  979. frame->data[0], frame->linesize[0],
  980. frame->width, frame->height);
  981. buf += off;
  982. av_image_copy_plane(buf, in->pitch,
  983. frame->data[1], frame->linesize[1],
  984. frame->width, frame->height >> 1);
  985. break;
  986. case AV_PIX_FMT_P010:
  987. av_image_copy_plane(buf, in->pitch,
  988. frame->data[0], frame->linesize[0],
  989. frame->width << 1, frame->height);
  990. buf += off;
  991. av_image_copy_plane(buf, in->pitch,
  992. frame->data[1], frame->linesize[1],
  993. frame->width << 1, frame->height >> 1);
  994. break;
  995. case AV_PIX_FMT_YUV444P:
  996. av_image_copy_plane(buf, in->pitch,
  997. frame->data[0], frame->linesize[0],
  998. frame->width, frame->height);
  999. buf += off;
  1000. av_image_copy_plane(buf, in->pitch,
  1001. frame->data[1], frame->linesize[1],
  1002. frame->width, frame->height);
  1003. buf += off;
  1004. av_image_copy_plane(buf, in->pitch,
  1005. frame->data[2], frame->linesize[2],
  1006. frame->width, frame->height);
  1007. break;
  1008. case AV_PIX_FMT_YUV444P16:
  1009. av_image_copy_plane(buf, in->pitch,
  1010. frame->data[0], frame->linesize[0],
  1011. frame->width << 1, frame->height);
  1012. buf += off;
  1013. av_image_copy_plane(buf, in->pitch,
  1014. frame->data[1], frame->linesize[1],
  1015. frame->width << 1, frame->height);
  1016. buf += off;
  1017. av_image_copy_plane(buf, in->pitch,
  1018. frame->data[2], frame->linesize[2],
  1019. frame->width << 1, frame->height);
  1020. break;
  1021. default:
  1022. return AVERROR_BUG;
  1023. }
  1024. return 0;
  1025. }
  1026. static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
  1027. {
  1028. NVENCContext *ctx = avctx->priv_data;
  1029. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1030. int i;
  1031. if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
  1032. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1033. if (!ctx->registered_frames[i].mapped) {
  1034. if (ctx->registered_frames[i].regptr) {
  1035. nv->nvEncUnregisterResource(ctx->nvenc_ctx,
  1036. ctx->registered_frames[i].regptr);
  1037. ctx->registered_frames[i].regptr = NULL;
  1038. }
  1039. return i;
  1040. }
  1041. }
  1042. } else {
  1043. return ctx->nb_registered_frames++;
  1044. }
  1045. av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
  1046. return AVERROR(ENOMEM);
  1047. }
  1048. static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
  1049. {
  1050. NVENCContext *ctx = avctx->priv_data;
  1051. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1052. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1053. NV_ENC_REGISTER_RESOURCE reg;
  1054. int i, idx, ret;
  1055. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1056. if (ctx->registered_frames[i].ptr == (CUdeviceptr)frame->data[0])
  1057. return i;
  1058. }
  1059. idx = nvenc_find_free_reg_resource(avctx);
  1060. if (idx < 0)
  1061. return idx;
  1062. reg.version = NV_ENC_REGISTER_RESOURCE_VER;
  1063. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
  1064. reg.width = frames_ctx->width;
  1065. reg.height = frames_ctx->height;
  1066. reg.bufferFormat = ctx->frames[0].format;
  1067. reg.pitch = frame->linesize[0];
  1068. reg.resourceToRegister = frame->data[0];
  1069. ret = nv->nvEncRegisterResource(ctx->nvenc_ctx, &reg);
  1070. if (ret != NV_ENC_SUCCESS) {
  1071. nvenc_print_error(avctx, ret, "Error registering an input resource");
  1072. return AVERROR_UNKNOWN;
  1073. }
  1074. ctx->registered_frames[idx].ptr = (CUdeviceptr)frame->data[0];
  1075. ctx->registered_frames[idx].regptr = reg.registeredResource;
  1076. return idx;
  1077. }
  1078. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  1079. NVENCFrame *nvenc_frame)
  1080. {
  1081. NVENCContext *ctx = avctx->priv_data;
  1082. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1083. int ret;
  1084. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1085. int reg_idx;
  1086. ret = nvenc_register_frame(avctx, frame);
  1087. if (ret < 0) {
  1088. av_log(avctx, AV_LOG_ERROR, "Could not register an input CUDA frame\n");
  1089. return ret;
  1090. }
  1091. reg_idx = ret;
  1092. ret = av_frame_ref(nvenc_frame->in_ref, frame);
  1093. if (ret < 0)
  1094. return ret;
  1095. nvenc_frame->in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
  1096. nvenc_frame->in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
  1097. ret = nv->nvEncMapInputResource(ctx->nvenc_ctx, &nvenc_frame->in_map);
  1098. if (ret != NV_ENC_SUCCESS) {
  1099. av_frame_unref(nvenc_frame->in_ref);
  1100. return nvenc_print_error(avctx, ret, "Error mapping an input resource");
  1101. }
  1102. ctx->registered_frames[reg_idx].mapped = 1;
  1103. nvenc_frame->reg_idx = reg_idx;
  1104. nvenc_frame->in = nvenc_frame->in_map.mappedResource;
  1105. } else {
  1106. NV_ENC_LOCK_INPUT_BUFFER params = { 0 };
  1107. params.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  1108. params.inputBuffer = nvenc_frame->in;
  1109. ret = nv->nvEncLockInputBuffer(ctx->nvenc_ctx, &params);
  1110. if (ret != NV_ENC_SUCCESS)
  1111. return nvenc_print_error(avctx, ret, "Cannot lock the buffer");
  1112. ret = nvenc_copy_frame(&params, frame);
  1113. if (ret < 0) {
  1114. nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
  1115. return ret;
  1116. }
  1117. ret = nv->nvEncUnlockInputBuffer(ctx->nvenc_ctx, nvenc_frame->in);
  1118. if (ret != NV_ENC_SUCCESS)
  1119. return nvenc_print_error(avctx, ret, "Cannot unlock the buffer");
  1120. }
  1121. return 0;
  1122. }
  1123. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  1124. NV_ENC_PIC_PARAMS *params)
  1125. {
  1126. NVENCContext *ctx = avctx->priv_data;
  1127. switch (avctx->codec->id) {
  1128. case AV_CODEC_ID_H264:
  1129. params->codecPicParams.h264PicParams.sliceMode =
  1130. ctx->config.encodeCodecConfig.h264Config.sliceMode;
  1131. params->codecPicParams.h264PicParams.sliceModeData =
  1132. ctx->config.encodeCodecConfig.h264Config.sliceModeData;
  1133. break;
  1134. case AV_CODEC_ID_HEVC:
  1135. params->codecPicParams.hevcPicParams.sliceMode =
  1136. ctx->config.encodeCodecConfig.hevcConfig.sliceMode;
  1137. params->codecPicParams.hevcPicParams.sliceModeData =
  1138. ctx->config.encodeCodecConfig.hevcConfig.sliceModeData;
  1139. break;
  1140. }
  1141. }
  1142. static inline int nvenc_enqueue_timestamp(AVFifoBuffer *f, int64_t pts)
  1143. {
  1144. return av_fifo_generic_write(f, &pts, sizeof(pts), NULL);
  1145. }
  1146. static inline int nvenc_dequeue_timestamp(AVFifoBuffer *f, int64_t *pts)
  1147. {
  1148. return av_fifo_generic_read(f, pts, sizeof(*pts), NULL);
  1149. }
  1150. static int nvenc_set_timestamp(AVCodecContext *avctx,
  1151. NV_ENC_LOCK_BITSTREAM *params,
  1152. AVPacket *pkt)
  1153. {
  1154. NVENCContext *ctx = avctx->priv_data;
  1155. pkt->pts = params->outputTimeStamp;
  1156. pkt->duration = params->outputDuration;
  1157. /* generate the first dts by linearly extrapolating the
  1158. * first two pts values to the past */
  1159. if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
  1160. ctx->initial_pts[1] != AV_NOPTS_VALUE) {
  1161. int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
  1162. int64_t delta;
  1163. if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
  1164. (ts0 > 0 && ts1 < INT64_MIN + ts0))
  1165. return AVERROR(ERANGE);
  1166. delta = ts1 - ts0;
  1167. if ((delta < 0 && ts0 > INT64_MAX + delta) ||
  1168. (delta > 0 && ts0 < INT64_MIN + delta))
  1169. return AVERROR(ERANGE);
  1170. pkt->dts = ts0 - delta;
  1171. ctx->first_packet_output = 1;
  1172. return 0;
  1173. }
  1174. return nvenc_dequeue_timestamp(ctx->timestamps, &pkt->dts);
  1175. }
  1176. static int nvenc_get_output(AVCodecContext *avctx, AVPacket *pkt)
  1177. {
  1178. NVENCContext *ctx = avctx->priv_data;
  1179. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1180. NV_ENC_LOCK_BITSTREAM params = { 0 };
  1181. NVENCFrame *frame;
  1182. int ret;
  1183. ret = av_fifo_generic_read(ctx->ready, &frame, sizeof(frame), NULL);
  1184. if (ret)
  1185. return ret;
  1186. params.version = NV_ENC_LOCK_BITSTREAM_VER;
  1187. params.outputBitstream = frame->out;
  1188. ret = nv->nvEncLockBitstream(ctx->nvenc_ctx, &params);
  1189. if (ret < 0)
  1190. return nvenc_print_error(avctx, ret, "Cannot lock the bitstream");
  1191. ret = ff_alloc_packet(pkt, params.bitstreamSizeInBytes);
  1192. if (ret < 0)
  1193. return ret;
  1194. memcpy(pkt->data, params.bitstreamBufferPtr, pkt->size);
  1195. ret = nv->nvEncUnlockBitstream(ctx->nvenc_ctx, frame->out);
  1196. if (ret < 0)
  1197. return nvenc_print_error(avctx, ret, "Cannot unlock the bitstream");
  1198. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1199. nv->nvEncUnmapInputResource(ctx->nvenc_ctx, frame->in_map.mappedResource);
  1200. av_frame_unref(frame->in_ref);
  1201. ctx->registered_frames[frame->reg_idx].mapped = 0;
  1202. frame->in = NULL;
  1203. }
  1204. frame->locked = 0;
  1205. ret = nvenc_set_timestamp(avctx, &params, pkt);
  1206. if (ret < 0)
  1207. return ret;
  1208. switch (params.pictureType) {
  1209. case NV_ENC_PIC_TYPE_IDR:
  1210. pkt->flags |= AV_PKT_FLAG_KEY;
  1211. #if FF_API_CODED_FRAME
  1212. FF_DISABLE_DEPRECATION_WARNINGS
  1213. case NV_ENC_PIC_TYPE_INTRA_REFRESH:
  1214. case NV_ENC_PIC_TYPE_I:
  1215. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_I;
  1216. break;
  1217. case NV_ENC_PIC_TYPE_P:
  1218. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_P;
  1219. break;
  1220. case NV_ENC_PIC_TYPE_B:
  1221. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_B;
  1222. break;
  1223. case NV_ENC_PIC_TYPE_BI:
  1224. avctx->coded_frame->pict_type = AV_PICTURE_TYPE_BI;
  1225. break;
  1226. FF_ENABLE_DEPRECATION_WARNINGS
  1227. #endif
  1228. }
  1229. return 0;
  1230. }
  1231. static int output_ready(AVCodecContext *avctx, int flush)
  1232. {
  1233. NVENCContext *ctx = avctx->priv_data;
  1234. int nb_ready, nb_pending;
  1235. /* when B-frames are enabled, we wait for two initial timestamps to
  1236. * calculate the first dts */
  1237. if (!flush && avctx->max_b_frames > 0 &&
  1238. (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
  1239. return 0;
  1240. nb_ready = av_fifo_size(ctx->ready) / sizeof(NVENCFrame*);
  1241. nb_pending = av_fifo_size(ctx->pending) / sizeof(NVENCFrame*);
  1242. if (flush)
  1243. return nb_ready > 0;
  1244. return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
  1245. }
  1246. int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1247. const AVFrame *frame, int *got_packet)
  1248. {
  1249. NVENCContext *ctx = avctx->priv_data;
  1250. NV_ENCODE_API_FUNCTION_LIST *nv = &ctx->nvel.nvenc_funcs;
  1251. NV_ENC_PIC_PARAMS params = { 0 };
  1252. NVENCFrame *nvenc_frame = NULL;
  1253. int enc_ret, ret;
  1254. params.version = NV_ENC_PIC_PARAMS_VER;
  1255. if (frame) {
  1256. nvenc_frame = get_free_frame(ctx);
  1257. if (!nvenc_frame) {
  1258. av_log(avctx, AV_LOG_ERROR, "No free surfaces\n");
  1259. return AVERROR_BUG;
  1260. }
  1261. ret = nvenc_upload_frame(avctx, frame, nvenc_frame);
  1262. if (ret < 0)
  1263. return ret;
  1264. params.inputBuffer = nvenc_frame->in;
  1265. params.bufferFmt = nvenc_frame->format;
  1266. params.inputWidth = frame->width;
  1267. params.inputHeight = frame->height;
  1268. params.outputBitstream = nvenc_frame->out;
  1269. params.inputTimeStamp = frame->pts;
  1270. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1271. if (frame->top_field_first)
  1272. params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  1273. else
  1274. params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  1275. } else {
  1276. params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  1277. }
  1278. nvenc_codec_specific_pic_params(avctx, &params);
  1279. ret = nvenc_enqueue_timestamp(ctx->timestamps, frame->pts);
  1280. if (ret < 0)
  1281. return ret;
  1282. if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
  1283. ctx->initial_pts[0] = frame->pts;
  1284. else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
  1285. ctx->initial_pts[1] = frame->pts;
  1286. } else {
  1287. params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  1288. }
  1289. enc_ret = nv->nvEncEncodePicture(ctx->nvenc_ctx, &params);
  1290. if (enc_ret != NV_ENC_SUCCESS &&
  1291. enc_ret != NV_ENC_ERR_NEED_MORE_INPUT)
  1292. return nvenc_print_error(avctx, enc_ret, "Error encoding the frame");
  1293. if (nvenc_frame) {
  1294. ret = av_fifo_generic_write(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
  1295. if (ret < 0)
  1296. return ret;
  1297. }
  1298. /* all the pending buffers are now ready for output */
  1299. if (enc_ret == NV_ENC_SUCCESS) {
  1300. while (av_fifo_size(ctx->pending) > 0) {
  1301. av_fifo_generic_read(ctx->pending, &nvenc_frame, sizeof(nvenc_frame), NULL);
  1302. av_fifo_generic_write(ctx->ready, &nvenc_frame, sizeof(nvenc_frame), NULL);
  1303. }
  1304. }
  1305. if (output_ready(avctx, !frame)) {
  1306. ret = nvenc_get_output(avctx, pkt);
  1307. if (ret < 0)
  1308. return ret;
  1309. *got_packet = 1;
  1310. } else {
  1311. *got_packet = 0;
  1312. }
  1313. return 0;
  1314. }