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.

1970 lines
65KB

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