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.

2208 lines
74KB

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