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.

1731 lines
58KB

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