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.

2215 lines
75KB

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