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.

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