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.

1989 lines
67KB

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