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.

1403 lines
44KB

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