]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale_cuda.c
avfilter/vf_scale_cuda: Add support for YUV444P16
[ffmpeg] / libavfilter / vf_scale_cuda.c
1 /*
2 * Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
3 *
4 * Permission is hereby granted, free of charge, to any person obtaining a
5 * copy of this software and associated documentation files (the "Software"),
6 * to deal in the Software without restriction, including without limitation
7 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
8 * and/or sell copies of the Software, and to permit persons to whom the
9 * Software is furnished to do so, subject to the following conditions:
10 *
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
13 *
14 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
17 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
19 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
20 * DEALINGS IN THE SOFTWARE.
21 */
22
23 #include <stdio.h>
24 #include <string.h>
25
26 #include "libavutil/avstring.h"
27 #include "libavutil/common.h"
28 #include "libavutil/hwcontext.h"
29 #include "libavutil/hwcontext_cuda_internal.h"
30 #include "libavutil/cuda_check.h"
31 #include "libavutil/internal.h"
32 #include "libavutil/opt.h"
33 #include "libavutil/pixdesc.h"
34
35 #include "avfilter.h"
36 #include "formats.h"
37 #include "internal.h"
38 #include "scale.h"
39 #include "video.h"
40
41 static const enum AVPixelFormat supported_formats[] = {
42     AV_PIX_FMT_YUV420P,
43     AV_PIX_FMT_NV12,
44     AV_PIX_FMT_YUV444P,
45     AV_PIX_FMT_P010,
46     AV_PIX_FMT_P016,
47     AV_PIX_FMT_YUV444P16,
48 };
49
50 #define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
51 #define ALIGN_UP(a, b) (((a) + (b) - 1) & ~((b) - 1))
52 #define NUM_BUFFERS 2
53 #define BLOCKX 32
54 #define BLOCKY 16
55
56 #define CHECK_CU(x) FF_CUDA_CHECK_DL(ctx, s->hwctx->internal->cuda_dl, x)
57
58 typedef struct CUDAScaleContext {
59     const AVClass *class;
60
61     AVCUDADeviceContext *hwctx;
62
63     enum AVPixelFormat in_fmt;
64     enum AVPixelFormat out_fmt;
65
66     struct {
67         int width;
68         int height;
69     } planes_in[3], planes_out[3];
70
71     AVBufferRef *frames_ctx;
72     AVFrame     *frame;
73
74     AVFrame *tmp_frame;
75     int passthrough;
76
77     /**
78      * Output sw format. AV_PIX_FMT_NONE for no conversion.
79      */
80     enum AVPixelFormat format;
81
82     char *w_expr;               ///< width  expression string
83     char *h_expr;               ///< height expression string
84
85     CUcontext   cu_ctx;
86     CUmodule    cu_module;
87     CUfunction  cu_func_uchar;
88     CUfunction  cu_func_uchar2;
89     CUfunction  cu_func_uchar4;
90     CUfunction  cu_func_ushort;
91     CUfunction  cu_func_ushort2;
92     CUfunction  cu_func_ushort4;
93     CUstream    cu_stream;
94
95     CUdeviceptr srcBuffer;
96     CUdeviceptr dstBuffer;
97     int         tex_alignment;
98 } CUDAScaleContext;
99
100 static av_cold int cudascale_init(AVFilterContext *ctx)
101 {
102     CUDAScaleContext *s = ctx->priv;
103
104     s->format = AV_PIX_FMT_NONE;
105     s->frame = av_frame_alloc();
106     if (!s->frame)
107         return AVERROR(ENOMEM);
108
109     s->tmp_frame = av_frame_alloc();
110     if (!s->tmp_frame)
111         return AVERROR(ENOMEM);
112
113     return 0;
114 }
115
116 static av_cold void cudascale_uninit(AVFilterContext *ctx)
117 {
118     CUDAScaleContext *s = ctx->priv;
119
120     av_frame_free(&s->frame);
121     av_buffer_unref(&s->frames_ctx);
122     av_frame_free(&s->tmp_frame);
123 }
124
125 static int cudascale_query_formats(AVFilterContext *ctx)
126 {
127     static const enum AVPixelFormat pixel_formats[] = {
128         AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE,
129     };
130     AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
131
132     return ff_set_common_formats(ctx, pix_fmts);
133 }
134
135 static av_cold int init_stage(CUDAScaleContext *s, AVBufferRef *device_ctx)
136 {
137     AVBufferRef *out_ref = NULL;
138     AVHWFramesContext *out_ctx;
139     int in_sw, in_sh, out_sw, out_sh;
140     int ret, i;
141
142     av_pix_fmt_get_chroma_sub_sample(s->in_fmt,  &in_sw,  &in_sh);
143     av_pix_fmt_get_chroma_sub_sample(s->out_fmt, &out_sw, &out_sh);
144     if (!s->planes_out[0].width) {
145         s->planes_out[0].width  = s->planes_in[0].width;
146         s->planes_out[0].height = s->planes_in[0].height;
147     }
148
149     for (i = 1; i < FF_ARRAY_ELEMS(s->planes_in); i++) {
150         s->planes_in[i].width   = s->planes_in[0].width   >> in_sw;
151         s->planes_in[i].height  = s->planes_in[0].height  >> in_sh;
152         s->planes_out[i].width  = s->planes_out[0].width  >> out_sw;
153         s->planes_out[i].height = s->planes_out[0].height >> out_sh;
154     }
155
156     out_ref = av_hwframe_ctx_alloc(device_ctx);
157     if (!out_ref)
158         return AVERROR(ENOMEM);
159     out_ctx = (AVHWFramesContext*)out_ref->data;
160
161     out_ctx->format    = AV_PIX_FMT_CUDA;
162     out_ctx->sw_format = s->out_fmt;
163     out_ctx->width     = FFALIGN(s->planes_out[0].width,  32);
164     out_ctx->height    = FFALIGN(s->planes_out[0].height, 32);
165
166     ret = av_hwframe_ctx_init(out_ref);
167     if (ret < 0)
168         goto fail;
169
170     av_frame_unref(s->frame);
171     ret = av_hwframe_get_buffer(out_ref, s->frame, 0);
172     if (ret < 0)
173         goto fail;
174
175     s->frame->width  = s->planes_out[0].width;
176     s->frame->height = s->planes_out[0].height;
177
178     av_buffer_unref(&s->frames_ctx);
179     s->frames_ctx = out_ref;
180
181     return 0;
182 fail:
183     av_buffer_unref(&out_ref);
184     return ret;
185 }
186
187 static int format_is_supported(enum AVPixelFormat fmt)
188 {
189     int i;
190
191     for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
192         if (supported_formats[i] == fmt)
193             return 1;
194     return 0;
195 }
196
197 static av_cold int init_processing_chain(AVFilterContext *ctx, int in_width, int in_height,
198                                          int out_width, int out_height)
199 {
200     CUDAScaleContext *s = ctx->priv;
201
202     AVHWFramesContext *in_frames_ctx;
203
204     enum AVPixelFormat in_format;
205     enum AVPixelFormat out_format;
206     int ret;
207
208     /* check that we have a hw context */
209     if (!ctx->inputs[0]->hw_frames_ctx) {
210         av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
211         return AVERROR(EINVAL);
212     }
213     in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
214     in_format     = in_frames_ctx->sw_format;
215     out_format    = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;
216
217     if (!format_is_supported(in_format)) {
218         av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n",
219                av_get_pix_fmt_name(in_format));
220         return AVERROR(ENOSYS);
221     }
222     if (!format_is_supported(out_format)) {
223         av_log(ctx, AV_LOG_ERROR, "Unsupported output format: %s\n",
224                av_get_pix_fmt_name(out_format));
225         return AVERROR(ENOSYS);
226     }
227
228     if (in_width == out_width && in_height == out_height)
229         s->passthrough = 1;
230
231     s->in_fmt = in_format;
232     s->out_fmt = out_format;
233
234     s->planes_in[0].width   = in_width;
235     s->planes_in[0].height  = in_height;
236     s->planes_out[0].width  = out_width;
237     s->planes_out[0].height = out_height;
238
239     ret = init_stage(s, in_frames_ctx->device_ref);
240     if (ret < 0)
241         return ret;
242
243     ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->frames_ctx);
244     if (!ctx->outputs[0]->hw_frames_ctx)
245         return AVERROR(ENOMEM);
246
247     return 0;
248 }
249
250 static av_cold int cudascale_config_props(AVFilterLink *outlink)
251 {
252     AVFilterContext *ctx = outlink->src;
253     AVFilterLink *inlink = outlink->src->inputs[0];
254     CUDAScaleContext *s  = ctx->priv;
255     AVHWFramesContext     *frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
256     AVCUDADeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
257     CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
258     CudaFunctions *cu = device_hwctx->internal->cuda_dl;
259     int w, h;
260     int ret;
261
262     extern char vf_scale_cuda_ptx[];
263
264     s->hwctx = device_hwctx;
265     s->cu_stream = s->hwctx->stream;
266
267     ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
268     if (ret < 0)
269         goto fail;
270
271     ret = CHECK_CU(cu->cuModuleLoadData(&s->cu_module, vf_scale_cuda_ptx));
272     if (ret < 0)
273         goto fail;
274
275     CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar, s->cu_module, "Subsample_Bilinear_uchar"));
276     if (ret < 0)
277         goto fail;
278
279     CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar2, s->cu_module, "Subsample_Bilinear_uchar2"));
280     if (ret < 0)
281         goto fail;
282
283     CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar4, s->cu_module, "Subsample_Bilinear_uchar4"));
284     if (ret < 0)
285         goto fail;
286
287     CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort, s->cu_module, "Subsample_Bilinear_ushort"));
288     if (ret < 0)
289         goto fail;
290
291     CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort2, s->cu_module, "Subsample_Bilinear_ushort2"));
292     if (ret < 0)
293         goto fail;
294
295     CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort4, s->cu_module, "Subsample_Bilinear_ushort4"));
296     if (ret < 0)
297         goto fail;
298
299
300     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
301
302     if ((ret = ff_scale_eval_dimensions(s,
303                                         s->w_expr, s->h_expr,
304                                         inlink, outlink,
305                                         &w, &h)) < 0)
306         goto fail;
307
308     if (((int64_t)h * inlink->w) > INT_MAX  ||
309         ((int64_t)w * inlink->h) > INT_MAX)
310         av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
311
312     outlink->w = w;
313     outlink->h = h;
314
315     ret = init_processing_chain(ctx, inlink->w, inlink->h, w, h);
316     if (ret < 0)
317         return ret;
318
319     av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d\n",
320            inlink->w, inlink->h, outlink->w, outlink->h);
321
322     if (inlink->sample_aspect_ratio.num) {
323         outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h*inlink->w,
324                                                              outlink->w*inlink->h},
325                                                 inlink->sample_aspect_ratio);
326     } else {
327         outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
328     }
329
330     return 0;
331
332 fail:
333     return ret;
334 }
335
336 static int call_resize_kernel(AVFilterContext *ctx, CUfunction func, int channels,
337                               uint8_t *src_dptr, int src_width, int src_height, int src_pitch,
338                               uint8_t *dst_dptr, int dst_width, int dst_height, int dst_pitch,
339                               int pixel_size)
340 {
341     CUDAScaleContext *s = ctx->priv;
342     CudaFunctions *cu = s->hwctx->internal->cuda_dl;
343     CUdeviceptr dst_devptr = (CUdeviceptr)dst_dptr;
344     CUtexObject tex = 0;
345     void *args_uchar[] = { &tex, &dst_devptr, &dst_width, &dst_height, &dst_pitch, &src_width, &src_height };
346     int ret;
347
348     CUDA_TEXTURE_DESC tex_desc = {
349         .filterMode = CU_TR_FILTER_MODE_LINEAR,
350         .flags = CU_TRSF_READ_AS_INTEGER,
351     };
352
353     CUDA_RESOURCE_DESC res_desc = {
354         .resType = CU_RESOURCE_TYPE_PITCH2D,
355         .res.pitch2D.format = pixel_size == 1 ?
356                               CU_AD_FORMAT_UNSIGNED_INT8 :
357                               CU_AD_FORMAT_UNSIGNED_INT16,
358         .res.pitch2D.numChannels = channels,
359         .res.pitch2D.width = src_width,
360         .res.pitch2D.height = src_height,
361         .res.pitch2D.pitchInBytes = src_pitch * pixel_size,
362         .res.pitch2D.devPtr = (CUdeviceptr)src_dptr,
363     };
364
365     ret = CHECK_CU(cu->cuTexObjectCreate(&tex, &res_desc, &tex_desc, NULL));
366     if (ret < 0)
367         goto exit;
368
369     ret = CHECK_CU(cu->cuLaunchKernel(func,
370                                       DIV_UP(dst_width, BLOCKX), DIV_UP(dst_height, BLOCKY), 1,
371                                       BLOCKX, BLOCKY, 1, 0, s->cu_stream, args_uchar, NULL));
372
373 exit:
374     if (tex)
375         CHECK_CU(cu->cuTexObjectDestroy(tex));
376
377     return ret;
378 }
379
380 static int scalecuda_resize(AVFilterContext *ctx,
381                             AVFrame *out, AVFrame *in)
382 {
383     AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
384     CUDAScaleContext *s = ctx->priv;
385
386     switch (in_frames_ctx->sw_format) {
387     case AV_PIX_FMT_YUV420P:
388         call_resize_kernel(ctx, s->cu_func_uchar, 1,
389                            in->data[0], in->width, in->height, in->linesize[0],
390                            out->data[0], out->width, out->height, out->linesize[0],
391                            1);
392         call_resize_kernel(ctx, s->cu_func_uchar, 1,
393                            in->data[0]+in->linesize[0]*in->height, in->width/2, in->height/2, in->linesize[0]/2,
394                            out->data[0]+out->linesize[0]*out->height, out->width/2, out->height/2, out->linesize[0]/2,
395                            1);
396         call_resize_kernel(ctx, s->cu_func_uchar, 1,
397                            in->data[0]+ ALIGN_UP((in->linesize[0]*in->height*5)/4, s->tex_alignment), in->width/2, in->height/2, in->linesize[0]/2,
398                            out->data[0]+(out->linesize[0]*out->height*5)/4, out->width/2, out->height/2, out->linesize[0]/2,
399                            1);
400         break;
401     case AV_PIX_FMT_YUV444P:
402         call_resize_kernel(ctx, s->cu_func_uchar, 1,
403                            in->data[0], in->width, in->height, in->linesize[0],
404                            out->data[0], out->width, out->height, out->linesize[0],
405                            1);
406         call_resize_kernel(ctx, s->cu_func_uchar, 1,
407                            in->data[0]+in->linesize[0]*in->height, in->width, in->height, in->linesize[0],
408                            out->data[0]+out->linesize[0]*out->height, out->width, out->height, out->linesize[0],
409                            1);
410         call_resize_kernel(ctx, s->cu_func_uchar, 1,
411                            in->data[0]+in->linesize[0]*in->height*2, in->width, in->height, in->linesize[0],
412                            out->data[0]+out->linesize[0]*out->height*2, out->width, out->height, out->linesize[0],
413                            1);
414         break;
415     case AV_PIX_FMT_YUV444P16:
416         call_resize_kernel(ctx, s->cu_func_ushort, 1,
417                            in->data[0], in->width, in->height, in->linesize[0] / 2,
418                            out->data[0], out->width, out->height, out->linesize[0] / 2,
419                            2);
420         call_resize_kernel(ctx, s->cu_func_ushort, 1,
421                            in->data[1], in->width, in->height, in->linesize[1] / 2,
422                            out->data[1], out->width, out->height, out->linesize[1] / 2,
423                            2);
424         call_resize_kernel(ctx, s->cu_func_ushort, 1,
425                            in->data[2], in->width, in->height, in->linesize[2] / 2,
426                            out->data[2], out->width, out->height, out->linesize[2] / 2,
427                            2);
428         break;
429     case AV_PIX_FMT_NV12:
430         call_resize_kernel(ctx, s->cu_func_uchar, 1,
431                            in->data[0], in->width, in->height, in->linesize[0],
432                            out->data[0], out->width, out->height, out->linesize[0],
433                            1);
434         call_resize_kernel(ctx, s->cu_func_uchar2, 2,
435                            in->data[1], in->width/2, in->height/2, in->linesize[1],
436                            out->data[0] + out->linesize[0] * ((out->height + 31) & ~0x1f), out->width/2, out->height/2, out->linesize[1]/2,
437                            1);
438         break;
439     case AV_PIX_FMT_P010LE:
440         call_resize_kernel(ctx, s->cu_func_ushort, 1,
441                            in->data[0], in->width, in->height, in->linesize[0]/2,
442                            out->data[0], out->width, out->height, out->linesize[0]/2,
443                            2);
444         call_resize_kernel(ctx, s->cu_func_ushort2, 2,
445                            in->data[1], in->width / 2, in->height / 2, in->linesize[1]/2,
446                            out->data[0] + out->linesize[0] * ((out->height + 31) & ~0x1f), out->width / 2, out->height / 2, out->linesize[1] / 4,
447                            2);
448         break;
449     case AV_PIX_FMT_P016LE:
450         call_resize_kernel(ctx, s->cu_func_ushort, 1,
451                            in->data[0], in->width, in->height, in->linesize[0] / 2,
452                            out->data[0], out->width, out->height, out->linesize[0] / 2,
453                            2);
454         call_resize_kernel(ctx, s->cu_func_ushort2, 2,
455                            in->data[1], in->width / 2, in->height / 2, in->linesize[1] / 2,
456                            out->data[0] + out->linesize[0] * ((out->height + 31) & ~0x1f), out->width / 2, out->height / 2, out->linesize[1] / 4,
457                            2);
458         break;
459     default:
460         return AVERROR_BUG;
461     }
462
463     return 0;
464 }
465
466 static int cudascale_scale(AVFilterContext *ctx, AVFrame *out, AVFrame *in)
467 {
468     CUDAScaleContext *s = ctx->priv;
469     AVFrame *src = in;
470     int ret;
471
472     ret = scalecuda_resize(ctx, s->frame, src);
473     if (ret < 0)
474         return ret;
475
476     src = s->frame;
477     ret = av_hwframe_get_buffer(src->hw_frames_ctx, s->tmp_frame, 0);
478     if (ret < 0)
479         return ret;
480
481     av_frame_move_ref(out, s->frame);
482     av_frame_move_ref(s->frame, s->tmp_frame);
483
484     ret = av_frame_copy_props(out, in);
485     if (ret < 0)
486         return ret;
487
488     return 0;
489 }
490
491 static int cudascale_filter_frame(AVFilterLink *link, AVFrame *in)
492 {
493     AVFilterContext       *ctx = link->dst;
494     CUDAScaleContext        *s = ctx->priv;
495     AVFilterLink      *outlink = ctx->outputs[0];
496     CudaFunctions          *cu = s->hwctx->internal->cuda_dl;
497
498     AVFrame *out = NULL;
499     CUcontext dummy;
500     int ret = 0;
501
502     out = av_frame_alloc();
503     if (!out) {
504         ret = AVERROR(ENOMEM);
505         goto fail;
506     }
507
508     ret = CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
509     if (ret < 0)
510         goto fail;
511
512     ret = cudascale_scale(ctx, out, in);
513
514     CHECK_CU(cu->cuCtxPopCurrent(&dummy));
515     if (ret < 0)
516         goto fail;
517
518     av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
519               (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
520               (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
521               INT_MAX);
522
523     av_frame_free(&in);
524     return ff_filter_frame(outlink, out);
525 fail:
526     av_frame_free(&in);
527     av_frame_free(&out);
528     return ret;
529 }
530
531 #define OFFSET(x) offsetof(CUDAScaleContext, x)
532 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM)
533 static const AVOption options[] = {
534     { "w",      "Output video width",  OFFSET(w_expr),     AV_OPT_TYPE_STRING, { .str = "iw"   }, .flags = FLAGS },
535     { "h",      "Output video height", OFFSET(h_expr),     AV_OPT_TYPE_STRING, { .str = "ih"   }, .flags = FLAGS },
536     { NULL },
537 };
538
539 static const AVClass cudascale_class = {
540     .class_name = "cudascale",
541     .item_name  = av_default_item_name,
542     .option     = options,
543     .version    = LIBAVUTIL_VERSION_INT,
544 };
545
546 static const AVFilterPad cudascale_inputs[] = {
547     {
548         .name        = "default",
549         .type        = AVMEDIA_TYPE_VIDEO,
550         .filter_frame = cudascale_filter_frame,
551     },
552     { NULL }
553 };
554
555 static const AVFilterPad cudascale_outputs[] = {
556     {
557         .name         = "default",
558         .type         = AVMEDIA_TYPE_VIDEO,
559         .config_props = cudascale_config_props,
560     },
561     { NULL }
562 };
563
564 AVFilter ff_vf_scale_cuda = {
565     .name      = "scale_cuda",
566     .description = NULL_IF_CONFIG_SMALL("GPU accelerated video resizer"),
567
568     .init          = cudascale_init,
569     .uninit        = cudascale_uninit,
570     .query_formats = cudascale_query_formats,
571
572     .priv_size = sizeof(CUDAScaleContext),
573     .priv_class = &cudascale_class,
574
575     .inputs    = cudascale_inputs,
576     .outputs   = cudascale_outputs,
577
578     .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,
579 };