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.

2029 lines
67KB

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