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.

1784 lines
59KB

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