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.

433 lines
12KB

  1. /*
  2. * HW decode acceleration through NVDEC
  3. *
  4. * Copyright (c) 2016 Anton Khirnov
  5. *
  6. * This file is part of Libav.
  7. *
  8. * Libav is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * Libav is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with Libav; if not, write to the Free Software Foundation,
  20. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. #include "config.h"
  23. #include "libavutil/common.h"
  24. #include "libavutil/error.h"
  25. #include "libavutil/hwcontext.h"
  26. #include "libavutil/hwcontext_cuda_internal.h"
  27. #include "libavutil/pixdesc.h"
  28. #include "libavutil/pixfmt.h"
  29. #include "avcodec.h"
  30. #include "decode.h"
  31. #include "nvdec.h"
  32. #include "internal.h"
  33. typedef struct NVDECDecoder {
  34. CUvideodecoder decoder;
  35. AVBufferRef *hw_device_ref;
  36. CUcontext cuda_ctx;
  37. CudaFunctions *cudl;
  38. CuvidFunctions *cvdl;
  39. } NVDECDecoder;
  40. typedef struct NVDECFramePool {
  41. unsigned int dpb_size;
  42. unsigned int nb_allocated;
  43. } NVDECFramePool;
  44. static int map_avcodec_id(enum AVCodecID id)
  45. {
  46. switch (id) {
  47. case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
  48. case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
  49. }
  50. return -1;
  51. }
  52. static int map_chroma_format(enum AVPixelFormat pix_fmt)
  53. {
  54. int shift_h = 0, shift_v = 0;
  55. av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
  56. if (shift_h == 1 && shift_v == 1)
  57. return cudaVideoChromaFormat_420;
  58. else if (shift_h == 1 && shift_v == 0)
  59. return cudaVideoChromaFormat_422;
  60. else if (shift_h == 0 && shift_v == 0)
  61. return cudaVideoChromaFormat_444;
  62. return -1;
  63. }
  64. static void nvdec_decoder_free(void *opaque, uint8_t *data)
  65. {
  66. NVDECDecoder *decoder = (NVDECDecoder*)data;
  67. if (decoder->decoder)
  68. decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
  69. av_buffer_unref(&decoder->hw_device_ref);
  70. cuvid_free_functions(&decoder->cvdl);
  71. av_freep(&decoder);
  72. }
  73. static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
  74. CUVIDDECODECREATEINFO *params, void *logctx)
  75. {
  76. AVHWDeviceContext *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
  77. AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
  78. AVBufferRef *decoder_ref;
  79. NVDECDecoder *decoder;
  80. CUcontext dummy;
  81. CUresult err;
  82. int ret;
  83. decoder = av_mallocz(sizeof(*decoder));
  84. if (!decoder)
  85. return AVERROR(ENOMEM);
  86. decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
  87. nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
  88. if (!decoder_ref) {
  89. av_freep(&decoder);
  90. return AVERROR(ENOMEM);
  91. }
  92. decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
  93. if (!decoder->hw_device_ref) {
  94. ret = AVERROR(ENOMEM);
  95. goto fail;
  96. }
  97. decoder->cuda_ctx = device_hwctx->cuda_ctx;
  98. decoder->cudl = device_hwctx->internal->cuda_dl;
  99. ret = cuvid_load_functions(&decoder->cvdl);
  100. if (ret < 0) {
  101. av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
  102. goto fail;
  103. }
  104. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  105. if (err != CUDA_SUCCESS) {
  106. ret = AVERROR_UNKNOWN;
  107. goto fail;
  108. }
  109. err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
  110. decoder->cudl->cuCtxPopCurrent(&dummy);
  111. if (err != CUDA_SUCCESS) {
  112. av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
  113. ret = AVERROR_UNKNOWN;
  114. goto fail;
  115. }
  116. *out = decoder_ref;
  117. return 0;
  118. fail:
  119. av_buffer_unref(&decoder_ref);
  120. return ret;
  121. }
  122. static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
  123. {
  124. NVDECFramePool *pool = opaque;
  125. AVBufferRef *ret;
  126. if (pool->nb_allocated >= pool->dpb_size)
  127. return NULL;
  128. ret = av_buffer_alloc(sizeof(unsigned int));
  129. if (!ret)
  130. return NULL;
  131. *(unsigned int*)ret->data = pool->nb_allocated++;
  132. return ret;
  133. }
  134. int ff_nvdec_decode_uninit(AVCodecContext *avctx)
  135. {
  136. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  137. av_freep(&ctx->bitstream);
  138. ctx->bitstream_len = 0;
  139. ctx->bitstream_allocated = 0;
  140. av_freep(&ctx->slice_offsets);
  141. ctx->nb_slices = 0;
  142. ctx->slice_offsets_allocated = 0;
  143. av_buffer_unref(&ctx->decoder_ref);
  144. av_buffer_pool_uninit(&ctx->decoder_pool);
  145. return 0;
  146. }
  147. int ff_nvdec_decode_init(AVCodecContext *avctx, unsigned int dpb_size)
  148. {
  149. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  150. NVDECFramePool *pool;
  151. AVHWFramesContext *frames_ctx;
  152. const AVPixFmtDescriptor *sw_desc;
  153. CUVIDDECODECREATEINFO params = { 0 };
  154. int cuvid_codec_type, cuvid_chroma_format;
  155. int ret = 0;
  156. sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
  157. if (!sw_desc)
  158. return AVERROR_BUG;
  159. cuvid_codec_type = map_avcodec_id(avctx->codec_id);
  160. if (cuvid_codec_type < 0) {
  161. av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
  162. return AVERROR_BUG;
  163. }
  164. cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
  165. if (cuvid_chroma_format < 0) {
  166. av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
  167. return AVERROR(ENOSYS);
  168. }
  169. if (avctx->thread_type & FF_THREAD_FRAME)
  170. dpb_size += avctx->thread_count;
  171. if (!avctx->hw_frames_ctx) {
  172. AVHWFramesContext *frames_ctx;
  173. if (!avctx->hw_device_ctx) {
  174. av_log(avctx, AV_LOG_ERROR, "A hardware device or frames context "
  175. "is required for CUVID decoding.\n");
  176. return AVERROR(EINVAL);
  177. }
  178. avctx->hw_frames_ctx = av_hwframe_ctx_alloc(avctx->hw_device_ctx);
  179. if (!avctx->hw_frames_ctx)
  180. return AVERROR(ENOMEM);
  181. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  182. frames_ctx->format = AV_PIX_FMT_CUDA;
  183. frames_ctx->width = avctx->coded_width;
  184. frames_ctx->height = avctx->coded_height;
  185. frames_ctx->sw_format = AV_PIX_FMT_NV12;
  186. frames_ctx->sw_format = sw_desc->comp[0].depth > 8 ?
  187. AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
  188. frames_ctx->initial_pool_size = dpb_size;
  189. ret = av_hwframe_ctx_init(avctx->hw_frames_ctx);
  190. if (ret < 0) {
  191. av_log(avctx, AV_LOG_ERROR, "Error initializing internal frames context\n");
  192. return ret;
  193. }
  194. }
  195. frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
  196. params.ulWidth = avctx->coded_width;
  197. params.ulHeight = avctx->coded_height;
  198. params.ulTargetWidth = avctx->coded_width;
  199. params.ulTargetHeight = avctx->coded_height;
  200. params.bitDepthMinus8 = sw_desc->comp[0].depth - 8;
  201. params.OutputFormat = params.bitDepthMinus8 ?
  202. cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
  203. params.CodecType = cuvid_codec_type;
  204. params.ChromaFormat = cuvid_chroma_format;
  205. params.ulNumDecodeSurfaces = dpb_size;
  206. params.ulNumOutputSurfaces = 1;
  207. ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);
  208. if (ret < 0)
  209. return ret;
  210. pool = av_mallocz(sizeof(*pool));
  211. if (!pool) {
  212. ret = AVERROR(ENOMEM);
  213. goto fail;
  214. }
  215. pool->dpb_size = dpb_size;
  216. ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
  217. nvdec_decoder_frame_alloc, av_free);
  218. if (!ctx->decoder_pool) {
  219. ret = AVERROR(ENOMEM);
  220. goto fail;
  221. }
  222. return 0;
  223. fail:
  224. ff_nvdec_decode_uninit(avctx);
  225. return ret;
  226. }
  227. static void nvdec_fdd_priv_free(void *priv)
  228. {
  229. NVDECFrame *cf = priv;
  230. if (!cf)
  231. return;
  232. av_buffer_unref(&cf->idx_ref);
  233. av_buffer_unref(&cf->decoder_ref);
  234. av_freep(&priv);
  235. }
  236. static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
  237. {
  238. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  239. NVDECFrame *cf = (NVDECFrame*)fdd->hwaccel_priv;
  240. NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
  241. CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
  242. CUresult err;
  243. CUcontext dummy;
  244. CUdeviceptr devptr;
  245. unsigned int pitch, i;
  246. unsigned int offset = 0;
  247. int ret = 0;
  248. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  249. if (err != CUDA_SUCCESS)
  250. return AVERROR_UNKNOWN;
  251. err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
  252. &pitch, &vpp);
  253. if (err != CUDA_SUCCESS) {
  254. av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
  255. err);
  256. ret = AVERROR_UNKNOWN;
  257. goto finish;
  258. }
  259. for (i = 0; frame->data[i]; i++) {
  260. CUDA_MEMCPY2D cpy = {
  261. .srcMemoryType = CU_MEMORYTYPE_DEVICE,
  262. .dstMemoryType = CU_MEMORYTYPE_DEVICE,
  263. .srcDevice = devptr,
  264. .dstDevice = (CUdeviceptr)frame->data[i],
  265. .srcPitch = pitch,
  266. .dstPitch = frame->linesize[i],
  267. .srcY = offset,
  268. .WidthInBytes = FFMIN(pitch, frame->linesize[i]),
  269. .Height = frame->height >> (i ? 1 : 0),
  270. };
  271. err = decoder->cudl->cuMemcpy2D(&cpy);
  272. if (err != CUDA_SUCCESS) {
  273. av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
  274. err);
  275. ret = AVERROR_UNKNOWN;
  276. goto copy_fail;
  277. }
  278. offset += cpy.Height;
  279. }
  280. copy_fail:
  281. decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
  282. finish:
  283. decoder->cudl->cuCtxPopCurrent(&dummy);
  284. return ret;
  285. }
  286. int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
  287. {
  288. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  289. FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
  290. NVDECFrame *cf = NULL;
  291. int ret;
  292. ctx->bitstream_len = 0;
  293. ctx->nb_slices = 0;
  294. if (fdd->hwaccel_priv)
  295. return 0;
  296. cf = av_mallocz(sizeof(*cf));
  297. if (!cf)
  298. return AVERROR(ENOMEM);
  299. cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
  300. if (!cf->decoder_ref)
  301. goto fail;
  302. cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
  303. if (!cf->idx_ref) {
  304. av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
  305. ret = AVERROR(ENOMEM);
  306. goto fail;
  307. }
  308. cf->idx = *(unsigned int*)cf->idx_ref->data;
  309. fdd->hwaccel_priv = cf;
  310. fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
  311. fdd->post_process = nvdec_retrieve_data;
  312. return 0;
  313. fail:
  314. nvdec_fdd_priv_free(cf);
  315. return ret;
  316. }
  317. int ff_nvdec_end_frame(AVCodecContext *avctx)
  318. {
  319. NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
  320. NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
  321. CUVIDPICPARAMS *pp = &ctx->pic_params;
  322. CUresult err;
  323. CUcontext dummy;
  324. int ret = 0;
  325. pp->nBitstreamDataLen = ctx->bitstream_len;
  326. pp->pBitstreamData = ctx->bitstream;
  327. pp->nNumSlices = ctx->nb_slices;
  328. pp->pSliceDataOffsets = ctx->slice_offsets;
  329. err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
  330. if (err != CUDA_SUCCESS)
  331. return AVERROR_UNKNOWN;
  332. err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
  333. if (err != CUDA_SUCCESS) {
  334. av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
  335. err);
  336. ret = AVERROR_UNKNOWN;
  337. goto finish;
  338. }
  339. finish:
  340. decoder->cudl->cuCtxPopCurrent(&dummy);
  341. return ret;
  342. }