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