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