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.

1673 lines
56KB

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