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.

2057 lines
69KB

  1. /*
  2. * H.264/HEVC hardware encoding using nvidia nvenc
  3. * Copyright (c) 2016 Timo Rothenpieler <timo@rothenpieler.org>
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg 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. * FFmpeg 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 FFmpeg; 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 "nvenc.h"
  23. #include "libavutil/hwcontext_cuda.h"
  24. #include "libavutil/hwcontext.h"
  25. #include "libavutil/imgutils.h"
  26. #include "libavutil/avassert.h"
  27. #include "libavutil/mem.h"
  28. #include "libavutil/pixdesc.h"
  29. #include "internal.h"
  30. #define NVENC_CAP 0x30
  31. #define IS_CBR(rc) (rc == NV_ENC_PARAMS_RC_CBR || \
  32. rc == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ || \
  33. rc == NV_ENC_PARAMS_RC_CBR_HQ)
  34. const enum AVPixelFormat ff_nvenc_pix_fmts[] = {
  35. AV_PIX_FMT_YUV420P,
  36. AV_PIX_FMT_NV12,
  37. AV_PIX_FMT_P010,
  38. AV_PIX_FMT_YUV444P,
  39. AV_PIX_FMT_P016, // Truncated to 10bits
  40. AV_PIX_FMT_YUV444P16, // Truncated to 10bits
  41. AV_PIX_FMT_0RGB32,
  42. AV_PIX_FMT_0BGR32,
  43. AV_PIX_FMT_CUDA,
  44. #if CONFIG_D3D11VA
  45. AV_PIX_FMT_D3D11,
  46. #endif
  47. AV_PIX_FMT_NONE
  48. };
  49. #define IS_10BIT(pix_fmt) (pix_fmt == AV_PIX_FMT_P010 || \
  50. pix_fmt == AV_PIX_FMT_P016 || \
  51. pix_fmt == AV_PIX_FMT_YUV444P16)
  52. #define IS_YUV444(pix_fmt) (pix_fmt == AV_PIX_FMT_YUV444P || \
  53. pix_fmt == AV_PIX_FMT_YUV444P16)
  54. static const struct {
  55. NVENCSTATUS nverr;
  56. int averr;
  57. const char *desc;
  58. } nvenc_errors[] = {
  59. { NV_ENC_SUCCESS, 0, "success" },
  60. { NV_ENC_ERR_NO_ENCODE_DEVICE, AVERROR(ENOENT), "no encode device" },
  61. { NV_ENC_ERR_UNSUPPORTED_DEVICE, AVERROR(ENOSYS), "unsupported device" },
  62. { NV_ENC_ERR_INVALID_ENCODERDEVICE, AVERROR(EINVAL), "invalid encoder device" },
  63. { NV_ENC_ERR_INVALID_DEVICE, AVERROR(EINVAL), "invalid device" },
  64. { NV_ENC_ERR_DEVICE_NOT_EXIST, AVERROR(EIO), "device does not exist" },
  65. { NV_ENC_ERR_INVALID_PTR, AVERROR(EFAULT), "invalid ptr" },
  66. { NV_ENC_ERR_INVALID_EVENT, AVERROR(EINVAL), "invalid event" },
  67. { NV_ENC_ERR_INVALID_PARAM, AVERROR(EINVAL), "invalid param" },
  68. { NV_ENC_ERR_INVALID_CALL, AVERROR(EINVAL), "invalid call" },
  69. { NV_ENC_ERR_OUT_OF_MEMORY, AVERROR(ENOMEM), "out of memory" },
  70. { NV_ENC_ERR_ENCODER_NOT_INITIALIZED, AVERROR(EINVAL), "encoder not initialized" },
  71. { NV_ENC_ERR_UNSUPPORTED_PARAM, AVERROR(ENOSYS), "unsupported param" },
  72. { NV_ENC_ERR_LOCK_BUSY, AVERROR(EAGAIN), "lock busy" },
  73. { NV_ENC_ERR_NOT_ENOUGH_BUFFER, AVERROR_BUFFER_TOO_SMALL, "not enough buffer"},
  74. { NV_ENC_ERR_INVALID_VERSION, AVERROR(EINVAL), "invalid version" },
  75. { NV_ENC_ERR_MAP_FAILED, AVERROR(EIO), "map failed" },
  76. { NV_ENC_ERR_NEED_MORE_INPUT, AVERROR(EAGAIN), "need more input" },
  77. { NV_ENC_ERR_ENCODER_BUSY, AVERROR(EAGAIN), "encoder busy" },
  78. { NV_ENC_ERR_EVENT_NOT_REGISTERD, AVERROR(EBADF), "event not registered" },
  79. { NV_ENC_ERR_GENERIC, AVERROR_UNKNOWN, "generic error" },
  80. { NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY, AVERROR(EINVAL), "incompatible client key" },
  81. { NV_ENC_ERR_UNIMPLEMENTED, AVERROR(ENOSYS), "unimplemented" },
  82. { NV_ENC_ERR_RESOURCE_REGISTER_FAILED, AVERROR(EIO), "resource register failed" },
  83. { NV_ENC_ERR_RESOURCE_NOT_REGISTERED, AVERROR(EBADF), "resource not registered" },
  84. { NV_ENC_ERR_RESOURCE_NOT_MAPPED, AVERROR(EBADF), "resource not mapped" },
  85. };
  86. static int nvenc_map_error(NVENCSTATUS err, const char **desc)
  87. {
  88. int i;
  89. for (i = 0; i < FF_ARRAY_ELEMS(nvenc_errors); i++) {
  90. if (nvenc_errors[i].nverr == err) {
  91. if (desc)
  92. *desc = nvenc_errors[i].desc;
  93. return nvenc_errors[i].averr;
  94. }
  95. }
  96. if (desc)
  97. *desc = "unknown error";
  98. return AVERROR_UNKNOWN;
  99. }
  100. static int nvenc_print_error(void *log_ctx, NVENCSTATUS err,
  101. const char *error_string)
  102. {
  103. const char *desc;
  104. int ret;
  105. ret = nvenc_map_error(err, &desc);
  106. av_log(log_ctx, AV_LOG_ERROR, "%s: %s (%d)\n", error_string, desc, err);
  107. return ret;
  108. }
  109. static void nvenc_print_driver_requirement(AVCodecContext *avctx, int level)
  110. {
  111. #if defined(_WIN32) || defined(__CYGWIN__)
  112. const char *minver = "378.66";
  113. #else
  114. const char *minver = "378.13";
  115. #endif
  116. av_log(avctx, level, "The minimum required Nvidia driver for nvenc is %s or newer\n", minver);
  117. }
  118. static av_cold int nvenc_load_libraries(AVCodecContext *avctx)
  119. {
  120. NvencContext *ctx = avctx->priv_data;
  121. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  122. NVENCSTATUS err;
  123. uint32_t nvenc_max_ver;
  124. int ret;
  125. ret = cuda_load_functions(&dl_fn->cuda_dl, avctx);
  126. if (ret < 0)
  127. return ret;
  128. ret = nvenc_load_functions(&dl_fn->nvenc_dl, avctx);
  129. if (ret < 0) {
  130. nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
  131. return ret;
  132. }
  133. err = dl_fn->nvenc_dl->NvEncodeAPIGetMaxSupportedVersion(&nvenc_max_ver);
  134. if (err != NV_ENC_SUCCESS)
  135. return nvenc_print_error(avctx, err, "Failed to query nvenc max version");
  136. av_log(avctx, AV_LOG_VERBOSE, "Loaded Nvenc version %d.%d\n", nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
  137. if ((NVENCAPI_MAJOR_VERSION << 4 | NVENCAPI_MINOR_VERSION) > nvenc_max_ver) {
  138. av_log(avctx, AV_LOG_ERROR, "Driver does not support the required nvenc API version. "
  139. "Required: %d.%d Found: %d.%d\n",
  140. NVENCAPI_MAJOR_VERSION, NVENCAPI_MINOR_VERSION,
  141. nvenc_max_ver >> 4, nvenc_max_ver & 0xf);
  142. nvenc_print_driver_requirement(avctx, AV_LOG_ERROR);
  143. return AVERROR(ENOSYS);
  144. }
  145. dl_fn->nvenc_funcs.version = NV_ENCODE_API_FUNCTION_LIST_VER;
  146. err = dl_fn->nvenc_dl->NvEncodeAPICreateInstance(&dl_fn->nvenc_funcs);
  147. if (err != NV_ENC_SUCCESS)
  148. return nvenc_print_error(avctx, err, "Failed to create nvenc instance");
  149. av_log(avctx, AV_LOG_VERBOSE, "Nvenc initialized successfully\n");
  150. return 0;
  151. }
  152. static int nvenc_push_context(AVCodecContext *avctx)
  153. {
  154. NvencContext *ctx = avctx->priv_data;
  155. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  156. CUresult cu_res;
  157. if (ctx->d3d11_device)
  158. return 0;
  159. cu_res = dl_fn->cuda_dl->cuCtxPushCurrent(ctx->cu_context);
  160. if (cu_res != CUDA_SUCCESS) {
  161. av_log(avctx, AV_LOG_ERROR, "cuCtxPushCurrent failed\n");
  162. return AVERROR_EXTERNAL;
  163. }
  164. return 0;
  165. }
  166. static int nvenc_pop_context(AVCodecContext *avctx)
  167. {
  168. NvencContext *ctx = avctx->priv_data;
  169. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  170. CUresult cu_res;
  171. CUcontext dummy;
  172. if (ctx->d3d11_device)
  173. return 0;
  174. cu_res = dl_fn->cuda_dl->cuCtxPopCurrent(&dummy);
  175. if (cu_res != CUDA_SUCCESS) {
  176. av_log(avctx, AV_LOG_ERROR, "cuCtxPopCurrent failed\n");
  177. return AVERROR_EXTERNAL;
  178. }
  179. return 0;
  180. }
  181. static av_cold int nvenc_open_session(AVCodecContext *avctx)
  182. {
  183. NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { 0 };
  184. NvencContext *ctx = avctx->priv_data;
  185. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  186. NVENCSTATUS ret;
  187. params.version = NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER;
  188. params.apiVersion = NVENCAPI_VERSION;
  189. if (ctx->d3d11_device) {
  190. params.device = ctx->d3d11_device;
  191. params.deviceType = NV_ENC_DEVICE_TYPE_DIRECTX;
  192. } else {
  193. params.device = ctx->cu_context;
  194. params.deviceType = NV_ENC_DEVICE_TYPE_CUDA;
  195. }
  196. ret = p_nvenc->nvEncOpenEncodeSessionEx(&params, &ctx->nvencoder);
  197. if (ret != NV_ENC_SUCCESS) {
  198. ctx->nvencoder = NULL;
  199. return nvenc_print_error(avctx, ret, "OpenEncodeSessionEx failed");
  200. }
  201. return 0;
  202. }
  203. static int nvenc_check_codec_support(AVCodecContext *avctx)
  204. {
  205. NvencContext *ctx = avctx->priv_data;
  206. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  207. int i, ret, count = 0;
  208. GUID *guids = NULL;
  209. ret = p_nvenc->nvEncGetEncodeGUIDCount(ctx->nvencoder, &count);
  210. if (ret != NV_ENC_SUCCESS || !count)
  211. return AVERROR(ENOSYS);
  212. guids = av_malloc(count * sizeof(GUID));
  213. if (!guids)
  214. return AVERROR(ENOMEM);
  215. ret = p_nvenc->nvEncGetEncodeGUIDs(ctx->nvencoder, guids, count, &count);
  216. if (ret != NV_ENC_SUCCESS) {
  217. ret = AVERROR(ENOSYS);
  218. goto fail;
  219. }
  220. ret = AVERROR(ENOSYS);
  221. for (i = 0; i < count; i++) {
  222. if (!memcmp(&guids[i], &ctx->init_encode_params.encodeGUID, sizeof(*guids))) {
  223. ret = 0;
  224. break;
  225. }
  226. }
  227. fail:
  228. av_free(guids);
  229. return ret;
  230. }
  231. static int nvenc_check_cap(AVCodecContext *avctx, NV_ENC_CAPS cap)
  232. {
  233. NvencContext *ctx = avctx->priv_data;
  234. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &ctx->nvenc_dload_funcs.nvenc_funcs;
  235. NV_ENC_CAPS_PARAM params = { 0 };
  236. int ret, val = 0;
  237. params.version = NV_ENC_CAPS_PARAM_VER;
  238. params.capsToQuery = cap;
  239. ret = p_nvenc->nvEncGetEncodeCaps(ctx->nvencoder, ctx->init_encode_params.encodeGUID, &params, &val);
  240. if (ret == NV_ENC_SUCCESS)
  241. return val;
  242. return 0;
  243. }
  244. static int nvenc_check_capabilities(AVCodecContext *avctx)
  245. {
  246. NvencContext *ctx = avctx->priv_data;
  247. int ret;
  248. ret = nvenc_check_codec_support(avctx);
  249. if (ret < 0) {
  250. av_log(avctx, AV_LOG_VERBOSE, "Codec not supported\n");
  251. return ret;
  252. }
  253. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE);
  254. if (IS_YUV444(ctx->data_pix_fmt) && ret <= 0) {
  255. av_log(avctx, AV_LOG_VERBOSE, "YUV444P not supported\n");
  256. return AVERROR(ENOSYS);
  257. }
  258. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOSSLESS_ENCODE);
  259. if (ctx->preset >= PRESET_LOSSLESS_DEFAULT && ret <= 0) {
  260. av_log(avctx, AV_LOG_VERBOSE, "Lossless encoding not supported\n");
  261. return AVERROR(ENOSYS);
  262. }
  263. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_WIDTH_MAX);
  264. if (ret < avctx->width) {
  265. av_log(avctx, AV_LOG_VERBOSE, "Width %d exceeds %d\n",
  266. avctx->width, ret);
  267. return AVERROR(ENOSYS);
  268. }
  269. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_HEIGHT_MAX);
  270. if (ret < avctx->height) {
  271. av_log(avctx, AV_LOG_VERBOSE, "Height %d exceeds %d\n",
  272. avctx->height, ret);
  273. return AVERROR(ENOSYS);
  274. }
  275. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_NUM_MAX_BFRAMES);
  276. if (ret < avctx->max_b_frames) {
  277. av_log(avctx, AV_LOG_VERBOSE, "Max B-frames %d exceed %d\n",
  278. avctx->max_b_frames, ret);
  279. return AVERROR(ENOSYS);
  280. }
  281. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_FIELD_ENCODING);
  282. if (ret < 1 && avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  283. av_log(avctx, AV_LOG_VERBOSE,
  284. "Interlaced encoding is not supported. Supported level: %d\n",
  285. ret);
  286. return AVERROR(ENOSYS);
  287. }
  288. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE);
  289. if (IS_10BIT(ctx->data_pix_fmt) && ret <= 0) {
  290. av_log(avctx, AV_LOG_VERBOSE, "10 bit encode not supported\n");
  291. return AVERROR(ENOSYS);
  292. }
  293. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_LOOKAHEAD);
  294. if (ctx->rc_lookahead > 0 && ret <= 0) {
  295. av_log(avctx, AV_LOG_VERBOSE, "RC lookahead not supported\n");
  296. return AVERROR(ENOSYS);
  297. }
  298. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ);
  299. if (ctx->temporal_aq > 0 && ret <= 0) {
  300. av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ not supported\n");
  301. return AVERROR(ENOSYS);
  302. }
  303. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_WEIGHTED_PREDICTION);
  304. if (ctx->weighted_pred > 0 && ret <= 0) {
  305. av_log (avctx, AV_LOG_VERBOSE, "Weighted Prediction not supported\n");
  306. return AVERROR(ENOSYS);
  307. }
  308. ret = nvenc_check_cap(avctx, NV_ENC_CAPS_SUPPORT_CABAC);
  309. if (ctx->coder == NV_ENC_H264_ENTROPY_CODING_MODE_CABAC && ret <= 0) {
  310. av_log(avctx, AV_LOG_VERBOSE, "CABAC entropy coding not supported\n");
  311. return AVERROR(ENOSYS);
  312. }
  313. return 0;
  314. }
  315. static av_cold int nvenc_check_device(AVCodecContext *avctx, int idx)
  316. {
  317. NvencContext *ctx = avctx->priv_data;
  318. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  319. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  320. char name[128] = { 0};
  321. int major, minor, ret;
  322. CUresult cu_res;
  323. CUdevice cu_device;
  324. int loglevel = AV_LOG_VERBOSE;
  325. if (ctx->device == LIST_DEVICES)
  326. loglevel = AV_LOG_INFO;
  327. cu_res = dl_fn->cuda_dl->cuDeviceGet(&cu_device, idx);
  328. if (cu_res != CUDA_SUCCESS) {
  329. av_log(avctx, AV_LOG_ERROR,
  330. "Cannot access the CUDA device %d\n",
  331. idx);
  332. return -1;
  333. }
  334. cu_res = dl_fn->cuda_dl->cuDeviceGetName(name, sizeof(name), cu_device);
  335. if (cu_res != CUDA_SUCCESS) {
  336. av_log(avctx, AV_LOG_ERROR, "cuDeviceGetName failed on device %d\n", idx);
  337. return -1;
  338. }
  339. cu_res = dl_fn->cuda_dl->cuDeviceComputeCapability(&major, &minor, cu_device);
  340. if (cu_res != CUDA_SUCCESS) {
  341. av_log(avctx, AV_LOG_ERROR, "cuDeviceComputeCapability failed on device %d\n", idx);
  342. return -1;
  343. }
  344. av_log(avctx, loglevel, "[ GPU #%d - < %s > has Compute SM %d.%d ]\n", idx, name, major, minor);
  345. if (((major << 4) | minor) < NVENC_CAP) {
  346. av_log(avctx, loglevel, "does not support NVENC\n");
  347. goto fail;
  348. }
  349. if (ctx->device != idx && ctx->device != ANY_DEVICE)
  350. return -1;
  351. cu_res = dl_fn->cuda_dl->cuCtxCreate(&ctx->cu_context_internal, 0, cu_device);
  352. if (cu_res != CUDA_SUCCESS) {
  353. av_log(avctx, AV_LOG_FATAL, "Failed creating CUDA context for NVENC: 0x%x\n", (int)cu_res);
  354. goto fail;
  355. }
  356. ctx->cu_context = ctx->cu_context_internal;
  357. if ((ret = nvenc_pop_context(avctx)) < 0)
  358. goto fail2;
  359. if ((ret = nvenc_open_session(avctx)) < 0)
  360. goto fail2;
  361. if ((ret = nvenc_check_capabilities(avctx)) < 0)
  362. goto fail3;
  363. av_log(avctx, loglevel, "supports NVENC\n");
  364. dl_fn->nvenc_device_count++;
  365. if (ctx->device == idx || ctx->device == ANY_DEVICE)
  366. return 0;
  367. fail3:
  368. if ((ret = nvenc_push_context(avctx)) < 0)
  369. return ret;
  370. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  371. ctx->nvencoder = NULL;
  372. if ((ret = nvenc_pop_context(avctx)) < 0)
  373. return ret;
  374. fail2:
  375. dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
  376. ctx->cu_context_internal = NULL;
  377. fail:
  378. return AVERROR(ENOSYS);
  379. }
  380. static av_cold int nvenc_setup_device(AVCodecContext *avctx)
  381. {
  382. NvencContext *ctx = avctx->priv_data;
  383. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  384. switch (avctx->codec->id) {
  385. case AV_CODEC_ID_H264:
  386. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_H264_GUID;
  387. break;
  388. case AV_CODEC_ID_HEVC:
  389. ctx->init_encode_params.encodeGUID = NV_ENC_CODEC_HEVC_GUID;
  390. break;
  391. default:
  392. return AVERROR_BUG;
  393. }
  394. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11 || avctx->hw_frames_ctx || avctx->hw_device_ctx) {
  395. AVHWFramesContext *frames_ctx;
  396. AVHWDeviceContext *hwdev_ctx;
  397. AVCUDADeviceContext *cuda_device_hwctx = NULL;
  398. #if CONFIG_D3D11VA
  399. AVD3D11VADeviceContext *d3d11_device_hwctx = NULL;
  400. #endif
  401. int ret;
  402. if (avctx->hw_frames_ctx) {
  403. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  404. if (frames_ctx->format == AV_PIX_FMT_CUDA)
  405. cuda_device_hwctx = frames_ctx->device_ctx->hwctx;
  406. #if CONFIG_D3D11VA
  407. else if (frames_ctx->format == AV_PIX_FMT_D3D11)
  408. d3d11_device_hwctx = frames_ctx->device_ctx->hwctx;
  409. #endif
  410. else
  411. return AVERROR(EINVAL);
  412. } else if (avctx->hw_device_ctx) {
  413. hwdev_ctx = (AVHWDeviceContext*)avctx->hw_device_ctx->data;
  414. if (hwdev_ctx->type == AV_HWDEVICE_TYPE_CUDA)
  415. cuda_device_hwctx = hwdev_ctx->hwctx;
  416. #if CONFIG_D3D11VA
  417. else if (hwdev_ctx->type == AV_HWDEVICE_TYPE_D3D11VA)
  418. d3d11_device_hwctx = hwdev_ctx->hwctx;
  419. #endif
  420. else
  421. return AVERROR(EINVAL);
  422. } else {
  423. return AVERROR(EINVAL);
  424. }
  425. if (cuda_device_hwctx) {
  426. ctx->cu_context = cuda_device_hwctx->cuda_ctx;
  427. }
  428. #if CONFIG_D3D11VA
  429. else if (d3d11_device_hwctx) {
  430. ctx->d3d11_device = d3d11_device_hwctx->device;
  431. ID3D11Device_AddRef(ctx->d3d11_device);
  432. }
  433. #endif
  434. ret = nvenc_open_session(avctx);
  435. if (ret < 0)
  436. return ret;
  437. ret = nvenc_check_capabilities(avctx);
  438. if (ret < 0) {
  439. av_log(avctx, AV_LOG_FATAL, "Provided device doesn't support required NVENC features\n");
  440. return ret;
  441. }
  442. } else {
  443. int i, nb_devices = 0;
  444. if ((dl_fn->cuda_dl->cuInit(0)) != CUDA_SUCCESS) {
  445. av_log(avctx, AV_LOG_ERROR,
  446. "Cannot init CUDA\n");
  447. return AVERROR_UNKNOWN;
  448. }
  449. if ((dl_fn->cuda_dl->cuDeviceGetCount(&nb_devices)) != CUDA_SUCCESS) {
  450. av_log(avctx, AV_LOG_ERROR,
  451. "Cannot enumerate the CUDA devices\n");
  452. return AVERROR_UNKNOWN;
  453. }
  454. if (!nb_devices) {
  455. av_log(avctx, AV_LOG_FATAL, "No CUDA capable devices found\n");
  456. return AVERROR_EXTERNAL;
  457. }
  458. av_log(avctx, AV_LOG_VERBOSE, "%d CUDA capable devices found\n", nb_devices);
  459. dl_fn->nvenc_device_count = 0;
  460. for (i = 0; i < nb_devices; ++i) {
  461. if ((nvenc_check_device(avctx, i)) >= 0 && ctx->device != LIST_DEVICES)
  462. return 0;
  463. }
  464. if (ctx->device == LIST_DEVICES)
  465. return AVERROR_EXIT;
  466. if (!dl_fn->nvenc_device_count) {
  467. av_log(avctx, AV_LOG_FATAL, "No NVENC capable devices found\n");
  468. return AVERROR_EXTERNAL;
  469. }
  470. av_log(avctx, AV_LOG_FATAL, "Requested GPU %d, but only %d GPUs are available!\n", ctx->device, nb_devices);
  471. return AVERROR(EINVAL);
  472. }
  473. return 0;
  474. }
  475. typedef struct GUIDTuple {
  476. const GUID guid;
  477. int flags;
  478. } GUIDTuple;
  479. #define PRESET_ALIAS(alias, name, ...) \
  480. [PRESET_ ## alias] = { NV_ENC_PRESET_ ## name ## _GUID, __VA_ARGS__ }
  481. #define PRESET(name, ...) PRESET_ALIAS(name, name, __VA_ARGS__)
  482. static void nvenc_map_preset(NvencContext *ctx)
  483. {
  484. GUIDTuple presets[] = {
  485. PRESET(DEFAULT),
  486. PRESET(HP),
  487. PRESET(HQ),
  488. PRESET(BD),
  489. PRESET_ALIAS(SLOW, HQ, NVENC_TWO_PASSES),
  490. PRESET_ALIAS(MEDIUM, HQ, NVENC_ONE_PASS),
  491. PRESET_ALIAS(FAST, HP, NVENC_ONE_PASS),
  492. PRESET(LOW_LATENCY_DEFAULT, NVENC_LOWLATENCY),
  493. PRESET(LOW_LATENCY_HP, NVENC_LOWLATENCY),
  494. PRESET(LOW_LATENCY_HQ, NVENC_LOWLATENCY),
  495. PRESET(LOSSLESS_DEFAULT, NVENC_LOSSLESS),
  496. PRESET(LOSSLESS_HP, NVENC_LOSSLESS),
  497. };
  498. GUIDTuple *t = &presets[ctx->preset];
  499. ctx->init_encode_params.presetGUID = t->guid;
  500. ctx->flags = t->flags;
  501. }
  502. #undef PRESET
  503. #undef PRESET_ALIAS
  504. static av_cold void set_constqp(AVCodecContext *avctx)
  505. {
  506. NvencContext *ctx = avctx->priv_data;
  507. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  508. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  509. if (ctx->init_qp_p >= 0) {
  510. rc->constQP.qpInterP = ctx->init_qp_p;
  511. if (ctx->init_qp_i >= 0 && ctx->init_qp_b >= 0) {
  512. rc->constQP.qpIntra = ctx->init_qp_i;
  513. rc->constQP.qpInterB = ctx->init_qp_b;
  514. } else if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  515. rc->constQP.qpIntra = av_clip(
  516. rc->constQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
  517. rc->constQP.qpInterB = av_clip(
  518. rc->constQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
  519. } else {
  520. rc->constQP.qpIntra = rc->constQP.qpInterP;
  521. rc->constQP.qpInterB = rc->constQP.qpInterP;
  522. }
  523. } else if (ctx->cqp >= 0) {
  524. rc->constQP.qpInterP = rc->constQP.qpInterB = rc->constQP.qpIntra = ctx->cqp;
  525. if (avctx->b_quant_factor != 0.0)
  526. rc->constQP.qpInterB = av_clip(ctx->cqp * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
  527. if (avctx->i_quant_factor != 0.0)
  528. rc->constQP.qpIntra = av_clip(ctx->cqp * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
  529. }
  530. avctx->qmin = -1;
  531. avctx->qmax = -1;
  532. }
  533. static av_cold void set_vbr(AVCodecContext *avctx)
  534. {
  535. NvencContext *ctx = avctx->priv_data;
  536. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  537. int qp_inter_p;
  538. if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  539. rc->enableMinQP = 1;
  540. rc->enableMaxQP = 1;
  541. rc->minQP.qpInterB = avctx->qmin;
  542. rc->minQP.qpInterP = avctx->qmin;
  543. rc->minQP.qpIntra = avctx->qmin;
  544. rc->maxQP.qpInterB = avctx->qmax;
  545. rc->maxQP.qpInterP = avctx->qmax;
  546. rc->maxQP.qpIntra = avctx->qmax;
  547. qp_inter_p = (avctx->qmax + 3 * avctx->qmin) / 4; // biased towards Qmin
  548. } else if (avctx->qmin >= 0) {
  549. rc->enableMinQP = 1;
  550. rc->minQP.qpInterB = avctx->qmin;
  551. rc->minQP.qpInterP = avctx->qmin;
  552. rc->minQP.qpIntra = avctx->qmin;
  553. qp_inter_p = avctx->qmin;
  554. } else {
  555. qp_inter_p = 26; // default to 26
  556. }
  557. rc->enableInitialRCQP = 1;
  558. if (ctx->init_qp_p < 0) {
  559. rc->initialRCQP.qpInterP = qp_inter_p;
  560. } else {
  561. rc->initialRCQP.qpInterP = ctx->init_qp_p;
  562. }
  563. if (ctx->init_qp_i < 0) {
  564. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  565. rc->initialRCQP.qpIntra = av_clip(
  566. rc->initialRCQP.qpInterP * fabs(avctx->i_quant_factor) + avctx->i_quant_offset + 0.5, 0, 51);
  567. } else {
  568. rc->initialRCQP.qpIntra = rc->initialRCQP.qpInterP;
  569. }
  570. } else {
  571. rc->initialRCQP.qpIntra = ctx->init_qp_i;
  572. }
  573. if (ctx->init_qp_b < 0) {
  574. if (avctx->i_quant_factor != 0.0 && avctx->b_quant_factor != 0.0) {
  575. rc->initialRCQP.qpInterB = av_clip(
  576. rc->initialRCQP.qpInterP * fabs(avctx->b_quant_factor) + avctx->b_quant_offset + 0.5, 0, 51);
  577. } else {
  578. rc->initialRCQP.qpInterB = rc->initialRCQP.qpInterP;
  579. }
  580. } else {
  581. rc->initialRCQP.qpInterB = ctx->init_qp_b;
  582. }
  583. }
  584. static av_cold void set_lossless(AVCodecContext *avctx)
  585. {
  586. NvencContext *ctx = avctx->priv_data;
  587. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  588. rc->rateControlMode = NV_ENC_PARAMS_RC_CONSTQP;
  589. rc->constQP.qpInterB = 0;
  590. rc->constQP.qpInterP = 0;
  591. rc->constQP.qpIntra = 0;
  592. avctx->qmin = -1;
  593. avctx->qmax = -1;
  594. }
  595. static void nvenc_override_rate_control(AVCodecContext *avctx)
  596. {
  597. NvencContext *ctx = avctx->priv_data;
  598. NV_ENC_RC_PARAMS *rc = &ctx->encode_config.rcParams;
  599. switch (ctx->rc) {
  600. case NV_ENC_PARAMS_RC_CONSTQP:
  601. set_constqp(avctx);
  602. return;
  603. case NV_ENC_PARAMS_RC_VBR_MINQP:
  604. if (avctx->qmin < 0) {
  605. av_log(avctx, AV_LOG_WARNING,
  606. "The variable bitrate rate-control requires "
  607. "the 'qmin' option set.\n");
  608. set_vbr(avctx);
  609. return;
  610. }
  611. /* fall through */
  612. case NV_ENC_PARAMS_RC_VBR_HQ:
  613. case NV_ENC_PARAMS_RC_VBR:
  614. set_vbr(avctx);
  615. break;
  616. case NV_ENC_PARAMS_RC_CBR:
  617. case NV_ENC_PARAMS_RC_CBR_HQ:
  618. case NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ:
  619. break;
  620. }
  621. rc->rateControlMode = ctx->rc;
  622. }
  623. static av_cold int nvenc_recalc_surfaces(AVCodecContext *avctx)
  624. {
  625. NvencContext *ctx = avctx->priv_data;
  626. // default minimum of 4 surfaces
  627. // multiply by 2 for number of NVENCs on gpu (hardcode to 2)
  628. // another multiply by 2 to avoid blocking next PBB group
  629. int nb_surfaces = FFMAX(4, ctx->encode_config.frameIntervalP * 2 * 2);
  630. // lookahead enabled
  631. if (ctx->rc_lookahead > 0) {
  632. // +1 is to account for lkd_bound calculation later
  633. // +4 is to allow sufficient pipelining with lookahead
  634. nb_surfaces = FFMAX(1, FFMAX(nb_surfaces, ctx->rc_lookahead + ctx->encode_config.frameIntervalP + 1 + 4));
  635. if (nb_surfaces > ctx->nb_surfaces && ctx->nb_surfaces > 0)
  636. {
  637. av_log(avctx, AV_LOG_WARNING,
  638. "Defined rc_lookahead requires more surfaces, "
  639. "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
  640. }
  641. ctx->nb_surfaces = FFMAX(nb_surfaces, ctx->nb_surfaces);
  642. } else {
  643. if (ctx->encode_config.frameIntervalP > 1 && ctx->nb_surfaces < nb_surfaces && ctx->nb_surfaces > 0)
  644. {
  645. av_log(avctx, AV_LOG_WARNING,
  646. "Defined b-frame requires more surfaces, "
  647. "increasing used surfaces %d -> %d\n", ctx->nb_surfaces, nb_surfaces);
  648. ctx->nb_surfaces = FFMAX(ctx->nb_surfaces, nb_surfaces);
  649. }
  650. else if (ctx->nb_surfaces <= 0)
  651. ctx->nb_surfaces = nb_surfaces;
  652. // otherwise use user specified value
  653. }
  654. ctx->nb_surfaces = FFMAX(1, FFMIN(MAX_REGISTERED_FRAMES, ctx->nb_surfaces));
  655. ctx->async_depth = FFMIN(ctx->async_depth, ctx->nb_surfaces - 1);
  656. return 0;
  657. }
  658. static av_cold void nvenc_setup_rate_control(AVCodecContext *avctx)
  659. {
  660. NvencContext *ctx = avctx->priv_data;
  661. if (avctx->global_quality > 0)
  662. av_log(avctx, AV_LOG_WARNING, "Using global_quality with nvenc is deprecated. Use qp instead.\n");
  663. if (ctx->cqp < 0 && avctx->global_quality > 0)
  664. ctx->cqp = avctx->global_quality;
  665. if (avctx->bit_rate > 0) {
  666. ctx->encode_config.rcParams.averageBitRate = avctx->bit_rate;
  667. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  668. ctx->encode_config.rcParams.maxBitRate = ctx->encode_config.rcParams.averageBitRate;
  669. }
  670. if (avctx->rc_max_rate > 0)
  671. ctx->encode_config.rcParams.maxBitRate = avctx->rc_max_rate;
  672. if (ctx->rc < 0) {
  673. if (ctx->flags & NVENC_ONE_PASS)
  674. ctx->twopass = 0;
  675. if (ctx->flags & NVENC_TWO_PASSES)
  676. ctx->twopass = 1;
  677. if (ctx->twopass < 0)
  678. ctx->twopass = (ctx->flags & NVENC_LOWLATENCY) != 0;
  679. if (ctx->cbr) {
  680. if (ctx->twopass) {
  681. ctx->rc = NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ;
  682. } else {
  683. ctx->rc = NV_ENC_PARAMS_RC_CBR;
  684. }
  685. } else if (ctx->cqp >= 0) {
  686. ctx->rc = NV_ENC_PARAMS_RC_CONSTQP;
  687. } else if (ctx->twopass) {
  688. ctx->rc = NV_ENC_PARAMS_RC_VBR_HQ;
  689. } else if (avctx->qmin >= 0 && avctx->qmax >= 0) {
  690. ctx->rc = NV_ENC_PARAMS_RC_VBR_MINQP;
  691. }
  692. }
  693. if (ctx->rc >= 0 && ctx->rc & RC_MODE_DEPRECATED) {
  694. av_log(avctx, AV_LOG_WARNING, "Specified rc mode is deprecated.\n");
  695. av_log(avctx, AV_LOG_WARNING, "\tll_2pass_quality -> cbr_ld_hq\n");
  696. av_log(avctx, AV_LOG_WARNING, "\tll_2pass_size -> cbr_hq\n");
  697. av_log(avctx, AV_LOG_WARNING, "\tvbr_2pass -> vbr_hq\n");
  698. av_log(avctx, AV_LOG_WARNING, "\tvbr_minqp -> (no replacement)\n");
  699. ctx->rc &= ~RC_MODE_DEPRECATED;
  700. }
  701. if (ctx->flags & NVENC_LOSSLESS) {
  702. set_lossless(avctx);
  703. } else if (ctx->rc >= 0) {
  704. nvenc_override_rate_control(avctx);
  705. } else {
  706. ctx->encode_config.rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR;
  707. set_vbr(avctx);
  708. }
  709. if (avctx->rc_buffer_size > 0) {
  710. ctx->encode_config.rcParams.vbvBufferSize = avctx->rc_buffer_size;
  711. } else if (ctx->encode_config.rcParams.averageBitRate > 0) {
  712. ctx->encode_config.rcParams.vbvBufferSize = 2 * ctx->encode_config.rcParams.averageBitRate;
  713. }
  714. if (ctx->aq) {
  715. ctx->encode_config.rcParams.enableAQ = 1;
  716. ctx->encode_config.rcParams.aqStrength = ctx->aq_strength;
  717. av_log(avctx, AV_LOG_VERBOSE, "AQ enabled.\n");
  718. }
  719. if (ctx->temporal_aq) {
  720. ctx->encode_config.rcParams.enableTemporalAQ = 1;
  721. av_log(avctx, AV_LOG_VERBOSE, "Temporal AQ enabled.\n");
  722. }
  723. if (ctx->rc_lookahead > 0) {
  724. int lkd_bound = FFMIN(ctx->nb_surfaces, ctx->async_depth) -
  725. ctx->encode_config.frameIntervalP - 4;
  726. if (lkd_bound < 0) {
  727. av_log(avctx, AV_LOG_WARNING,
  728. "Lookahead not enabled. Increase buffer delay (-delay).\n");
  729. } else {
  730. ctx->encode_config.rcParams.enableLookahead = 1;
  731. ctx->encode_config.rcParams.lookaheadDepth = av_clip(ctx->rc_lookahead, 0, lkd_bound);
  732. ctx->encode_config.rcParams.disableIadapt = ctx->no_scenecut;
  733. ctx->encode_config.rcParams.disableBadapt = !ctx->b_adapt;
  734. av_log(avctx, AV_LOG_VERBOSE,
  735. "Lookahead enabled: depth %d, scenecut %s, B-adapt %s.\n",
  736. ctx->encode_config.rcParams.lookaheadDepth,
  737. ctx->encode_config.rcParams.disableIadapt ? "disabled" : "enabled",
  738. ctx->encode_config.rcParams.disableBadapt ? "disabled" : "enabled");
  739. }
  740. }
  741. if (ctx->strict_gop) {
  742. ctx->encode_config.rcParams.strictGOPTarget = 1;
  743. av_log(avctx, AV_LOG_VERBOSE, "Strict GOP target enabled.\n");
  744. }
  745. if (ctx->nonref_p)
  746. ctx->encode_config.rcParams.enableNonRefP = 1;
  747. if (ctx->zerolatency)
  748. ctx->encode_config.rcParams.zeroReorderDelay = 1;
  749. if (ctx->quality)
  750. {
  751. //convert from float to fixed point 8.8
  752. int tmp_quality = (int)(ctx->quality * 256.0f);
  753. ctx->encode_config.rcParams.targetQuality = (uint8_t)(tmp_quality >> 8);
  754. ctx->encode_config.rcParams.targetQualityLSB = (uint8_t)(tmp_quality & 0xff);
  755. }
  756. }
  757. static av_cold int nvenc_setup_h264_config(AVCodecContext *avctx)
  758. {
  759. NvencContext *ctx = avctx->priv_data;
  760. NV_ENC_CONFIG *cc = &ctx->encode_config;
  761. NV_ENC_CONFIG_H264 *h264 = &cc->encodeCodecConfig.h264Config;
  762. NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui = &h264->h264VUIParameters;
  763. vui->colourMatrix = avctx->colorspace;
  764. vui->colourPrimaries = avctx->color_primaries;
  765. vui->transferCharacteristics = avctx->color_trc;
  766. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  767. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  768. vui->colourDescriptionPresentFlag =
  769. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  770. vui->videoSignalTypePresentFlag =
  771. (vui->colourDescriptionPresentFlag
  772. || vui->videoFormat != 5
  773. || vui->videoFullRangeFlag != 0);
  774. h264->sliceMode = 3;
  775. h264->sliceModeData = 1;
  776. h264->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  777. h264->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  778. h264->outputAUD = ctx->aud;
  779. if (avctx->refs >= 0) {
  780. /* 0 means "let the hardware decide" */
  781. h264->maxNumRefFrames = avctx->refs;
  782. }
  783. if (avctx->gop_size >= 0) {
  784. h264->idrPeriod = cc->gopLength;
  785. }
  786. if (IS_CBR(cc->rcParams.rateControlMode)) {
  787. h264->outputBufferingPeriodSEI = 1;
  788. }
  789. h264->outputPictureTimingSEI = 1;
  790. if (cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_LOWDELAY_HQ ||
  791. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR_HQ ||
  792. cc->rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR_HQ) {
  793. h264->adaptiveTransformMode = NV_ENC_H264_ADAPTIVE_TRANSFORM_ENABLE;
  794. h264->fmoMode = NV_ENC_H264_FMO_DISABLE;
  795. }
  796. if (ctx->flags & NVENC_LOSSLESS) {
  797. h264->qpPrimeYZeroTransformBypassFlag = 1;
  798. } else {
  799. switch(ctx->profile) {
  800. case NV_ENC_H264_PROFILE_BASELINE:
  801. cc->profileGUID = NV_ENC_H264_PROFILE_BASELINE_GUID;
  802. avctx->profile = FF_PROFILE_H264_BASELINE;
  803. break;
  804. case NV_ENC_H264_PROFILE_MAIN:
  805. cc->profileGUID = NV_ENC_H264_PROFILE_MAIN_GUID;
  806. avctx->profile = FF_PROFILE_H264_MAIN;
  807. break;
  808. case NV_ENC_H264_PROFILE_HIGH:
  809. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_GUID;
  810. avctx->profile = FF_PROFILE_H264_HIGH;
  811. break;
  812. case NV_ENC_H264_PROFILE_HIGH_444P:
  813. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  814. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  815. break;
  816. }
  817. }
  818. // force setting profile as high444p if input is AV_PIX_FMT_YUV444P
  819. if (ctx->data_pix_fmt == AV_PIX_FMT_YUV444P) {
  820. cc->profileGUID = NV_ENC_H264_PROFILE_HIGH_444_GUID;
  821. avctx->profile = FF_PROFILE_H264_HIGH_444_PREDICTIVE;
  822. }
  823. h264->chromaFormatIDC = avctx->profile == FF_PROFILE_H264_HIGH_444_PREDICTIVE ? 3 : 1;
  824. h264->level = ctx->level;
  825. if (ctx->coder >= 0)
  826. h264->entropyCodingMode = ctx->coder;
  827. return 0;
  828. }
  829. static av_cold int nvenc_setup_hevc_config(AVCodecContext *avctx)
  830. {
  831. NvencContext *ctx = avctx->priv_data;
  832. NV_ENC_CONFIG *cc = &ctx->encode_config;
  833. NV_ENC_CONFIG_HEVC *hevc = &cc->encodeCodecConfig.hevcConfig;
  834. NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui = &hevc->hevcVUIParameters;
  835. vui->colourMatrix = avctx->colorspace;
  836. vui->colourPrimaries = avctx->color_primaries;
  837. vui->transferCharacteristics = avctx->color_trc;
  838. vui->videoFullRangeFlag = (avctx->color_range == AVCOL_RANGE_JPEG
  839. || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ420P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ422P || ctx->data_pix_fmt == AV_PIX_FMT_YUVJ444P);
  840. vui->colourDescriptionPresentFlag =
  841. (avctx->colorspace != 2 || avctx->color_primaries != 2 || avctx->color_trc != 2);
  842. vui->videoSignalTypePresentFlag =
  843. (vui->colourDescriptionPresentFlag
  844. || vui->videoFormat != 5
  845. || vui->videoFullRangeFlag != 0);
  846. hevc->sliceMode = 3;
  847. hevc->sliceModeData = 1;
  848. hevc->disableSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 1 : 0;
  849. hevc->repeatSPSPPS = (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) ? 0 : 1;
  850. hevc->outputAUD = ctx->aud;
  851. if (avctx->refs >= 0) {
  852. /* 0 means "let the hardware decide" */
  853. hevc->maxNumRefFramesInDPB = avctx->refs;
  854. }
  855. if (avctx->gop_size >= 0) {
  856. hevc->idrPeriod = cc->gopLength;
  857. }
  858. if (IS_CBR(cc->rcParams.rateControlMode)) {
  859. hevc->outputBufferingPeriodSEI = 1;
  860. }
  861. hevc->outputPictureTimingSEI = 1;
  862. switch (ctx->profile) {
  863. case NV_ENC_HEVC_PROFILE_MAIN:
  864. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN_GUID;
  865. avctx->profile = FF_PROFILE_HEVC_MAIN;
  866. break;
  867. case NV_ENC_HEVC_PROFILE_MAIN_10:
  868. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  869. avctx->profile = FF_PROFILE_HEVC_MAIN_10;
  870. break;
  871. case NV_ENC_HEVC_PROFILE_REXT:
  872. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  873. avctx->profile = FF_PROFILE_HEVC_REXT;
  874. break;
  875. }
  876. // force setting profile as main10 if input is 10 bit
  877. if (IS_10BIT(ctx->data_pix_fmt)) {
  878. cc->profileGUID = NV_ENC_HEVC_PROFILE_MAIN10_GUID;
  879. avctx->profile = FF_PROFILE_HEVC_MAIN_10;
  880. }
  881. // force setting profile as rext if input is yuv444
  882. if (IS_YUV444(ctx->data_pix_fmt)) {
  883. cc->profileGUID = NV_ENC_HEVC_PROFILE_FREXT_GUID;
  884. avctx->profile = FF_PROFILE_HEVC_REXT;
  885. }
  886. hevc->chromaFormatIDC = IS_YUV444(ctx->data_pix_fmt) ? 3 : 1;
  887. hevc->pixelBitDepthMinus8 = IS_10BIT(ctx->data_pix_fmt) ? 2 : 0;
  888. hevc->level = ctx->level;
  889. hevc->tier = ctx->tier;
  890. return 0;
  891. }
  892. static av_cold int nvenc_setup_codec_config(AVCodecContext *avctx)
  893. {
  894. switch (avctx->codec->id) {
  895. case AV_CODEC_ID_H264:
  896. return nvenc_setup_h264_config(avctx);
  897. case AV_CODEC_ID_HEVC:
  898. return nvenc_setup_hevc_config(avctx);
  899. /* Earlier switch/case will return if unknown codec is passed. */
  900. }
  901. return 0;
  902. }
  903. static av_cold int nvenc_setup_encoder(AVCodecContext *avctx)
  904. {
  905. NvencContext *ctx = avctx->priv_data;
  906. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  907. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  908. NV_ENC_PRESET_CONFIG preset_config = { 0 };
  909. NVENCSTATUS nv_status = NV_ENC_SUCCESS;
  910. AVCPBProperties *cpb_props;
  911. int res = 0;
  912. int dw, dh;
  913. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  914. ctx->init_encode_params.version = NV_ENC_INITIALIZE_PARAMS_VER;
  915. ctx->init_encode_params.encodeHeight = avctx->height;
  916. ctx->init_encode_params.encodeWidth = avctx->width;
  917. ctx->init_encode_params.encodeConfig = &ctx->encode_config;
  918. nvenc_map_preset(ctx);
  919. preset_config.version = NV_ENC_PRESET_CONFIG_VER;
  920. preset_config.presetCfg.version = NV_ENC_CONFIG_VER;
  921. nv_status = p_nvenc->nvEncGetEncodePresetConfig(ctx->nvencoder,
  922. ctx->init_encode_params.encodeGUID,
  923. ctx->init_encode_params.presetGUID,
  924. &preset_config);
  925. if (nv_status != NV_ENC_SUCCESS)
  926. return nvenc_print_error(avctx, nv_status, "Cannot get the preset configuration");
  927. memcpy(&ctx->encode_config, &preset_config.presetCfg, sizeof(ctx->encode_config));
  928. ctx->encode_config.version = NV_ENC_CONFIG_VER;
  929. dw = avctx->width;
  930. dh = avctx->height;
  931. if (avctx->sample_aspect_ratio.num > 0 && avctx->sample_aspect_ratio.den > 0) {
  932. dw*= avctx->sample_aspect_ratio.num;
  933. dh*= avctx->sample_aspect_ratio.den;
  934. }
  935. av_reduce(&dw, &dh, dw, dh, 1024 * 1024);
  936. ctx->init_encode_params.darHeight = dh;
  937. ctx->init_encode_params.darWidth = dw;
  938. ctx->init_encode_params.frameRateNum = avctx->time_base.den;
  939. ctx->init_encode_params.frameRateDen = avctx->time_base.num * avctx->ticks_per_frame;
  940. ctx->init_encode_params.enableEncodeAsync = 0;
  941. ctx->init_encode_params.enablePTD = 1;
  942. if (ctx->weighted_pred == 1)
  943. ctx->init_encode_params.enableWeightedPrediction = 1;
  944. if (ctx->bluray_compat) {
  945. ctx->aud = 1;
  946. avctx->refs = FFMIN(FFMAX(avctx->refs, 0), 6);
  947. avctx->max_b_frames = FFMIN(avctx->max_b_frames, 3);
  948. switch (avctx->codec->id) {
  949. case AV_CODEC_ID_H264:
  950. /* maximum level depends on used resolution */
  951. break;
  952. case AV_CODEC_ID_HEVC:
  953. ctx->level = NV_ENC_LEVEL_HEVC_51;
  954. ctx->tier = NV_ENC_TIER_HEVC_HIGH;
  955. break;
  956. }
  957. }
  958. if (avctx->gop_size > 0) {
  959. if (avctx->max_b_frames >= 0) {
  960. /* 0 is intra-only, 1 is I/P only, 2 is one B-Frame, 3 two B-frames, and so on. */
  961. ctx->encode_config.frameIntervalP = avctx->max_b_frames + 1;
  962. }
  963. ctx->encode_config.gopLength = avctx->gop_size;
  964. } else if (avctx->gop_size == 0) {
  965. ctx->encode_config.frameIntervalP = 0;
  966. ctx->encode_config.gopLength = 1;
  967. }
  968. ctx->initial_pts[0] = AV_NOPTS_VALUE;
  969. ctx->initial_pts[1] = AV_NOPTS_VALUE;
  970. nvenc_recalc_surfaces(avctx);
  971. nvenc_setup_rate_control(avctx);
  972. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  973. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FIELD;
  974. } else {
  975. ctx->encode_config.frameFieldMode = NV_ENC_PARAMS_FRAME_FIELD_MODE_FRAME;
  976. }
  977. res = nvenc_setup_codec_config(avctx);
  978. if (res)
  979. return res;
  980. res = nvenc_push_context(avctx);
  981. if (res < 0)
  982. return res;
  983. nv_status = p_nvenc->nvEncInitializeEncoder(ctx->nvencoder, &ctx->init_encode_params);
  984. res = nvenc_pop_context(avctx);
  985. if (res < 0)
  986. return res;
  987. if (nv_status != NV_ENC_SUCCESS) {
  988. return nvenc_print_error(avctx, nv_status, "InitializeEncoder failed");
  989. }
  990. if (ctx->encode_config.frameIntervalP > 1)
  991. avctx->has_b_frames = 2;
  992. if (ctx->encode_config.rcParams.averageBitRate > 0)
  993. avctx->bit_rate = ctx->encode_config.rcParams.averageBitRate;
  994. cpb_props = ff_add_cpb_side_data(avctx);
  995. if (!cpb_props)
  996. return AVERROR(ENOMEM);
  997. cpb_props->max_bitrate = ctx->encode_config.rcParams.maxBitRate;
  998. cpb_props->avg_bitrate = avctx->bit_rate;
  999. cpb_props->buffer_size = ctx->encode_config.rcParams.vbvBufferSize;
  1000. return 0;
  1001. }
  1002. static NV_ENC_BUFFER_FORMAT nvenc_map_buffer_format(enum AVPixelFormat pix_fmt)
  1003. {
  1004. switch (pix_fmt) {
  1005. case AV_PIX_FMT_YUV420P:
  1006. return NV_ENC_BUFFER_FORMAT_YV12_PL;
  1007. case AV_PIX_FMT_NV12:
  1008. return NV_ENC_BUFFER_FORMAT_NV12_PL;
  1009. case AV_PIX_FMT_P010:
  1010. case AV_PIX_FMT_P016:
  1011. return NV_ENC_BUFFER_FORMAT_YUV420_10BIT;
  1012. case AV_PIX_FMT_YUV444P:
  1013. return NV_ENC_BUFFER_FORMAT_YUV444_PL;
  1014. case AV_PIX_FMT_YUV444P16:
  1015. return NV_ENC_BUFFER_FORMAT_YUV444_10BIT;
  1016. case AV_PIX_FMT_0RGB32:
  1017. return NV_ENC_BUFFER_FORMAT_ARGB;
  1018. case AV_PIX_FMT_0BGR32:
  1019. return NV_ENC_BUFFER_FORMAT_ABGR;
  1020. default:
  1021. return NV_ENC_BUFFER_FORMAT_UNDEFINED;
  1022. }
  1023. }
  1024. static av_cold int nvenc_alloc_surface(AVCodecContext *avctx, int idx)
  1025. {
  1026. NvencContext *ctx = avctx->priv_data;
  1027. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1028. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1029. NvencSurface* tmp_surface = &ctx->surfaces[idx];
  1030. NVENCSTATUS nv_status;
  1031. NV_ENC_CREATE_BITSTREAM_BUFFER allocOut = { 0 };
  1032. allocOut.version = NV_ENC_CREATE_BITSTREAM_BUFFER_VER;
  1033. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1034. ctx->surfaces[idx].in_ref = av_frame_alloc();
  1035. if (!ctx->surfaces[idx].in_ref)
  1036. return AVERROR(ENOMEM);
  1037. } else {
  1038. NV_ENC_CREATE_INPUT_BUFFER allocSurf = { 0 };
  1039. ctx->surfaces[idx].format = nvenc_map_buffer_format(ctx->data_pix_fmt);
  1040. if (ctx->surfaces[idx].format == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
  1041. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
  1042. av_get_pix_fmt_name(ctx->data_pix_fmt));
  1043. return AVERROR(EINVAL);
  1044. }
  1045. allocSurf.version = NV_ENC_CREATE_INPUT_BUFFER_VER;
  1046. allocSurf.width = avctx->width;
  1047. allocSurf.height = avctx->height;
  1048. allocSurf.bufferFmt = ctx->surfaces[idx].format;
  1049. nv_status = p_nvenc->nvEncCreateInputBuffer(ctx->nvencoder, &allocSurf);
  1050. if (nv_status != NV_ENC_SUCCESS) {
  1051. return nvenc_print_error(avctx, nv_status, "CreateInputBuffer failed");
  1052. }
  1053. ctx->surfaces[idx].input_surface = allocSurf.inputBuffer;
  1054. ctx->surfaces[idx].width = allocSurf.width;
  1055. ctx->surfaces[idx].height = allocSurf.height;
  1056. }
  1057. nv_status = p_nvenc->nvEncCreateBitstreamBuffer(ctx->nvencoder, &allocOut);
  1058. if (nv_status != NV_ENC_SUCCESS) {
  1059. int err = nvenc_print_error(avctx, nv_status, "CreateBitstreamBuffer failed");
  1060. if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
  1061. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[idx].input_surface);
  1062. av_frame_free(&ctx->surfaces[idx].in_ref);
  1063. return err;
  1064. }
  1065. ctx->surfaces[idx].output_surface = allocOut.bitstreamBuffer;
  1066. ctx->surfaces[idx].size = allocOut.size;
  1067. av_fifo_generic_write(ctx->unused_surface_queue, &tmp_surface, sizeof(tmp_surface), NULL);
  1068. return 0;
  1069. }
  1070. static av_cold int nvenc_setup_surfaces(AVCodecContext *avctx)
  1071. {
  1072. NvencContext *ctx = avctx->priv_data;
  1073. int i, res = 0, res2;
  1074. ctx->surfaces = av_mallocz_array(ctx->nb_surfaces, sizeof(*ctx->surfaces));
  1075. if (!ctx->surfaces)
  1076. return AVERROR(ENOMEM);
  1077. ctx->timestamp_list = av_fifo_alloc(ctx->nb_surfaces * sizeof(int64_t));
  1078. if (!ctx->timestamp_list)
  1079. return AVERROR(ENOMEM);
  1080. ctx->unused_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
  1081. if (!ctx->unused_surface_queue)
  1082. return AVERROR(ENOMEM);
  1083. ctx->output_surface_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
  1084. if (!ctx->output_surface_queue)
  1085. return AVERROR(ENOMEM);
  1086. ctx->output_surface_ready_queue = av_fifo_alloc(ctx->nb_surfaces * sizeof(NvencSurface*));
  1087. if (!ctx->output_surface_ready_queue)
  1088. return AVERROR(ENOMEM);
  1089. res = nvenc_push_context(avctx);
  1090. if (res < 0)
  1091. return res;
  1092. for (i = 0; i < ctx->nb_surfaces; i++) {
  1093. if ((res = nvenc_alloc_surface(avctx, i)) < 0)
  1094. goto fail;
  1095. }
  1096. fail:
  1097. res2 = nvenc_pop_context(avctx);
  1098. if (res2 < 0)
  1099. return res2;
  1100. return res;
  1101. }
  1102. static av_cold int nvenc_setup_extradata(AVCodecContext *avctx)
  1103. {
  1104. NvencContext *ctx = avctx->priv_data;
  1105. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1106. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1107. NVENCSTATUS nv_status;
  1108. uint32_t outSize = 0;
  1109. char tmpHeader[256];
  1110. NV_ENC_SEQUENCE_PARAM_PAYLOAD payload = { 0 };
  1111. payload.version = NV_ENC_SEQUENCE_PARAM_PAYLOAD_VER;
  1112. payload.spsppsBuffer = tmpHeader;
  1113. payload.inBufferSize = sizeof(tmpHeader);
  1114. payload.outSPSPPSPayloadSize = &outSize;
  1115. nv_status = p_nvenc->nvEncGetSequenceParams(ctx->nvencoder, &payload);
  1116. if (nv_status != NV_ENC_SUCCESS) {
  1117. return nvenc_print_error(avctx, nv_status, "GetSequenceParams failed");
  1118. }
  1119. avctx->extradata_size = outSize;
  1120. avctx->extradata = av_mallocz(outSize + AV_INPUT_BUFFER_PADDING_SIZE);
  1121. if (!avctx->extradata) {
  1122. return AVERROR(ENOMEM);
  1123. }
  1124. memcpy(avctx->extradata, tmpHeader, outSize);
  1125. return 0;
  1126. }
  1127. av_cold int ff_nvenc_encode_close(AVCodecContext *avctx)
  1128. {
  1129. NvencContext *ctx = avctx->priv_data;
  1130. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1131. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1132. int i, res;
  1133. /* the encoder has to be flushed before it can be closed */
  1134. if (ctx->nvencoder) {
  1135. NV_ENC_PIC_PARAMS params = { .version = NV_ENC_PIC_PARAMS_VER,
  1136. .encodePicFlags = NV_ENC_PIC_FLAG_EOS };
  1137. res = nvenc_push_context(avctx);
  1138. if (res < 0)
  1139. return res;
  1140. p_nvenc->nvEncEncodePicture(ctx->nvencoder, &params);
  1141. }
  1142. av_fifo_freep(&ctx->timestamp_list);
  1143. av_fifo_freep(&ctx->output_surface_ready_queue);
  1144. av_fifo_freep(&ctx->output_surface_queue);
  1145. av_fifo_freep(&ctx->unused_surface_queue);
  1146. if (ctx->surfaces && (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11)) {
  1147. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1148. if (ctx->registered_frames[i].mapped)
  1149. p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[i].in_map.mappedResource);
  1150. if (ctx->registered_frames[i].regptr)
  1151. p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  1152. }
  1153. ctx->nb_registered_frames = 0;
  1154. }
  1155. if (ctx->surfaces) {
  1156. for (i = 0; i < ctx->nb_surfaces; ++i) {
  1157. if (avctx->pix_fmt != AV_PIX_FMT_CUDA && avctx->pix_fmt != AV_PIX_FMT_D3D11)
  1158. p_nvenc->nvEncDestroyInputBuffer(ctx->nvencoder, ctx->surfaces[i].input_surface);
  1159. av_frame_free(&ctx->surfaces[i].in_ref);
  1160. p_nvenc->nvEncDestroyBitstreamBuffer(ctx->nvencoder, ctx->surfaces[i].output_surface);
  1161. }
  1162. }
  1163. av_freep(&ctx->surfaces);
  1164. ctx->nb_surfaces = 0;
  1165. if (ctx->nvencoder) {
  1166. p_nvenc->nvEncDestroyEncoder(ctx->nvencoder);
  1167. res = nvenc_pop_context(avctx);
  1168. if (res < 0)
  1169. return res;
  1170. }
  1171. ctx->nvencoder = NULL;
  1172. if (ctx->cu_context_internal)
  1173. dl_fn->cuda_dl->cuCtxDestroy(ctx->cu_context_internal);
  1174. ctx->cu_context = ctx->cu_context_internal = NULL;
  1175. #if CONFIG_D3D11VA
  1176. if (ctx->d3d11_device) {
  1177. ID3D11Device_Release(ctx->d3d11_device);
  1178. ctx->d3d11_device = NULL;
  1179. }
  1180. #endif
  1181. nvenc_free_functions(&dl_fn->nvenc_dl);
  1182. cuda_free_functions(&dl_fn->cuda_dl);
  1183. dl_fn->nvenc_device_count = 0;
  1184. av_log(avctx, AV_LOG_VERBOSE, "Nvenc unloaded\n");
  1185. return 0;
  1186. }
  1187. av_cold int ff_nvenc_encode_init(AVCodecContext *avctx)
  1188. {
  1189. NvencContext *ctx = avctx->priv_data;
  1190. int ret;
  1191. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1192. AVHWFramesContext *frames_ctx;
  1193. if (!avctx->hw_frames_ctx) {
  1194. av_log(avctx, AV_LOG_ERROR,
  1195. "hw_frames_ctx must be set when using GPU frames as input\n");
  1196. return AVERROR(EINVAL);
  1197. }
  1198. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  1199. if (frames_ctx->format != avctx->pix_fmt) {
  1200. av_log(avctx, AV_LOG_ERROR,
  1201. "hw_frames_ctx must match the GPU frame type\n");
  1202. return AVERROR(EINVAL);
  1203. }
  1204. ctx->data_pix_fmt = frames_ctx->sw_format;
  1205. } else {
  1206. ctx->data_pix_fmt = avctx->pix_fmt;
  1207. }
  1208. if ((ret = nvenc_load_libraries(avctx)) < 0)
  1209. return ret;
  1210. if ((ret = nvenc_setup_device(avctx)) < 0)
  1211. return ret;
  1212. if ((ret = nvenc_setup_encoder(avctx)) < 0)
  1213. return ret;
  1214. if ((ret = nvenc_setup_surfaces(avctx)) < 0)
  1215. return ret;
  1216. if (avctx->flags & AV_CODEC_FLAG_GLOBAL_HEADER) {
  1217. if ((ret = nvenc_setup_extradata(avctx)) < 0)
  1218. return ret;
  1219. }
  1220. return 0;
  1221. }
  1222. static NvencSurface *get_free_frame(NvencContext *ctx)
  1223. {
  1224. NvencSurface *tmp_surf;
  1225. if (!(av_fifo_size(ctx->unused_surface_queue) > 0))
  1226. // queue empty
  1227. return NULL;
  1228. av_fifo_generic_read(ctx->unused_surface_queue, &tmp_surf, sizeof(tmp_surf), NULL);
  1229. return tmp_surf;
  1230. }
  1231. static int nvenc_copy_frame(AVCodecContext *avctx, NvencSurface *nv_surface,
  1232. NV_ENC_LOCK_INPUT_BUFFER *lock_buffer_params, const AVFrame *frame)
  1233. {
  1234. int dst_linesize[4] = {
  1235. lock_buffer_params->pitch,
  1236. lock_buffer_params->pitch,
  1237. lock_buffer_params->pitch,
  1238. lock_buffer_params->pitch
  1239. };
  1240. uint8_t *dst_data[4];
  1241. int ret;
  1242. if (frame->format == AV_PIX_FMT_YUV420P)
  1243. dst_linesize[1] = dst_linesize[2] >>= 1;
  1244. ret = av_image_fill_pointers(dst_data, frame->format, nv_surface->height,
  1245. lock_buffer_params->bufferDataPtr, dst_linesize);
  1246. if (ret < 0)
  1247. return ret;
  1248. if (frame->format == AV_PIX_FMT_YUV420P)
  1249. FFSWAP(uint8_t*, dst_data[1], dst_data[2]);
  1250. av_image_copy(dst_data, dst_linesize,
  1251. (const uint8_t**)frame->data, frame->linesize, frame->format,
  1252. avctx->width, avctx->height);
  1253. return 0;
  1254. }
  1255. static int nvenc_find_free_reg_resource(AVCodecContext *avctx)
  1256. {
  1257. NvencContext *ctx = avctx->priv_data;
  1258. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1259. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1260. NVENCSTATUS nv_status;
  1261. int i;
  1262. if (ctx->nb_registered_frames == FF_ARRAY_ELEMS(ctx->registered_frames)) {
  1263. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1264. if (!ctx->registered_frames[i].mapped) {
  1265. if (ctx->registered_frames[i].regptr) {
  1266. nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[i].regptr);
  1267. if (nv_status != NV_ENC_SUCCESS)
  1268. return nvenc_print_error(avctx, nv_status, "Failed unregistering unused input resource");
  1269. ctx->registered_frames[i].ptr = NULL;
  1270. ctx->registered_frames[i].regptr = NULL;
  1271. }
  1272. return i;
  1273. }
  1274. }
  1275. } else {
  1276. return ctx->nb_registered_frames++;
  1277. }
  1278. av_log(avctx, AV_LOG_ERROR, "Too many registered CUDA frames\n");
  1279. return AVERROR(ENOMEM);
  1280. }
  1281. static int nvenc_register_frame(AVCodecContext *avctx, const AVFrame *frame)
  1282. {
  1283. NvencContext *ctx = avctx->priv_data;
  1284. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1285. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1286. AVHWFramesContext *frames_ctx = (AVHWFramesContext*)frame->hw_frames_ctx->data;
  1287. NV_ENC_REGISTER_RESOURCE reg;
  1288. int i, idx, ret;
  1289. for (i = 0; i < ctx->nb_registered_frames; i++) {
  1290. if (avctx->pix_fmt == AV_PIX_FMT_CUDA && ctx->registered_frames[i].ptr == frame->data[0])
  1291. return i;
  1292. else if (avctx->pix_fmt == AV_PIX_FMT_D3D11 && ctx->registered_frames[i].ptr == frame->data[0] && ctx->registered_frames[i].ptr_index == (intptr_t)frame->data[1])
  1293. return i;
  1294. }
  1295. idx = nvenc_find_free_reg_resource(avctx);
  1296. if (idx < 0)
  1297. return idx;
  1298. reg.version = NV_ENC_REGISTER_RESOURCE_VER;
  1299. reg.width = frames_ctx->width;
  1300. reg.height = frames_ctx->height;
  1301. reg.pitch = frame->linesize[0];
  1302. reg.resourceToRegister = frame->data[0];
  1303. if (avctx->pix_fmt == AV_PIX_FMT_CUDA) {
  1304. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_CUDADEVICEPTR;
  1305. }
  1306. else if (avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1307. reg.resourceType = NV_ENC_INPUT_RESOURCE_TYPE_DIRECTX;
  1308. reg.subResourceIndex = (intptr_t)frame->data[1];
  1309. }
  1310. reg.bufferFormat = nvenc_map_buffer_format(frames_ctx->sw_format);
  1311. if (reg.bufferFormat == NV_ENC_BUFFER_FORMAT_UNDEFINED) {
  1312. av_log(avctx, AV_LOG_FATAL, "Invalid input pixel format: %s\n",
  1313. av_get_pix_fmt_name(frames_ctx->sw_format));
  1314. return AVERROR(EINVAL);
  1315. }
  1316. ret = p_nvenc->nvEncRegisterResource(ctx->nvencoder, &reg);
  1317. if (ret != NV_ENC_SUCCESS) {
  1318. nvenc_print_error(avctx, ret, "Error registering an input resource");
  1319. return AVERROR_UNKNOWN;
  1320. }
  1321. ctx->registered_frames[idx].ptr = frame->data[0];
  1322. ctx->registered_frames[idx].ptr_index = reg.subResourceIndex;
  1323. ctx->registered_frames[idx].regptr = reg.registeredResource;
  1324. return idx;
  1325. }
  1326. static int nvenc_upload_frame(AVCodecContext *avctx, const AVFrame *frame,
  1327. NvencSurface *nvenc_frame)
  1328. {
  1329. NvencContext *ctx = avctx->priv_data;
  1330. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1331. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1332. int res;
  1333. NVENCSTATUS nv_status;
  1334. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1335. int reg_idx = nvenc_register_frame(avctx, frame);
  1336. if (reg_idx < 0) {
  1337. av_log(avctx, AV_LOG_ERROR, "Could not register an input HW frame\n");
  1338. return reg_idx;
  1339. }
  1340. res = av_frame_ref(nvenc_frame->in_ref, frame);
  1341. if (res < 0)
  1342. return res;
  1343. if (!ctx->registered_frames[reg_idx].mapped) {
  1344. ctx->registered_frames[reg_idx].in_map.version = NV_ENC_MAP_INPUT_RESOURCE_VER;
  1345. ctx->registered_frames[reg_idx].in_map.registeredResource = ctx->registered_frames[reg_idx].regptr;
  1346. nv_status = p_nvenc->nvEncMapInputResource(ctx->nvencoder, &ctx->registered_frames[reg_idx].in_map);
  1347. if (nv_status != NV_ENC_SUCCESS) {
  1348. av_frame_unref(nvenc_frame->in_ref);
  1349. return nvenc_print_error(avctx, nv_status, "Error mapping an input resource");
  1350. }
  1351. }
  1352. ctx->registered_frames[reg_idx].mapped += 1;
  1353. nvenc_frame->reg_idx = reg_idx;
  1354. nvenc_frame->input_surface = ctx->registered_frames[reg_idx].in_map.mappedResource;
  1355. nvenc_frame->format = ctx->registered_frames[reg_idx].in_map.mappedBufferFmt;
  1356. nvenc_frame->pitch = frame->linesize[0];
  1357. return 0;
  1358. } else {
  1359. NV_ENC_LOCK_INPUT_BUFFER lockBufferParams = { 0 };
  1360. lockBufferParams.version = NV_ENC_LOCK_INPUT_BUFFER_VER;
  1361. lockBufferParams.inputBuffer = nvenc_frame->input_surface;
  1362. nv_status = p_nvenc->nvEncLockInputBuffer(ctx->nvencoder, &lockBufferParams);
  1363. if (nv_status != NV_ENC_SUCCESS) {
  1364. return nvenc_print_error(avctx, nv_status, "Failed locking nvenc input buffer");
  1365. }
  1366. nvenc_frame->pitch = lockBufferParams.pitch;
  1367. res = nvenc_copy_frame(avctx, nvenc_frame, &lockBufferParams, frame);
  1368. nv_status = p_nvenc->nvEncUnlockInputBuffer(ctx->nvencoder, nvenc_frame->input_surface);
  1369. if (nv_status != NV_ENC_SUCCESS) {
  1370. return nvenc_print_error(avctx, nv_status, "Failed unlocking input buffer!");
  1371. }
  1372. return res;
  1373. }
  1374. }
  1375. static void nvenc_codec_specific_pic_params(AVCodecContext *avctx,
  1376. NV_ENC_PIC_PARAMS *params)
  1377. {
  1378. NvencContext *ctx = avctx->priv_data;
  1379. switch (avctx->codec->id) {
  1380. case AV_CODEC_ID_H264:
  1381. params->codecPicParams.h264PicParams.sliceMode =
  1382. ctx->encode_config.encodeCodecConfig.h264Config.sliceMode;
  1383. params->codecPicParams.h264PicParams.sliceModeData =
  1384. ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1385. break;
  1386. case AV_CODEC_ID_HEVC:
  1387. params->codecPicParams.hevcPicParams.sliceMode =
  1388. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceMode;
  1389. params->codecPicParams.hevcPicParams.sliceModeData =
  1390. ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1391. break;
  1392. }
  1393. }
  1394. static inline void timestamp_queue_enqueue(AVFifoBuffer* queue, int64_t timestamp)
  1395. {
  1396. av_fifo_generic_write(queue, &timestamp, sizeof(timestamp), NULL);
  1397. }
  1398. static inline int64_t timestamp_queue_dequeue(AVFifoBuffer* queue)
  1399. {
  1400. int64_t timestamp = AV_NOPTS_VALUE;
  1401. if (av_fifo_size(queue) > 0)
  1402. av_fifo_generic_read(queue, &timestamp, sizeof(timestamp), NULL);
  1403. return timestamp;
  1404. }
  1405. static int nvenc_set_timestamp(AVCodecContext *avctx,
  1406. NV_ENC_LOCK_BITSTREAM *params,
  1407. AVPacket *pkt)
  1408. {
  1409. NvencContext *ctx = avctx->priv_data;
  1410. pkt->pts = params->outputTimeStamp;
  1411. /* generate the first dts by linearly extrapolating the
  1412. * first two pts values to the past */
  1413. if (avctx->max_b_frames > 0 && !ctx->first_packet_output &&
  1414. ctx->initial_pts[1] != AV_NOPTS_VALUE) {
  1415. int64_t ts0 = ctx->initial_pts[0], ts1 = ctx->initial_pts[1];
  1416. int64_t delta;
  1417. if ((ts0 < 0 && ts1 > INT64_MAX + ts0) ||
  1418. (ts0 > 0 && ts1 < INT64_MIN + ts0))
  1419. return AVERROR(ERANGE);
  1420. delta = ts1 - ts0;
  1421. if ((delta < 0 && ts0 > INT64_MAX + delta) ||
  1422. (delta > 0 && ts0 < INT64_MIN + delta))
  1423. return AVERROR(ERANGE);
  1424. pkt->dts = ts0 - delta;
  1425. ctx->first_packet_output = 1;
  1426. return 0;
  1427. }
  1428. pkt->dts = timestamp_queue_dequeue(ctx->timestamp_list);
  1429. return 0;
  1430. }
  1431. static int process_output_surface(AVCodecContext *avctx, AVPacket *pkt, NvencSurface *tmpoutsurf)
  1432. {
  1433. NvencContext *ctx = avctx->priv_data;
  1434. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1435. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1436. uint32_t slice_mode_data;
  1437. uint32_t *slice_offsets = NULL;
  1438. NV_ENC_LOCK_BITSTREAM lock_params = { 0 };
  1439. NVENCSTATUS nv_status;
  1440. int res = 0;
  1441. enum AVPictureType pict_type;
  1442. switch (avctx->codec->id) {
  1443. case AV_CODEC_ID_H264:
  1444. slice_mode_data = ctx->encode_config.encodeCodecConfig.h264Config.sliceModeData;
  1445. break;
  1446. case AV_CODEC_ID_H265:
  1447. slice_mode_data = ctx->encode_config.encodeCodecConfig.hevcConfig.sliceModeData;
  1448. break;
  1449. default:
  1450. av_log(avctx, AV_LOG_ERROR, "Unknown codec name\n");
  1451. res = AVERROR(EINVAL);
  1452. goto error;
  1453. }
  1454. slice_offsets = av_mallocz(slice_mode_data * sizeof(*slice_offsets));
  1455. if (!slice_offsets) {
  1456. res = AVERROR(ENOMEM);
  1457. goto error;
  1458. }
  1459. lock_params.version = NV_ENC_LOCK_BITSTREAM_VER;
  1460. lock_params.doNotWait = 0;
  1461. lock_params.outputBitstream = tmpoutsurf->output_surface;
  1462. lock_params.sliceOffsets = slice_offsets;
  1463. nv_status = p_nvenc->nvEncLockBitstream(ctx->nvencoder, &lock_params);
  1464. if (nv_status != NV_ENC_SUCCESS) {
  1465. res = nvenc_print_error(avctx, nv_status, "Failed locking bitstream buffer");
  1466. goto error;
  1467. }
  1468. if (res = ff_alloc_packet2(avctx, pkt, lock_params.bitstreamSizeInBytes,0)) {
  1469. p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1470. goto error;
  1471. }
  1472. memcpy(pkt->data, lock_params.bitstreamBufferPtr, lock_params.bitstreamSizeInBytes);
  1473. nv_status = p_nvenc->nvEncUnlockBitstream(ctx->nvencoder, tmpoutsurf->output_surface);
  1474. if (nv_status != NV_ENC_SUCCESS) {
  1475. res = nvenc_print_error(avctx, nv_status, "Failed unlocking bitstream buffer, expect the gates of mordor to open");
  1476. goto error;
  1477. }
  1478. if (avctx->pix_fmt == AV_PIX_FMT_CUDA || avctx->pix_fmt == AV_PIX_FMT_D3D11) {
  1479. ctx->registered_frames[tmpoutsurf->reg_idx].mapped -= 1;
  1480. if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped == 0) {
  1481. nv_status = p_nvenc->nvEncUnmapInputResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].in_map.mappedResource);
  1482. if (nv_status != NV_ENC_SUCCESS) {
  1483. res = nvenc_print_error(avctx, nv_status, "Failed unmapping input resource");
  1484. goto error;
  1485. }
  1486. nv_status = p_nvenc->nvEncUnregisterResource(ctx->nvencoder, ctx->registered_frames[tmpoutsurf->reg_idx].regptr);
  1487. if (nv_status != NV_ENC_SUCCESS) {
  1488. res = nvenc_print_error(avctx, nv_status, "Failed unregistering input resource");
  1489. goto error;
  1490. }
  1491. ctx->registered_frames[tmpoutsurf->reg_idx].ptr = NULL;
  1492. ctx->registered_frames[tmpoutsurf->reg_idx].regptr = NULL;
  1493. } else if (ctx->registered_frames[tmpoutsurf->reg_idx].mapped < 0) {
  1494. res = AVERROR_BUG;
  1495. goto error;
  1496. }
  1497. av_frame_unref(tmpoutsurf->in_ref);
  1498. tmpoutsurf->input_surface = NULL;
  1499. }
  1500. switch (lock_params.pictureType) {
  1501. case NV_ENC_PIC_TYPE_IDR:
  1502. pkt->flags |= AV_PKT_FLAG_KEY;
  1503. case NV_ENC_PIC_TYPE_I:
  1504. pict_type = AV_PICTURE_TYPE_I;
  1505. break;
  1506. case NV_ENC_PIC_TYPE_P:
  1507. pict_type = AV_PICTURE_TYPE_P;
  1508. break;
  1509. case NV_ENC_PIC_TYPE_B:
  1510. pict_type = AV_PICTURE_TYPE_B;
  1511. break;
  1512. case NV_ENC_PIC_TYPE_BI:
  1513. pict_type = AV_PICTURE_TYPE_BI;
  1514. break;
  1515. default:
  1516. av_log(avctx, AV_LOG_ERROR, "Unknown picture type encountered, expect the output to be broken.\n");
  1517. av_log(avctx, AV_LOG_ERROR, "Please report this error and include as much information on how to reproduce it as possible.\n");
  1518. res = AVERROR_EXTERNAL;
  1519. goto error;
  1520. }
  1521. #if FF_API_CODED_FRAME
  1522. FF_DISABLE_DEPRECATION_WARNINGS
  1523. avctx->coded_frame->pict_type = pict_type;
  1524. FF_ENABLE_DEPRECATION_WARNINGS
  1525. #endif
  1526. ff_side_data_set_encoder_stats(pkt,
  1527. (lock_params.frameAvgQP - 1) * FF_QP2LAMBDA, NULL, 0, pict_type);
  1528. res = nvenc_set_timestamp(avctx, &lock_params, pkt);
  1529. if (res < 0)
  1530. goto error2;
  1531. av_free(slice_offsets);
  1532. return 0;
  1533. error:
  1534. timestamp_queue_dequeue(ctx->timestamp_list);
  1535. error2:
  1536. av_free(slice_offsets);
  1537. return res;
  1538. }
  1539. static int output_ready(AVCodecContext *avctx, int flush)
  1540. {
  1541. NvencContext *ctx = avctx->priv_data;
  1542. int nb_ready, nb_pending;
  1543. /* when B-frames are enabled, we wait for two initial timestamps to
  1544. * calculate the first dts */
  1545. if (!flush && avctx->max_b_frames > 0 &&
  1546. (ctx->initial_pts[0] == AV_NOPTS_VALUE || ctx->initial_pts[1] == AV_NOPTS_VALUE))
  1547. return 0;
  1548. nb_ready = av_fifo_size(ctx->output_surface_ready_queue) / sizeof(NvencSurface*);
  1549. nb_pending = av_fifo_size(ctx->output_surface_queue) / sizeof(NvencSurface*);
  1550. if (flush)
  1551. return nb_ready > 0;
  1552. return (nb_ready > 0) && (nb_ready + nb_pending >= ctx->async_depth);
  1553. }
  1554. int ff_nvenc_send_frame(AVCodecContext *avctx, const AVFrame *frame)
  1555. {
  1556. NVENCSTATUS nv_status;
  1557. NvencSurface *tmp_out_surf, *in_surf;
  1558. int res, res2;
  1559. NvencContext *ctx = avctx->priv_data;
  1560. NvencDynLoadFunctions *dl_fn = &ctx->nvenc_dload_funcs;
  1561. NV_ENCODE_API_FUNCTION_LIST *p_nvenc = &dl_fn->nvenc_funcs;
  1562. NV_ENC_PIC_PARAMS pic_params = { 0 };
  1563. pic_params.version = NV_ENC_PIC_PARAMS_VER;
  1564. if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
  1565. return AVERROR(EINVAL);
  1566. if (ctx->encoder_flushing)
  1567. return AVERROR_EOF;
  1568. if (frame) {
  1569. in_surf = get_free_frame(ctx);
  1570. if (!in_surf)
  1571. return AVERROR(EAGAIN);
  1572. res = nvenc_push_context(avctx);
  1573. if (res < 0)
  1574. return res;
  1575. res = nvenc_upload_frame(avctx, frame, in_surf);
  1576. res2 = nvenc_pop_context(avctx);
  1577. if (res2 < 0)
  1578. return res2;
  1579. if (res)
  1580. return res;
  1581. pic_params.inputBuffer = in_surf->input_surface;
  1582. pic_params.bufferFmt = in_surf->format;
  1583. pic_params.inputWidth = in_surf->width;
  1584. pic_params.inputHeight = in_surf->height;
  1585. pic_params.inputPitch = in_surf->pitch;
  1586. pic_params.outputBitstream = in_surf->output_surface;
  1587. if (avctx->flags & AV_CODEC_FLAG_INTERLACED_DCT) {
  1588. if (frame->top_field_first)
  1589. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_TOP_BOTTOM;
  1590. else
  1591. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FIELD_BOTTOM_TOP;
  1592. } else {
  1593. pic_params.pictureStruct = NV_ENC_PIC_STRUCT_FRAME;
  1594. }
  1595. if (ctx->forced_idr >= 0 && frame->pict_type == AV_PICTURE_TYPE_I) {
  1596. pic_params.encodePicFlags =
  1597. ctx->forced_idr ? NV_ENC_PIC_FLAG_FORCEIDR : NV_ENC_PIC_FLAG_FORCEINTRA;
  1598. } else {
  1599. pic_params.encodePicFlags = 0;
  1600. }
  1601. pic_params.inputTimeStamp = frame->pts;
  1602. nvenc_codec_specific_pic_params(avctx, &pic_params);
  1603. } else {
  1604. pic_params.encodePicFlags = NV_ENC_PIC_FLAG_EOS;
  1605. ctx->encoder_flushing = 1;
  1606. }
  1607. res = nvenc_push_context(avctx);
  1608. if (res < 0)
  1609. return res;
  1610. nv_status = p_nvenc->nvEncEncodePicture(ctx->nvencoder, &pic_params);
  1611. res = nvenc_pop_context(avctx);
  1612. if (res < 0)
  1613. return res;
  1614. if (nv_status != NV_ENC_SUCCESS &&
  1615. nv_status != NV_ENC_ERR_NEED_MORE_INPUT)
  1616. return nvenc_print_error(avctx, nv_status, "EncodePicture failed!");
  1617. if (frame) {
  1618. av_fifo_generic_write(ctx->output_surface_queue, &in_surf, sizeof(in_surf), NULL);
  1619. timestamp_queue_enqueue(ctx->timestamp_list, frame->pts);
  1620. if (ctx->initial_pts[0] == AV_NOPTS_VALUE)
  1621. ctx->initial_pts[0] = frame->pts;
  1622. else if (ctx->initial_pts[1] == AV_NOPTS_VALUE)
  1623. ctx->initial_pts[1] = frame->pts;
  1624. }
  1625. /* all the pending buffers are now ready for output */
  1626. if (nv_status == NV_ENC_SUCCESS) {
  1627. while (av_fifo_size(ctx->output_surface_queue) > 0) {
  1628. av_fifo_generic_read(ctx->output_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1629. av_fifo_generic_write(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1630. }
  1631. }
  1632. return 0;
  1633. }
  1634. int ff_nvenc_receive_packet(AVCodecContext *avctx, AVPacket *pkt)
  1635. {
  1636. NvencSurface *tmp_out_surf;
  1637. int res, res2;
  1638. NvencContext *ctx = avctx->priv_data;
  1639. if ((!ctx->cu_context && !ctx->d3d11_device) || !ctx->nvencoder)
  1640. return AVERROR(EINVAL);
  1641. if (output_ready(avctx, ctx->encoder_flushing)) {
  1642. av_fifo_generic_read(ctx->output_surface_ready_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1643. res = nvenc_push_context(avctx);
  1644. if (res < 0)
  1645. return res;
  1646. res = process_output_surface(avctx, pkt, tmp_out_surf);
  1647. res2 = nvenc_pop_context(avctx);
  1648. if (res2 < 0)
  1649. return res2;
  1650. if (res)
  1651. return res;
  1652. av_fifo_generic_write(ctx->unused_surface_queue, &tmp_out_surf, sizeof(tmp_out_surf), NULL);
  1653. } else if (ctx->encoder_flushing) {
  1654. return AVERROR_EOF;
  1655. } else {
  1656. return AVERROR(EAGAIN);
  1657. }
  1658. return 0;
  1659. }
  1660. int ff_nvenc_encode_frame(AVCodecContext *avctx, AVPacket *pkt,
  1661. const AVFrame *frame, int *got_packet)
  1662. {
  1663. NvencContext *ctx = avctx->priv_data;
  1664. int res;
  1665. if (!ctx->encoder_flushing) {
  1666. res = ff_nvenc_send_frame(avctx, frame);
  1667. if (res < 0)
  1668. return res;
  1669. }
  1670. res = ff_nvenc_receive_packet(avctx, pkt);
  1671. if (res == AVERROR(EAGAIN) || res == AVERROR_EOF) {
  1672. *got_packet = 0;
  1673. } else if (res < 0) {
  1674. return res;
  1675. } else {
  1676. *got_packet = 1;
  1677. }
  1678. return 0;
  1679. }