2 * Copyright (c) 2017, NVIDIA CORPORATION. All rights reserved.
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:
11 * The above copyright notice and this permission notice shall be included in
12 * all copies or substantial portions of the Software.
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.
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"
38 #include "scale_eval.h"
41 static const enum AVPixelFormat supported_formats[] = {
50 #define DIV_UP(a, b) ( ((a) + (b) - 1) / (b) )
54 #define CHECK_CU(x) FF_CUDA_CHECK_DL(ctx, s->hwctx->internal->cuda_dl, x)
67 typedef struct CUDAScaleContext {
70 AVCUDADeviceContext *hwctx;
72 enum AVPixelFormat in_fmt;
73 enum AVPixelFormat out_fmt;
75 AVBufferRef *frames_ctx;
82 * Output sw format. AV_PIX_FMT_NONE for no conversion.
84 enum AVPixelFormat format;
86 char *w_expr; ///< width expression string
87 char *h_expr; ///< height expression string
89 int force_original_aspect_ratio;
90 int force_divisible_by;
94 CUfunction cu_func_uchar;
95 CUfunction cu_func_uchar2;
96 CUfunction cu_func_uchar4;
97 CUfunction cu_func_ushort;
98 CUfunction cu_func_ushort2;
99 CUfunction cu_func_ushort4;
102 CUdeviceptr srcBuffer;
103 CUdeviceptr dstBuffer;
107 int interp_use_linear;
108 int interp_as_integer;
111 static av_cold int cudascale_init(AVFilterContext *ctx)
113 CUDAScaleContext *s = ctx->priv;
115 s->format = AV_PIX_FMT_NONE;
116 s->frame = av_frame_alloc();
118 return AVERROR(ENOMEM);
120 s->tmp_frame = av_frame_alloc();
122 return AVERROR(ENOMEM);
127 static av_cold void cudascale_uninit(AVFilterContext *ctx)
129 CUDAScaleContext *s = ctx->priv;
131 if (s->hwctx && s->cu_module) {
132 CudaFunctions *cu = s->hwctx->internal->cuda_dl;
135 CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
136 CHECK_CU(cu->cuModuleUnload(s->cu_module));
138 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
141 av_frame_free(&s->frame);
142 av_buffer_unref(&s->frames_ctx);
143 av_frame_free(&s->tmp_frame);
146 static int cudascale_query_formats(AVFilterContext *ctx)
148 static const enum AVPixelFormat pixel_formats[] = {
149 AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE,
151 AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
153 return AVERROR(ENOMEM);
155 return ff_set_common_formats(ctx, pix_fmts);
158 static av_cold int init_hwframe_ctx(CUDAScaleContext *s, AVBufferRef *device_ctx, int width, int height)
160 AVBufferRef *out_ref = NULL;
161 AVHWFramesContext *out_ctx;
164 out_ref = av_hwframe_ctx_alloc(device_ctx);
166 return AVERROR(ENOMEM);
167 out_ctx = (AVHWFramesContext*)out_ref->data;
169 out_ctx->format = AV_PIX_FMT_CUDA;
170 out_ctx->sw_format = s->out_fmt;
171 out_ctx->width = FFALIGN(width, 32);
172 out_ctx->height = FFALIGN(height, 32);
174 ret = av_hwframe_ctx_init(out_ref);
178 av_frame_unref(s->frame);
179 ret = av_hwframe_get_buffer(out_ref, s->frame, 0);
183 s->frame->width = width;
184 s->frame->height = height;
186 av_buffer_unref(&s->frames_ctx);
187 s->frames_ctx = out_ref;
191 av_buffer_unref(&out_ref);
195 static int format_is_supported(enum AVPixelFormat fmt)
199 for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
200 if (supported_formats[i] == fmt)
205 static av_cold int init_processing_chain(AVFilterContext *ctx, int in_width, int in_height,
206 int out_width, int out_height)
208 CUDAScaleContext *s = ctx->priv;
210 AVHWFramesContext *in_frames_ctx;
212 enum AVPixelFormat in_format;
213 enum AVPixelFormat out_format;
216 /* check that we have a hw context */
217 if (!ctx->inputs[0]->hw_frames_ctx) {
218 av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
219 return AVERROR(EINVAL);
221 in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
222 in_format = in_frames_ctx->sw_format;
223 out_format = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;
225 if (!format_is_supported(in_format)) {
226 av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n",
227 av_get_pix_fmt_name(in_format));
228 return AVERROR(ENOSYS);
230 if (!format_is_supported(out_format)) {
231 av_log(ctx, AV_LOG_ERROR, "Unsupported output format: %s\n",
232 av_get_pix_fmt_name(out_format));
233 return AVERROR(ENOSYS);
236 s->in_fmt = in_format;
237 s->out_fmt = out_format;
239 if (s->passthrough && in_width == out_width && in_height == out_height && in_format == out_format) {
240 s->frames_ctx = av_buffer_ref(ctx->inputs[0]->hw_frames_ctx);
242 return AVERROR(ENOMEM);
246 ret = init_hwframe_ctx(s, in_frames_ctx->device_ref, out_width, out_height);
251 ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->frames_ctx);
252 if (!ctx->outputs[0]->hw_frames_ctx)
253 return AVERROR(ENOMEM);
258 static av_cold int cudascale_config_props(AVFilterLink *outlink)
260 AVFilterContext *ctx = outlink->src;
261 AVFilterLink *inlink = outlink->src->inputs[0];
262 CUDAScaleContext *s = ctx->priv;
263 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
264 AVCUDADeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
265 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
266 CudaFunctions *cu = device_hwctx->internal->cuda_dl;
272 const char *function_infix = "";
274 extern char vf_scale_cuda_ptx[];
275 extern char vf_scale_cuda_bicubic_ptx[];
277 switch(s->interp_algo) {
278 case INTERP_ALGO_NEAREST:
279 scaler_ptx = vf_scale_cuda_ptx;
280 function_infix = "_Nearest";
281 s->interp_use_linear = 0;
282 s->interp_as_integer = 1;
284 case INTERP_ALGO_BILINEAR:
285 scaler_ptx = vf_scale_cuda_ptx;
286 function_infix = "_Bilinear";
287 s->interp_use_linear = 1;
288 s->interp_as_integer = 1;
290 case INTERP_ALGO_DEFAULT:
291 case INTERP_ALGO_BICUBIC:
292 scaler_ptx = vf_scale_cuda_bicubic_ptx;
293 function_infix = "_Bicubic";
294 s->interp_use_linear = 0;
295 s->interp_as_integer = 0;
297 case INTERP_ALGO_LANCZOS:
298 scaler_ptx = vf_scale_cuda_bicubic_ptx;
299 function_infix = "_Lanczos";
300 s->interp_use_linear = 0;
301 s->interp_as_integer = 0;
304 av_log(ctx, AV_LOG_ERROR, "Unknown interpolation algorithm\n");
308 s->hwctx = device_hwctx;
309 s->cu_stream = s->hwctx->stream;
311 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
315 ret = CHECK_CU(cu->cuModuleLoadData(&s->cu_module, scaler_ptx));
319 snprintf(buf, sizeof(buf), "Subsample%s_uchar", function_infix);
320 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar, s->cu_module, buf));
324 snprintf(buf, sizeof(buf), "Subsample%s_uchar2", function_infix);
325 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar2, s->cu_module, buf));
329 snprintf(buf, sizeof(buf), "Subsample%s_uchar4", function_infix);
330 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar4, s->cu_module, buf));
334 snprintf(buf, sizeof(buf), "Subsample%s_ushort", function_infix);
335 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort, s->cu_module, buf));
339 snprintf(buf, sizeof(buf), "Subsample%s_ushort2", function_infix);
340 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort2, s->cu_module, buf));
344 snprintf(buf, sizeof(buf), "Subsample%s_ushort4", function_infix);
345 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort4, s->cu_module, buf));
350 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
352 if ((ret = ff_scale_eval_dimensions(s,
353 s->w_expr, s->h_expr,
358 ff_scale_adjust_dimensions(inlink, &w, &h,
359 s->force_original_aspect_ratio, s->force_divisible_by);
361 if (((int64_t)h * inlink->w) > INT_MAX ||
362 ((int64_t)w * inlink->h) > INT_MAX)
363 av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
368 ret = init_processing_chain(ctx, inlink->w, inlink->h, w, h);
372 av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d%s\n",
373 inlink->w, inlink->h, outlink->w, outlink->h, s->passthrough ? " (passthrough)" : "");
375 if (inlink->sample_aspect_ratio.num) {
376 outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h*inlink->w,
377 outlink->w*inlink->h},
378 inlink->sample_aspect_ratio);
380 outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
389 static int call_resize_kernel(AVFilterContext *ctx, CUfunction func, int channels,
390 uint8_t *src_dptr, int src_width, int src_height, int src_pitch,
391 uint8_t *dst_dptr, int dst_width, int dst_height, int dst_pitch,
392 int pixel_size, int bit_depth)
394 CUDAScaleContext *s = ctx->priv;
395 CudaFunctions *cu = s->hwctx->internal->cuda_dl;
396 CUdeviceptr dst_devptr = (CUdeviceptr)dst_dptr;
398 void *args_uchar[] = { &tex, &dst_devptr, &dst_width, &dst_height, &dst_pitch, &src_width, &src_height, &bit_depth };
401 CUDA_TEXTURE_DESC tex_desc = {
402 .filterMode = s->interp_use_linear ?
403 CU_TR_FILTER_MODE_LINEAR :
404 CU_TR_FILTER_MODE_POINT,
405 .flags = s->interp_as_integer ? CU_TRSF_READ_AS_INTEGER : 0,
408 CUDA_RESOURCE_DESC res_desc = {
409 .resType = CU_RESOURCE_TYPE_PITCH2D,
410 .res.pitch2D.format = pixel_size == 1 ?
411 CU_AD_FORMAT_UNSIGNED_INT8 :
412 CU_AD_FORMAT_UNSIGNED_INT16,
413 .res.pitch2D.numChannels = channels,
414 .res.pitch2D.width = src_width,
415 .res.pitch2D.height = src_height,
416 .res.pitch2D.pitchInBytes = src_pitch * pixel_size,
417 .res.pitch2D.devPtr = (CUdeviceptr)src_dptr,
420 ret = CHECK_CU(cu->cuTexObjectCreate(&tex, &res_desc, &tex_desc, NULL));
424 ret = CHECK_CU(cu->cuLaunchKernel(func,
425 DIV_UP(dst_width, BLOCKX), DIV_UP(dst_height, BLOCKY), 1,
426 BLOCKX, BLOCKY, 1, 0, s->cu_stream, args_uchar, NULL));
430 CHECK_CU(cu->cuTexObjectDestroy(tex));
435 static int scalecuda_resize(AVFilterContext *ctx,
436 AVFrame *out, AVFrame *in)
438 AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
439 CUDAScaleContext *s = ctx->priv;
441 switch (in_frames_ctx->sw_format) {
442 case AV_PIX_FMT_YUV420P:
443 call_resize_kernel(ctx, s->cu_func_uchar, 1,
444 in->data[0], in->width, in->height, in->linesize[0],
445 out->data[0], out->width, out->height, out->linesize[0],
447 call_resize_kernel(ctx, s->cu_func_uchar, 1,
448 in->data[1], in->width / 2, in->height / 2, in->linesize[1],
449 out->data[1], out->width / 2, out->height / 2, out->linesize[1],
451 call_resize_kernel(ctx, s->cu_func_uchar, 1,
452 in->data[2], in->width / 2, in->height / 2, in->linesize[2],
453 out->data[2], out->width / 2, out->height / 2, out->linesize[2],
456 case AV_PIX_FMT_YUV444P:
457 call_resize_kernel(ctx, s->cu_func_uchar, 1,
458 in->data[0], in->width, in->height, in->linesize[0],
459 out->data[0], out->width, out->height, out->linesize[0],
461 call_resize_kernel(ctx, s->cu_func_uchar, 1,
462 in->data[1], in->width, in->height, in->linesize[1],
463 out->data[1], out->width, out->height, out->linesize[1],
465 call_resize_kernel(ctx, s->cu_func_uchar, 1,
466 in->data[2], in->width, in->height, in->linesize[2],
467 out->data[2], out->width, out->height, out->linesize[2],
470 case AV_PIX_FMT_YUV444P16:
471 call_resize_kernel(ctx, s->cu_func_ushort, 1,
472 in->data[0], in->width, in->height, in->linesize[0] / 2,
473 out->data[0], out->width, out->height, out->linesize[0] / 2,
475 call_resize_kernel(ctx, s->cu_func_ushort, 1,
476 in->data[1], in->width, in->height, in->linesize[1] / 2,
477 out->data[1], out->width, out->height, out->linesize[1] / 2,
479 call_resize_kernel(ctx, s->cu_func_ushort, 1,
480 in->data[2], in->width, in->height, in->linesize[2] / 2,
481 out->data[2], out->width, out->height, out->linesize[2] / 2,
484 case AV_PIX_FMT_NV12:
485 call_resize_kernel(ctx, s->cu_func_uchar, 1,
486 in->data[0], in->width, in->height, in->linesize[0],
487 out->data[0], out->width, out->height, out->linesize[0],
489 call_resize_kernel(ctx, s->cu_func_uchar2, 2,
490 in->data[1], in->width / 2, in->height / 2, in->linesize[1],
491 out->data[1], out->width / 2, out->height / 2, out->linesize[1] / 2,
494 case AV_PIX_FMT_P010LE:
495 call_resize_kernel(ctx, s->cu_func_ushort, 1,
496 in->data[0], in->width, in->height, in->linesize[0] / 2,
497 out->data[0], out->width, out->height, out->linesize[0] / 2,
499 call_resize_kernel(ctx, s->cu_func_ushort2, 2,
500 in->data[1], in->width / 2, in->height / 2, in->linesize[1] / 2,
501 out->data[1], out->width / 2, out->height / 2, out->linesize[1] / 4,
504 case AV_PIX_FMT_P016LE:
505 call_resize_kernel(ctx, s->cu_func_ushort, 1,
506 in->data[0], in->width, in->height, in->linesize[0] / 2,
507 out->data[0], out->width, out->height, out->linesize[0] / 2,
509 call_resize_kernel(ctx, s->cu_func_ushort2, 2,
510 in->data[1], in->width / 2, in->height / 2, in->linesize[1] / 2,
511 out->data[1], out->width / 2, out->height / 2, out->linesize[1] / 4,
521 static int cudascale_scale(AVFilterContext *ctx, AVFrame *out, AVFrame *in)
523 CUDAScaleContext *s = ctx->priv;
524 AVFilterLink *outlink = ctx->outputs[0];
528 ret = scalecuda_resize(ctx, s->frame, src);
533 ret = av_hwframe_get_buffer(src->hw_frames_ctx, s->tmp_frame, 0);
537 av_frame_move_ref(out, s->frame);
538 av_frame_move_ref(s->frame, s->tmp_frame);
540 s->frame->width = outlink->w;
541 s->frame->height = outlink->h;
543 ret = av_frame_copy_props(out, in);
550 static int cudascale_filter_frame(AVFilterLink *link, AVFrame *in)
552 AVFilterContext *ctx = link->dst;
553 CUDAScaleContext *s = ctx->priv;
554 AVFilterLink *outlink = ctx->outputs[0];
555 CudaFunctions *cu = s->hwctx->internal->cuda_dl;
562 return ff_filter_frame(outlink, in);
564 out = av_frame_alloc();
566 ret = AVERROR(ENOMEM);
570 ret = CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
574 ret = cudascale_scale(ctx, out, in);
576 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
580 av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
581 (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
582 (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
586 return ff_filter_frame(outlink, out);
593 static AVFrame *cudascale_get_video_buffer(AVFilterLink *inlink, int w, int h)
595 CUDAScaleContext *s = inlink->dst->priv;
597 return s->passthrough ?
598 ff_null_get_video_buffer (inlink, w, h) :
599 ff_default_get_video_buffer(inlink, w, h);
602 #define OFFSET(x) offsetof(CUDAScaleContext, x)
603 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM)
604 static const AVOption options[] = {
605 { "w", "Output video width", OFFSET(w_expr), AV_OPT_TYPE_STRING, { .str = "iw" }, .flags = FLAGS },
606 { "h", "Output video height", OFFSET(h_expr), AV_OPT_TYPE_STRING, { .str = "ih" }, .flags = FLAGS },
607 { "interp_algo", "Interpolation algorithm used for resizing", OFFSET(interp_algo), AV_OPT_TYPE_INT, { .i64 = INTERP_ALGO_DEFAULT }, 0, INTERP_ALGO_COUNT - 1, FLAGS, "interp_algo" },
608 { "nearest", "nearest neighbour", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_NEAREST }, 0, 0, FLAGS, "interp_algo" },
609 { "bilinear", "bilinear", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_BILINEAR }, 0, 0, FLAGS, "interp_algo" },
610 { "bicubic", "bicubic", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_BICUBIC }, 0, 0, FLAGS, "interp_algo" },
611 { "lanczos", "lanczos", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_LANCZOS }, 0, 0, FLAGS, "interp_algo" },
612 { "passthrough", "Do not process frames at all if parameters match", OFFSET(passthrough), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
613 { "force_original_aspect_ratio", "decrease or increase w/h if necessary to keep the original AR", OFFSET(force_original_aspect_ratio), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 2, FLAGS, "force_oar" },
614 { "disable", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, 0, 0, FLAGS, "force_oar" },
615 { "decrease", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, FLAGS, "force_oar" },
616 { "increase", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2 }, 0, 0, FLAGS, "force_oar" },
617 { "force_divisible_by", "enforce that the output resolution is divisible by a defined integer when force_original_aspect_ratio is used", OFFSET(force_divisible_by), AV_OPT_TYPE_INT, { .i64 = 1}, 1, 256, FLAGS },
621 static const AVClass cudascale_class = {
622 .class_name = "cudascale",
623 .item_name = av_default_item_name,
625 .version = LIBAVUTIL_VERSION_INT,
628 static const AVFilterPad cudascale_inputs[] = {
631 .type = AVMEDIA_TYPE_VIDEO,
632 .filter_frame = cudascale_filter_frame,
633 .get_video_buffer = cudascale_get_video_buffer,
638 static const AVFilterPad cudascale_outputs[] = {
641 .type = AVMEDIA_TYPE_VIDEO,
642 .config_props = cudascale_config_props,
647 AVFilter ff_vf_scale_cuda = {
648 .name = "scale_cuda",
649 .description = NULL_IF_CONFIG_SMALL("GPU accelerated video resizer"),
651 .init = cudascale_init,
652 .uninit = cudascale_uninit,
653 .query_formats = cudascale_query_formats,
655 .priv_size = sizeof(CUDAScaleContext),
656 .priv_class = &cudascale_class,
658 .inputs = cudascale_inputs,
659 .outputs = cudascale_outputs,
661 .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,