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