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.

1613 lines
52KB

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