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.

1801 lines
60KB

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