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