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