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.

1645 lines
55KB

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