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.

1416 lines
45KB

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