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.

2330 lines
78KB

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