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.

1879 lines
63KB

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