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.

1563 lines
52KB

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