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.

1770 lines
59KB

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