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.

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