]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvdec.c
Merge commit '8e0febe28effe7f427e45190eab37110126161ea'
[ffmpeg] / libavcodec / nvdec.c
1 /*
2  * HW decode acceleration through NVDEC
3  *
4  * Copyright (c) 2016 Anton Khirnov
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg 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  * FFmpeg 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 FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 #include "config.h"
24
25 #include "libavutil/common.h"
26 #include "libavutil/error.h"
27 #include "libavutil/hwcontext.h"
28 #include "libavutil/hwcontext_cuda_internal.h"
29 #include "libavutil/pixdesc.h"
30 #include "libavutil/pixfmt.h"
31
32 #include "avcodec.h"
33 #include "decode.h"
34 #include "nvdec.h"
35 #include "internal.h"
36
37 typedef struct NVDECDecoder {
38     CUvideodecoder decoder;
39
40     AVBufferRef *hw_device_ref;
41     CUcontext    cuda_ctx;
42
43     CudaFunctions *cudl;
44     CuvidFunctions *cvdl;
45 } NVDECDecoder;
46
47 typedef struct NVDECFramePool {
48     unsigned int dpb_size;
49     unsigned int nb_allocated;
50 } NVDECFramePool;
51
52 static int map_avcodec_id(enum AVCodecID id)
53 {
54     switch (id) {
55     case AV_CODEC_ID_H264: return cudaVideoCodec_H264;
56     case AV_CODEC_ID_HEVC: return cudaVideoCodec_HEVC;
57     }
58     return -1;
59 }
60
61 static int map_chroma_format(enum AVPixelFormat pix_fmt)
62 {
63     int shift_h = 0, shift_v = 0;
64
65     av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
66
67     if (shift_h == 1 && shift_v == 1)
68         return cudaVideoChromaFormat_420;
69     else if (shift_h == 1 && shift_v == 0)
70         return cudaVideoChromaFormat_422;
71     else if (shift_h == 0 && shift_v == 0)
72         return cudaVideoChromaFormat_444;
73
74     return -1;
75 }
76
77 static void nvdec_decoder_free(void *opaque, uint8_t *data)
78 {
79     NVDECDecoder *decoder = (NVDECDecoder*)data;
80
81     if (decoder->decoder)
82         decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
83
84     av_buffer_unref(&decoder->hw_device_ref);
85
86     cuvid_free_functions(&decoder->cvdl);
87
88     av_freep(&decoder);
89 }
90
91 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
92                                 CUVIDDECODECREATEINFO *params, void *logctx)
93 {
94     AVHWDeviceContext  *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
95     AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
96
97     AVBufferRef *decoder_ref;
98     NVDECDecoder *decoder;
99
100     CUcontext dummy;
101     CUresult err;
102     int ret;
103
104     decoder = av_mallocz(sizeof(*decoder));
105     if (!decoder)
106         return AVERROR(ENOMEM);
107
108     decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
109                                    nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
110     if (!decoder_ref) {
111         av_freep(&decoder);
112         return AVERROR(ENOMEM);
113     }
114
115     decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
116     if (!decoder->hw_device_ref) {
117         ret = AVERROR(ENOMEM);
118         goto fail;
119     }
120     decoder->cuda_ctx = device_hwctx->cuda_ctx;
121     decoder->cudl = device_hwctx->internal->cuda_dl;
122
123     ret = cuvid_load_functions(&decoder->cvdl);
124     if (ret < 0) {
125         av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
126         goto fail;
127     }
128
129     err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
130     if (err != CUDA_SUCCESS) {
131         ret = AVERROR_UNKNOWN;
132         goto fail;
133     }
134
135     err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
136
137     decoder->cudl->cuCtxPopCurrent(&dummy);
138
139     if (err != CUDA_SUCCESS) {
140         av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
141         ret = AVERROR_UNKNOWN;
142         goto fail;
143     }
144
145     *out = decoder_ref;
146
147     return 0;
148 fail:
149     av_buffer_unref(&decoder_ref);
150     return ret;
151 }
152
153 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
154 {
155     NVDECFramePool *pool = opaque;
156     AVBufferRef *ret;
157
158     if (pool->nb_allocated >= pool->dpb_size)
159         return NULL;
160
161     ret = av_buffer_alloc(sizeof(unsigned int));
162     if (!ret)
163         return NULL;
164
165     *(unsigned int*)ret->data = pool->nb_allocated++;
166
167     return ret;
168 }
169
170 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
171 {
172     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
173
174     av_freep(&ctx->bitstream);
175     ctx->bitstream_len       = 0;
176     ctx->bitstream_allocated = 0;
177
178     av_freep(&ctx->slice_offsets);
179     ctx->nb_slices               = 0;
180     ctx->slice_offsets_allocated = 0;
181
182     av_buffer_unref(&ctx->decoder_ref);
183     av_buffer_pool_uninit(&ctx->decoder_pool);
184
185     return 0;
186 }
187
188 int ff_nvdec_decode_init(AVCodecContext *avctx)
189 {
190     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
191
192     NVDECFramePool      *pool;
193     AVHWFramesContext   *frames_ctx;
194     const AVPixFmtDescriptor *sw_desc;
195
196     CUVIDDECODECREATEINFO params = { 0 };
197
198     int cuvid_codec_type, cuvid_chroma_format;
199     int ret = 0;
200
201     sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
202     if (!sw_desc)
203         return AVERROR_BUG;
204
205     cuvid_codec_type = map_avcodec_id(avctx->codec_id);
206     if (cuvid_codec_type < 0) {
207         av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
208         return AVERROR_BUG;
209     }
210
211     cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
212     if (cuvid_chroma_format < 0) {
213         av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
214         return AVERROR(ENOSYS);
215     }
216
217     if (!avctx->hw_frames_ctx) {
218         ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
219         if (ret < 0)
220             return ret;
221     }
222
223     frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
224
225     params.ulWidth             = avctx->coded_width;
226     params.ulHeight            = avctx->coded_height;
227     params.ulTargetWidth       = avctx->coded_width;
228     params.ulTargetHeight      = avctx->coded_height;
229     params.bitDepthMinus8      = sw_desc->comp[0].depth - 8;
230     params.OutputFormat        = params.bitDepthMinus8 ?
231                                  cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
232     params.CodecType           = cuvid_codec_type;
233     params.ChromaFormat        = cuvid_chroma_format;
234     params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
235     params.ulNumOutputSurfaces = 1;
236
237     ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);
238     if (ret < 0)
239         return ret;
240
241     pool = av_mallocz(sizeof(*pool));
242     if (!pool) {
243         ret = AVERROR(ENOMEM);
244         goto fail;
245     }
246     pool->dpb_size = frames_ctx->initial_pool_size;
247
248     ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
249                                              nvdec_decoder_frame_alloc, av_free);
250     if (!ctx->decoder_pool) {
251         ret = AVERROR(ENOMEM);
252         goto fail;
253     }
254
255     return 0;
256 fail:
257     ff_nvdec_decode_uninit(avctx);
258     return ret;
259 }
260
261 static void nvdec_fdd_priv_free(void *priv)
262 {
263     NVDECFrame *cf = priv;
264
265     if (!cf)
266         return;
267
268     av_buffer_unref(&cf->idx_ref);
269     av_buffer_unref(&cf->decoder_ref);
270
271     av_freep(&priv);
272 }
273
274 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
275 {
276     FrameDecodeData  *fdd = (FrameDecodeData*)frame->private_ref->data;
277     NVDECFrame        *cf = (NVDECFrame*)fdd->hwaccel_priv;
278     NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
279
280     CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
281
282     CUresult err;
283     CUcontext dummy;
284     CUdeviceptr devptr;
285
286     unsigned int pitch, i;
287     unsigned int offset = 0;
288     int ret = 0;
289
290     err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
291     if (err != CUDA_SUCCESS)
292         return AVERROR_UNKNOWN;
293
294     err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
295                                             &pitch, &vpp);
296     if (err != CUDA_SUCCESS) {
297         av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
298                err);
299         ret = AVERROR_UNKNOWN;
300         goto finish;
301     }
302
303     for (i = 0; frame->data[i]; i++) {
304         CUDA_MEMCPY2D cpy = {
305             .srcMemoryType = CU_MEMORYTYPE_DEVICE,
306             .dstMemoryType = CU_MEMORYTYPE_DEVICE,
307             .srcDevice     = devptr,
308             .dstDevice     = (CUdeviceptr)frame->data[i],
309             .srcPitch      = pitch,
310             .dstPitch      = frame->linesize[i],
311             .srcY          = offset,
312             .WidthInBytes  = FFMIN(pitch, frame->linesize[i]),
313             .Height        = frame->height >> (i ? 1 : 0),
314         };
315
316         err = decoder->cudl->cuMemcpy2D(&cpy);
317         if (err != CUDA_SUCCESS) {
318             av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
319                    err);
320             ret = AVERROR_UNKNOWN;
321             goto copy_fail;
322         }
323
324         offset += cpy.Height;
325     }
326
327 copy_fail:
328     decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
329
330 finish:
331     decoder->cudl->cuCtxPopCurrent(&dummy);
332     return ret;
333 }
334
335 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
336 {
337     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
338     FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
339     NVDECFrame *cf = NULL;
340     int ret;
341
342     ctx->bitstream_len = 0;
343     ctx->nb_slices     = 0;
344
345     if (fdd->hwaccel_priv)
346         return 0;
347
348     cf = av_mallocz(sizeof(*cf));
349     if (!cf)
350         return AVERROR(ENOMEM);
351
352     cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
353     if (!cf->decoder_ref)
354         goto fail;
355
356     cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
357     if (!cf->idx_ref) {
358         av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
359         ret = AVERROR(ENOMEM);
360         goto fail;
361     }
362     cf->idx = *(unsigned int*)cf->idx_ref->data;
363
364     fdd->hwaccel_priv      = cf;
365     fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
366     fdd->post_process      = nvdec_retrieve_data;
367
368     return 0;
369 fail:
370     nvdec_fdd_priv_free(cf);
371     return ret;
372
373 }
374
375 int ff_nvdec_end_frame(AVCodecContext *avctx)
376 {
377     NVDECContext     *ctx = avctx->internal->hwaccel_priv_data;
378     NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
379     CUVIDPICPARAMS    *pp = &ctx->pic_params;
380
381     CUresult err;
382     CUcontext dummy;
383
384     int ret = 0;
385
386     pp->nBitstreamDataLen = ctx->bitstream_len;
387     pp->pBitstreamData    = ctx->bitstream;
388     pp->nNumSlices        = ctx->nb_slices;
389     pp->pSliceDataOffsets = ctx->slice_offsets;
390
391     err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
392     if (err != CUDA_SUCCESS)
393         return AVERROR_UNKNOWN;
394
395     err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
396     if (err != CUDA_SUCCESS) {
397         av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
398                err);
399         ret = AVERROR_UNKNOWN;
400         goto finish;
401     }
402
403 finish:
404     decoder->cudl->cuCtxPopCurrent(&dummy);
405
406     return ret;
407 }
408
409 int ff_nvdec_frame_params(AVCodecContext *avctx,
410                           AVBufferRef *hw_frames_ctx,
411                           int dpb_size)
412 {
413     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
414     const AVPixFmtDescriptor *sw_desc;
415     int cuvid_codec_type, cuvid_chroma_format;
416
417     sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
418     if (!sw_desc)
419         return AVERROR_BUG;
420
421     cuvid_codec_type = map_avcodec_id(avctx->codec_id);
422     if (cuvid_codec_type < 0) {
423         av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
424         return AVERROR_BUG;
425     }
426
427     cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
428     if (cuvid_chroma_format < 0) {
429         av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
430         return AVERROR(EINVAL);
431     }
432
433     if (avctx->thread_type & FF_THREAD_FRAME)
434         dpb_size += avctx->thread_count;
435
436     frames_ctx->format            = AV_PIX_FMT_CUDA;
437     frames_ctx->width             = avctx->coded_width;
438     frames_ctx->height            = avctx->coded_height;
439     frames_ctx->sw_format         = sw_desc->comp[0].depth > 8 ?
440                                     AV_PIX_FMT_P010 : AV_PIX_FMT_NV12;
441     frames_ctx->initial_pool_size = dpb_size;
442
443     return 0;
444 }