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.

2261 lines
76KB

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