]> git.sesse.net Git - ffmpeg/blob - libavcodec/nvdec.c
libvpxdec: remove pre-1.4.0 checks
[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     case AV_CODEC_ID_MPEG1VIDEO: return cudaVideoCodec_MPEG1;
58     case AV_CODEC_ID_MPEG2VIDEO: return cudaVideoCodec_MPEG2;
59     case AV_CODEC_ID_MPEG4:      return cudaVideoCodec_MPEG4;
60     case AV_CODEC_ID_VC1:        return cudaVideoCodec_VC1;
61     case AV_CODEC_ID_VP9:        return cudaVideoCodec_VP9;
62     case AV_CODEC_ID_WMV3:       return cudaVideoCodec_VC1;
63     }
64     return -1;
65 }
66
67 static int map_chroma_format(enum AVPixelFormat pix_fmt)
68 {
69     int shift_h = 0, shift_v = 0;
70
71     av_pix_fmt_get_chroma_sub_sample(pix_fmt, &shift_h, &shift_v);
72
73     if (shift_h == 1 && shift_v == 1)
74         return cudaVideoChromaFormat_420;
75     else if (shift_h == 1 && shift_v == 0)
76         return cudaVideoChromaFormat_422;
77     else if (shift_h == 0 && shift_v == 0)
78         return cudaVideoChromaFormat_444;
79
80     return -1;
81 }
82
83 static int nvdec_test_capabilities(NVDECDecoder *decoder,
84                                    CUVIDDECODECREATEINFO *params, void *logctx)
85 {
86     CUresult err;
87     CUVIDDECODECAPS caps = { 0 };
88
89     caps.eCodecType      = params->CodecType;
90     caps.eChromaFormat   = params->ChromaFormat;
91     caps.nBitDepthMinus8 = params->bitDepthMinus8;
92
93     err = decoder->cvdl->cuvidGetDecoderCaps(&caps);
94     if (err != CUDA_SUCCESS) {
95         av_log(logctx, AV_LOG_ERROR, "Failed querying decoder capabilities\n");
96         return AVERROR_UNKNOWN;
97     }
98
99     av_log(logctx, AV_LOG_VERBOSE, "NVDEC capabilities:\n");
100     av_log(logctx, AV_LOG_VERBOSE, "format supported: %s, max_mb_count: %d\n",
101            caps.bIsSupported ? "yes" : "no", caps.nMaxMBCount);
102     av_log(logctx, AV_LOG_VERBOSE, "min_width: %d, max_width: %d\n",
103            caps.nMinWidth, caps.nMaxWidth);
104     av_log(logctx, AV_LOG_VERBOSE, "min_height: %d, max_height: %d\n",
105            caps.nMinHeight, caps.nMaxHeight);
106
107     if (!caps.bIsSupported) {
108         av_log(logctx, AV_LOG_ERROR, "Hardware is lacking required capabilities\n");
109         return AVERROR(EINVAL);
110     }
111
112     if (params->ulWidth > caps.nMaxWidth || params->ulWidth < caps.nMinWidth) {
113         av_log(logctx, AV_LOG_ERROR, "Video width %d not within range from %d to %d\n",
114                (int)params->ulWidth, caps.nMinWidth, caps.nMaxWidth);
115         return AVERROR(EINVAL);
116     }
117
118     if (params->ulHeight > caps.nMaxHeight || params->ulHeight < caps.nMinHeight) {
119         av_log(logctx, AV_LOG_ERROR, "Video height %d not within range from %d to %d\n",
120                (int)params->ulHeight, caps.nMinHeight, caps.nMaxHeight);
121         return AVERROR(EINVAL);
122     }
123
124     if ((params->ulWidth * params->ulHeight) / 256 > caps.nMaxMBCount) {
125         av_log(logctx, AV_LOG_ERROR, "Video macroblock count %d exceeds maximum of %d\n",
126                (int)(params->ulWidth * params->ulHeight) / 256, caps.nMaxMBCount);
127         return AVERROR(EINVAL);
128     }
129
130     return 0;
131 }
132
133 static void nvdec_decoder_free(void *opaque, uint8_t *data)
134 {
135     NVDECDecoder *decoder = (NVDECDecoder*)data;
136
137     if (decoder->decoder)
138         decoder->cvdl->cuvidDestroyDecoder(decoder->decoder);
139
140     av_buffer_unref(&decoder->hw_device_ref);
141
142     cuvid_free_functions(&decoder->cvdl);
143
144     av_freep(&decoder);
145 }
146
147 static int nvdec_decoder_create(AVBufferRef **out, AVBufferRef *hw_device_ref,
148                                 CUVIDDECODECREATEINFO *params, void *logctx)
149 {
150     AVHWDeviceContext  *hw_device_ctx = (AVHWDeviceContext*)hw_device_ref->data;
151     AVCUDADeviceContext *device_hwctx = hw_device_ctx->hwctx;
152
153     AVBufferRef *decoder_ref;
154     NVDECDecoder *decoder;
155
156     CUcontext dummy;
157     CUresult err;
158     int ret;
159
160     decoder = av_mallocz(sizeof(*decoder));
161     if (!decoder)
162         return AVERROR(ENOMEM);
163
164     decoder_ref = av_buffer_create((uint8_t*)decoder, sizeof(*decoder),
165                                    nvdec_decoder_free, NULL, AV_BUFFER_FLAG_READONLY);
166     if (!decoder_ref) {
167         av_freep(&decoder);
168         return AVERROR(ENOMEM);
169     }
170
171     decoder->hw_device_ref = av_buffer_ref(hw_device_ref);
172     if (!decoder->hw_device_ref) {
173         ret = AVERROR(ENOMEM);
174         goto fail;
175     }
176     decoder->cuda_ctx = device_hwctx->cuda_ctx;
177     decoder->cudl = device_hwctx->internal->cuda_dl;
178
179     ret = cuvid_load_functions(&decoder->cvdl, logctx);
180     if (ret < 0) {
181         av_log(logctx, AV_LOG_ERROR, "Failed loading nvcuvid.\n");
182         goto fail;
183     }
184
185     err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
186     if (err != CUDA_SUCCESS) {
187         ret = AVERROR_UNKNOWN;
188         goto fail;
189     }
190
191     ret = nvdec_test_capabilities(decoder, params, logctx);
192     if (ret < 0) {
193         decoder->cudl->cuCtxPopCurrent(&dummy);
194         goto fail;
195     }
196
197     err = decoder->cvdl->cuvidCreateDecoder(&decoder->decoder, params);
198
199     decoder->cudl->cuCtxPopCurrent(&dummy);
200
201     if (err != CUDA_SUCCESS) {
202         av_log(logctx, AV_LOG_ERROR, "Error creating a NVDEC decoder: %d\n", err);
203         ret = AVERROR_UNKNOWN;
204         goto fail;
205     }
206
207     *out = decoder_ref;
208
209     return 0;
210 fail:
211     av_buffer_unref(&decoder_ref);
212     return ret;
213 }
214
215 static AVBufferRef *nvdec_decoder_frame_alloc(void *opaque, int size)
216 {
217     NVDECFramePool *pool = opaque;
218     AVBufferRef *ret;
219
220     if (pool->nb_allocated >= pool->dpb_size)
221         return NULL;
222
223     ret = av_buffer_alloc(sizeof(unsigned int));
224     if (!ret)
225         return NULL;
226
227     *(unsigned int*)ret->data = pool->nb_allocated++;
228
229     return ret;
230 }
231
232 int ff_nvdec_decode_uninit(AVCodecContext *avctx)
233 {
234     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
235
236     av_freep(&ctx->bitstream);
237     ctx->bitstream_len       = 0;
238     ctx->bitstream_allocated = 0;
239
240     av_freep(&ctx->slice_offsets);
241     ctx->nb_slices               = 0;
242     ctx->slice_offsets_allocated = 0;
243
244     av_buffer_unref(&ctx->decoder_ref);
245     av_buffer_pool_uninit(&ctx->decoder_pool);
246
247     return 0;
248 }
249
250 int ff_nvdec_decode_init(AVCodecContext *avctx)
251 {
252     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
253
254     NVDECFramePool      *pool;
255     AVHWFramesContext   *frames_ctx;
256     const AVPixFmtDescriptor *sw_desc;
257
258     CUVIDDECODECREATEINFO params = { 0 };
259
260     int cuvid_codec_type, cuvid_chroma_format;
261     int ret = 0;
262
263     sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
264     if (!sw_desc)
265         return AVERROR_BUG;
266
267     cuvid_codec_type = map_avcodec_id(avctx->codec_id);
268     if (cuvid_codec_type < 0) {
269         av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
270         return AVERROR_BUG;
271     }
272
273     cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
274     if (cuvid_chroma_format < 0) {
275         av_log(avctx, AV_LOG_ERROR, "Unsupported chroma format\n");
276         return AVERROR(ENOSYS);
277     }
278
279     if (!avctx->hw_frames_ctx) {
280         ret = ff_decode_get_hw_frames_ctx(avctx, AV_HWDEVICE_TYPE_CUDA);
281         if (ret < 0)
282             return ret;
283     }
284
285     frames_ctx = (AVHWFramesContext*)avctx->hw_frames_ctx->data;
286
287     params.ulWidth             = avctx->coded_width;
288     params.ulHeight            = avctx->coded_height;
289     params.ulTargetWidth       = avctx->coded_width;
290     params.ulTargetHeight      = avctx->coded_height;
291     params.bitDepthMinus8      = sw_desc->comp[0].depth - 8;
292     params.OutputFormat        = params.bitDepthMinus8 ?
293                                  cudaVideoSurfaceFormat_P016 : cudaVideoSurfaceFormat_NV12;
294     params.CodecType           = cuvid_codec_type;
295     params.ChromaFormat        = cuvid_chroma_format;
296     params.ulNumDecodeSurfaces = frames_ctx->initial_pool_size;
297     params.ulNumOutputSurfaces = 1;
298
299     ret = nvdec_decoder_create(&ctx->decoder_ref, frames_ctx->device_ref, &params, avctx);
300     if (ret < 0) {
301         if (params.ulNumDecodeSurfaces > 32) {
302             av_log(avctx, AV_LOG_WARNING, "Using more than 32 (%d) decode surfaces might cause nvdec to fail.\n",
303                    (int)params.ulNumDecodeSurfaces);
304             av_log(avctx, AV_LOG_WARNING, "Try lowering the amount of threads. Using %d right now.\n",
305                    avctx->thread_count);
306         }
307         return ret;
308     }
309
310     pool = av_mallocz(sizeof(*pool));
311     if (!pool) {
312         ret = AVERROR(ENOMEM);
313         goto fail;
314     }
315     pool->dpb_size = frames_ctx->initial_pool_size;
316
317     ctx->decoder_pool = av_buffer_pool_init2(sizeof(int), pool,
318                                              nvdec_decoder_frame_alloc, av_free);
319     if (!ctx->decoder_pool) {
320         ret = AVERROR(ENOMEM);
321         goto fail;
322     }
323
324     return 0;
325 fail:
326     ff_nvdec_decode_uninit(avctx);
327     return ret;
328 }
329
330 static void nvdec_fdd_priv_free(void *priv)
331 {
332     NVDECFrame *cf = priv;
333
334     if (!cf)
335         return;
336
337     av_buffer_unref(&cf->idx_ref);
338     av_buffer_unref(&cf->decoder_ref);
339
340     av_freep(&priv);
341 }
342
343 static int nvdec_retrieve_data(void *logctx, AVFrame *frame)
344 {
345     FrameDecodeData  *fdd = (FrameDecodeData*)frame->private_ref->data;
346     NVDECFrame        *cf = (NVDECFrame*)fdd->hwaccel_priv;
347     NVDECDecoder *decoder = (NVDECDecoder*)cf->decoder_ref->data;
348
349     CUVIDPROCPARAMS vpp = { .progressive_frame = 1 };
350
351     CUresult err;
352     CUcontext dummy;
353     CUdeviceptr devptr;
354
355     unsigned int pitch, i;
356     unsigned int offset = 0;
357     int ret = 0;
358
359     err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
360     if (err != CUDA_SUCCESS)
361         return AVERROR_UNKNOWN;
362
363     err = decoder->cvdl->cuvidMapVideoFrame(decoder->decoder, cf->idx, &devptr,
364                                             &pitch, &vpp);
365     if (err != CUDA_SUCCESS) {
366         av_log(logctx, AV_LOG_ERROR, "Error mapping a picture with CUVID: %d\n",
367                err);
368         ret = AVERROR_UNKNOWN;
369         goto finish;
370     }
371
372     for (i = 0; frame->data[i]; i++) {
373         CUDA_MEMCPY2D cpy = {
374             .srcMemoryType = CU_MEMORYTYPE_DEVICE,
375             .dstMemoryType = CU_MEMORYTYPE_DEVICE,
376             .srcDevice     = devptr,
377             .dstDevice     = (CUdeviceptr)frame->data[i],
378             .srcPitch      = pitch,
379             .dstPitch      = frame->linesize[i],
380             .srcY          = offset,
381             .WidthInBytes  = FFMIN(pitch, frame->linesize[i]),
382             .Height        = frame->height >> (i ? 1 : 0),
383         };
384
385         err = decoder->cudl->cuMemcpy2D(&cpy);
386         if (err != CUDA_SUCCESS) {
387             av_log(logctx, AV_LOG_ERROR, "Error copying decoded frame: %d\n",
388                    err);
389             ret = AVERROR_UNKNOWN;
390             goto copy_fail;
391         }
392
393         offset += cpy.Height;
394     }
395
396 copy_fail:
397     decoder->cvdl->cuvidUnmapVideoFrame(decoder->decoder, devptr);
398
399 finish:
400     decoder->cudl->cuCtxPopCurrent(&dummy);
401     return ret;
402 }
403
404 int ff_nvdec_start_frame(AVCodecContext *avctx, AVFrame *frame)
405 {
406     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
407     FrameDecodeData *fdd = (FrameDecodeData*)frame->private_ref->data;
408     NVDECFrame *cf = NULL;
409     int ret;
410
411     ctx->bitstream_len = 0;
412     ctx->nb_slices     = 0;
413
414     if (fdd->hwaccel_priv)
415         return 0;
416
417     cf = av_mallocz(sizeof(*cf));
418     if (!cf)
419         return AVERROR(ENOMEM);
420
421     cf->decoder_ref = av_buffer_ref(ctx->decoder_ref);
422     if (!cf->decoder_ref) {
423         ret = AVERROR(ENOMEM);
424         goto fail;
425     }
426
427     cf->idx_ref = av_buffer_pool_get(ctx->decoder_pool);
428     if (!cf->idx_ref) {
429         av_log(avctx, AV_LOG_ERROR, "No decoder surfaces left\n");
430         ret = AVERROR(ENOMEM);
431         goto fail;
432     }
433     cf->idx = *(unsigned int*)cf->idx_ref->data;
434
435     fdd->hwaccel_priv      = cf;
436     fdd->hwaccel_priv_free = nvdec_fdd_priv_free;
437     fdd->post_process      = nvdec_retrieve_data;
438
439     return 0;
440 fail:
441     nvdec_fdd_priv_free(cf);
442     return ret;
443
444 }
445
446 int ff_nvdec_end_frame(AVCodecContext *avctx)
447 {
448     NVDECContext     *ctx = avctx->internal->hwaccel_priv_data;
449     NVDECDecoder *decoder = (NVDECDecoder*)ctx->decoder_ref->data;
450     CUVIDPICPARAMS    *pp = &ctx->pic_params;
451
452     CUresult err;
453     CUcontext dummy;
454
455     int ret = 0;
456
457     pp->nBitstreamDataLen = ctx->bitstream_len;
458     pp->pBitstreamData    = ctx->bitstream;
459     pp->nNumSlices        = ctx->nb_slices;
460     pp->pSliceDataOffsets = ctx->slice_offsets;
461
462     err = decoder->cudl->cuCtxPushCurrent(decoder->cuda_ctx);
463     if (err != CUDA_SUCCESS)
464         return AVERROR_UNKNOWN;
465
466     err = decoder->cvdl->cuvidDecodePicture(decoder->decoder, &ctx->pic_params);
467     if (err != CUDA_SUCCESS) {
468         av_log(avctx, AV_LOG_ERROR, "Error decoding a picture with NVDEC: %d\n",
469                err);
470         ret = AVERROR_UNKNOWN;
471         goto finish;
472     }
473
474 finish:
475     decoder->cudl->cuCtxPopCurrent(&dummy);
476
477     return ret;
478 }
479
480 int ff_nvdec_simple_end_frame(AVCodecContext *avctx)
481 {
482     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
483     int ret = ff_nvdec_end_frame(avctx);
484     ctx->bitstream = NULL;
485     return ret;
486 }
487
488 int ff_nvdec_simple_decode_slice(AVCodecContext *avctx, const uint8_t *buffer,
489                                  uint32_t size)
490 {
491     NVDECContext *ctx = avctx->internal->hwaccel_priv_data;
492     void *tmp;
493
494     tmp = av_fast_realloc(ctx->slice_offsets, &ctx->slice_offsets_allocated,
495                           (ctx->nb_slices + 1) * sizeof(*ctx->slice_offsets));
496     if (!tmp)
497         return AVERROR(ENOMEM);
498     ctx->slice_offsets = tmp;
499
500     if (!ctx->bitstream)
501         ctx->bitstream = (uint8_t*)buffer;
502
503     ctx->slice_offsets[ctx->nb_slices] = buffer - ctx->bitstream;
504     ctx->bitstream_len += size;
505     ctx->nb_slices++;
506
507     return 0;
508 }
509
510 int ff_nvdec_frame_params(AVCodecContext *avctx,
511                           AVBufferRef *hw_frames_ctx,
512                           int dpb_size)
513 {
514     AVHWFramesContext *frames_ctx = (AVHWFramesContext*)hw_frames_ctx->data;
515     const AVPixFmtDescriptor *sw_desc;
516     int cuvid_codec_type, cuvid_chroma_format;
517
518     sw_desc = av_pix_fmt_desc_get(avctx->sw_pix_fmt);
519     if (!sw_desc)
520         return AVERROR_BUG;
521
522     cuvid_codec_type = map_avcodec_id(avctx->codec_id);
523     if (cuvid_codec_type < 0) {
524         av_log(avctx, AV_LOG_ERROR, "Unsupported codec ID\n");
525         return AVERROR_BUG;
526     }
527
528     cuvid_chroma_format = map_chroma_format(avctx->sw_pix_fmt);
529     if (cuvid_chroma_format < 0) {
530         av_log(avctx, AV_LOG_VERBOSE, "Unsupported chroma format\n");
531         return AVERROR(EINVAL);
532     }
533
534     frames_ctx->format            = AV_PIX_FMT_CUDA;
535     frames_ctx->width             = avctx->coded_width;
536     frames_ctx->height            = avctx->coded_height;
537     frames_ctx->initial_pool_size = dpb_size;
538
539     switch (sw_desc->comp[0].depth) {
540     case 8:
541         frames_ctx->sw_format = AV_PIX_FMT_NV12;
542         break;
543     case 10:
544         frames_ctx->sw_format = AV_PIX_FMT_P010;
545         break;
546     case 12:
547         frames_ctx->sw_format = AV_PIX_FMT_P016;
548         break;
549     default:
550         return AVERROR(EINVAL);
551     }
552
553     return 0;
554 }
555
556 int ff_nvdec_get_ref_idx(AVFrame *frame)
557 {
558     FrameDecodeData *fdd;
559     NVDECFrame *cf;
560
561     if (!frame || !frame->private_ref)
562         return -1;
563
564     fdd = (FrameDecodeData*)frame->private_ref->data;
565     cf  = (NVDECFrame*)fdd->hwaccel_priv;
566     if (!cf)
567         return -1;
568
569     return cf->idx;
570 }