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.

1723 lines
57KB

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