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.

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