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.

1803 lines
60KB

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