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.

1444 lines
46KB

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