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)
66 typedef struct CUDAScaleContext {
69 AVCUDADeviceContext *hwctx;
71 enum AVPixelFormat in_fmt;
72 enum AVPixelFormat out_fmt;
74 AVBufferRef *frames_ctx;
81 * Output sw format. AV_PIX_FMT_NONE for no conversion.
83 enum AVPixelFormat format;
85 char *w_expr; ///< width expression string
86 char *h_expr; ///< height expression string
88 int force_original_aspect_ratio;
89 int force_divisible_by;
93 CUfunction cu_func_uchar;
94 CUfunction cu_func_uchar2;
95 CUfunction cu_func_uchar4;
96 CUfunction cu_func_ushort;
97 CUfunction cu_func_ushort2;
98 CUfunction cu_func_ushort4;
101 CUdeviceptr srcBuffer;
102 CUdeviceptr dstBuffer;
106 int interp_use_linear;
107 int interp_as_integer;
110 static av_cold int cudascale_init(AVFilterContext *ctx)
112 CUDAScaleContext *s = ctx->priv;
114 s->format = AV_PIX_FMT_NONE;
115 s->frame = av_frame_alloc();
117 return AVERROR(ENOMEM);
119 s->tmp_frame = av_frame_alloc();
121 return AVERROR(ENOMEM);
126 static av_cold void cudascale_uninit(AVFilterContext *ctx)
128 CUDAScaleContext *s = ctx->priv;
130 if (s->hwctx && s->cu_module) {
131 CudaFunctions *cu = s->hwctx->internal->cuda_dl;
134 CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
135 CHECK_CU(cu->cuModuleUnload(s->cu_module));
137 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
140 av_frame_free(&s->frame);
141 av_buffer_unref(&s->frames_ctx);
142 av_frame_free(&s->tmp_frame);
145 static int cudascale_query_formats(AVFilterContext *ctx)
147 static const enum AVPixelFormat pixel_formats[] = {
148 AV_PIX_FMT_CUDA, AV_PIX_FMT_NONE,
150 AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
152 return AVERROR(ENOMEM);
154 return ff_set_common_formats(ctx, pix_fmts);
157 static av_cold int init_hwframe_ctx(CUDAScaleContext *s, AVBufferRef *device_ctx, int width, int height)
159 AVBufferRef *out_ref = NULL;
160 AVHWFramesContext *out_ctx;
163 out_ref = av_hwframe_ctx_alloc(device_ctx);
165 return AVERROR(ENOMEM);
166 out_ctx = (AVHWFramesContext*)out_ref->data;
168 out_ctx->format = AV_PIX_FMT_CUDA;
169 out_ctx->sw_format = s->out_fmt;
170 out_ctx->width = FFALIGN(width, 32);
171 out_ctx->height = FFALIGN(height, 32);
173 ret = av_hwframe_ctx_init(out_ref);
177 av_frame_unref(s->frame);
178 ret = av_hwframe_get_buffer(out_ref, s->frame, 0);
182 s->frame->width = width;
183 s->frame->height = height;
185 av_buffer_unref(&s->frames_ctx);
186 s->frames_ctx = out_ref;
190 av_buffer_unref(&out_ref);
194 static int format_is_supported(enum AVPixelFormat fmt)
198 for (i = 0; i < FF_ARRAY_ELEMS(supported_formats); i++)
199 if (supported_formats[i] == fmt)
204 static av_cold int init_processing_chain(AVFilterContext *ctx, int in_width, int in_height,
205 int out_width, int out_height)
207 CUDAScaleContext *s = ctx->priv;
209 AVHWFramesContext *in_frames_ctx;
211 enum AVPixelFormat in_format;
212 enum AVPixelFormat out_format;
215 /* check that we have a hw context */
216 if (!ctx->inputs[0]->hw_frames_ctx) {
217 av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
218 return AVERROR(EINVAL);
220 in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
221 in_format = in_frames_ctx->sw_format;
222 out_format = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;
224 if (!format_is_supported(in_format)) {
225 av_log(ctx, AV_LOG_ERROR, "Unsupported input format: %s\n",
226 av_get_pix_fmt_name(in_format));
227 return AVERROR(ENOSYS);
229 if (!format_is_supported(out_format)) {
230 av_log(ctx, AV_LOG_ERROR, "Unsupported output format: %s\n",
231 av_get_pix_fmt_name(out_format));
232 return AVERROR(ENOSYS);
235 s->in_fmt = in_format;
236 s->out_fmt = out_format;
238 if (s->passthrough && in_width == out_width && in_height == out_height && in_format == out_format) {
239 s->frames_ctx = av_buffer_ref(ctx->inputs[0]->hw_frames_ctx);
241 return AVERROR(ENOMEM);
245 ret = init_hwframe_ctx(s, in_frames_ctx->device_ref, out_width, out_height);
250 ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->frames_ctx);
251 if (!ctx->outputs[0]->hw_frames_ctx)
252 return AVERROR(ENOMEM);
257 static av_cold int cudascale_config_props(AVFilterLink *outlink)
259 AVFilterContext *ctx = outlink->src;
260 AVFilterLink *inlink = outlink->src->inputs[0];
261 CUDAScaleContext *s = ctx->priv;
262 AVHWFramesContext *frames_ctx = (AVHWFramesContext*)inlink->hw_frames_ctx->data;
263 AVCUDADeviceContext *device_hwctx = frames_ctx->device_ctx->hwctx;
264 CUcontext dummy, cuda_ctx = device_hwctx->cuda_ctx;
265 CudaFunctions *cu = device_hwctx->internal->cuda_dl;
271 const char *function_infix = "";
273 extern char vf_scale_cuda_ptx[];
274 extern char vf_scale_cuda_bicubic_ptx[];
276 switch(s->interp_algo) {
277 case INTERP_ALGO_NEAREST:
278 scaler_ptx = vf_scale_cuda_ptx;
279 function_infix = "_Nearest";
280 s->interp_use_linear = 0;
281 s->interp_as_integer = 1;
283 case INTERP_ALGO_BILINEAR:
284 scaler_ptx = vf_scale_cuda_ptx;
285 function_infix = "_Bilinear";
286 s->interp_use_linear = 1;
287 s->interp_as_integer = 1;
289 case INTERP_ALGO_DEFAULT:
290 case INTERP_ALGO_BICUBIC:
291 scaler_ptx = vf_scale_cuda_bicubic_ptx;
292 function_infix = "_Bicubic";
293 s->interp_use_linear = 0;
294 s->interp_as_integer = 0;
297 av_log(ctx, AV_LOG_ERROR, "Unknown interpolation algorithm\n");
301 s->hwctx = device_hwctx;
302 s->cu_stream = s->hwctx->stream;
304 ret = CHECK_CU(cu->cuCtxPushCurrent(cuda_ctx));
308 ret = CHECK_CU(cu->cuModuleLoadData(&s->cu_module, scaler_ptx));
312 snprintf(buf, sizeof(buf), "Subsample%s_uchar", function_infix);
313 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar, s->cu_module, buf));
317 snprintf(buf, sizeof(buf), "Subsample%s_uchar2", function_infix);
318 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar2, s->cu_module, buf));
322 snprintf(buf, sizeof(buf), "Subsample%s_uchar4", function_infix);
323 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_uchar4, s->cu_module, buf));
327 snprintf(buf, sizeof(buf), "Subsample%s_ushort", function_infix);
328 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort, s->cu_module, buf));
332 snprintf(buf, sizeof(buf), "Subsample%s_ushort2", function_infix);
333 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort2, s->cu_module, buf));
337 snprintf(buf, sizeof(buf), "Subsample%s_ushort4", function_infix);
338 CHECK_CU(cu->cuModuleGetFunction(&s->cu_func_ushort4, s->cu_module, buf));
343 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
345 if ((ret = ff_scale_eval_dimensions(s,
346 s->w_expr, s->h_expr,
351 ff_scale_adjust_dimensions(inlink, &w, &h,
352 s->force_original_aspect_ratio, s->force_divisible_by);
354 if (((int64_t)h * inlink->w) > INT_MAX ||
355 ((int64_t)w * inlink->h) > INT_MAX)
356 av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
361 ret = init_processing_chain(ctx, inlink->w, inlink->h, w, h);
365 av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d%s\n",
366 inlink->w, inlink->h, outlink->w, outlink->h, s->passthrough ? " (passthrough)" : "");
368 if (inlink->sample_aspect_ratio.num) {
369 outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h*inlink->w,
370 outlink->w*inlink->h},
371 inlink->sample_aspect_ratio);
373 outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
382 static int call_resize_kernel(AVFilterContext *ctx, CUfunction func, int channels,
383 uint8_t *src_dptr, int src_width, int src_height, int src_pitch,
384 uint8_t *dst_dptr, int dst_width, int dst_height, int dst_pitch,
385 int pixel_size, int bit_depth)
387 CUDAScaleContext *s = ctx->priv;
388 CudaFunctions *cu = s->hwctx->internal->cuda_dl;
389 CUdeviceptr dst_devptr = (CUdeviceptr)dst_dptr;
391 void *args_uchar[] = { &tex, &dst_devptr, &dst_width, &dst_height, &dst_pitch, &src_width, &src_height, &bit_depth };
394 CUDA_TEXTURE_DESC tex_desc = {
395 .filterMode = s->interp_use_linear ?
396 CU_TR_FILTER_MODE_LINEAR :
397 CU_TR_FILTER_MODE_POINT,
398 .flags = s->interp_as_integer ? CU_TRSF_READ_AS_INTEGER : 0,
401 CUDA_RESOURCE_DESC res_desc = {
402 .resType = CU_RESOURCE_TYPE_PITCH2D,
403 .res.pitch2D.format = pixel_size == 1 ?
404 CU_AD_FORMAT_UNSIGNED_INT8 :
405 CU_AD_FORMAT_UNSIGNED_INT16,
406 .res.pitch2D.numChannels = channels,
407 .res.pitch2D.width = src_width,
408 .res.pitch2D.height = src_height,
409 .res.pitch2D.pitchInBytes = src_pitch * pixel_size,
410 .res.pitch2D.devPtr = (CUdeviceptr)src_dptr,
413 ret = CHECK_CU(cu->cuTexObjectCreate(&tex, &res_desc, &tex_desc, NULL));
417 ret = CHECK_CU(cu->cuLaunchKernel(func,
418 DIV_UP(dst_width, BLOCKX), DIV_UP(dst_height, BLOCKY), 1,
419 BLOCKX, BLOCKY, 1, 0, s->cu_stream, args_uchar, NULL));
423 CHECK_CU(cu->cuTexObjectDestroy(tex));
428 static int scalecuda_resize(AVFilterContext *ctx,
429 AVFrame *out, AVFrame *in)
431 AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)in->hw_frames_ctx->data;
432 CUDAScaleContext *s = ctx->priv;
434 switch (in_frames_ctx->sw_format) {
435 case AV_PIX_FMT_YUV420P:
436 call_resize_kernel(ctx, s->cu_func_uchar, 1,
437 in->data[0], in->width, in->height, in->linesize[0],
438 out->data[0], out->width, out->height, out->linesize[0],
440 call_resize_kernel(ctx, s->cu_func_uchar, 1,
441 in->data[1], in->width / 2, in->height / 2, in->linesize[1],
442 out->data[1], out->width / 2, out->height / 2, out->linesize[1],
444 call_resize_kernel(ctx, s->cu_func_uchar, 1,
445 in->data[2], in->width / 2, in->height / 2, in->linesize[2],
446 out->data[2], out->width / 2, out->height / 2, out->linesize[2],
449 case AV_PIX_FMT_YUV444P:
450 call_resize_kernel(ctx, s->cu_func_uchar, 1,
451 in->data[0], in->width, in->height, in->linesize[0],
452 out->data[0], out->width, out->height, out->linesize[0],
454 call_resize_kernel(ctx, s->cu_func_uchar, 1,
455 in->data[1], in->width, in->height, in->linesize[1],
456 out->data[1], out->width, out->height, out->linesize[1],
458 call_resize_kernel(ctx, s->cu_func_uchar, 1,
459 in->data[2], in->width, in->height, in->linesize[2],
460 out->data[2], out->width, out->height, out->linesize[2],
463 case AV_PIX_FMT_YUV444P16:
464 call_resize_kernel(ctx, s->cu_func_ushort, 1,
465 in->data[0], in->width, in->height, in->linesize[0] / 2,
466 out->data[0], out->width, out->height, out->linesize[0] / 2,
468 call_resize_kernel(ctx, s->cu_func_ushort, 1,
469 in->data[1], in->width, in->height, in->linesize[1] / 2,
470 out->data[1], out->width, out->height, out->linesize[1] / 2,
472 call_resize_kernel(ctx, s->cu_func_ushort, 1,
473 in->data[2], in->width, in->height, in->linesize[2] / 2,
474 out->data[2], out->width, out->height, out->linesize[2] / 2,
477 case AV_PIX_FMT_NV12:
478 call_resize_kernel(ctx, s->cu_func_uchar, 1,
479 in->data[0], in->width, in->height, in->linesize[0],
480 out->data[0], out->width, out->height, out->linesize[0],
482 call_resize_kernel(ctx, s->cu_func_uchar2, 2,
483 in->data[1], in->width / 2, in->height / 2, in->linesize[1],
484 out->data[1], out->width / 2, out->height / 2, out->linesize[1] / 2,
487 case AV_PIX_FMT_P010LE:
488 call_resize_kernel(ctx, s->cu_func_ushort, 1,
489 in->data[0], in->width, in->height, in->linesize[0] / 2,
490 out->data[0], out->width, out->height, out->linesize[0] / 2,
492 call_resize_kernel(ctx, s->cu_func_ushort2, 2,
493 in->data[1], in->width / 2, in->height / 2, in->linesize[1] / 2,
494 out->data[1], out->width / 2, out->height / 2, out->linesize[1] / 4,
497 case AV_PIX_FMT_P016LE:
498 call_resize_kernel(ctx, s->cu_func_ushort, 1,
499 in->data[0], in->width, in->height, in->linesize[0] / 2,
500 out->data[0], out->width, out->height, out->linesize[0] / 2,
502 call_resize_kernel(ctx, s->cu_func_ushort2, 2,
503 in->data[1], in->width / 2, in->height / 2, in->linesize[1] / 2,
504 out->data[1], out->width / 2, out->height / 2, out->linesize[1] / 4,
514 static int cudascale_scale(AVFilterContext *ctx, AVFrame *out, AVFrame *in)
516 CUDAScaleContext *s = ctx->priv;
517 AVFilterLink *outlink = ctx->outputs[0];
521 ret = scalecuda_resize(ctx, s->frame, src);
526 ret = av_hwframe_get_buffer(src->hw_frames_ctx, s->tmp_frame, 0);
530 av_frame_move_ref(out, s->frame);
531 av_frame_move_ref(s->frame, s->tmp_frame);
533 s->frame->width = outlink->w;
534 s->frame->height = outlink->h;
536 ret = av_frame_copy_props(out, in);
543 static int cudascale_filter_frame(AVFilterLink *link, AVFrame *in)
545 AVFilterContext *ctx = link->dst;
546 CUDAScaleContext *s = ctx->priv;
547 AVFilterLink *outlink = ctx->outputs[0];
548 CudaFunctions *cu = s->hwctx->internal->cuda_dl;
555 return ff_filter_frame(outlink, in);
557 out = av_frame_alloc();
559 ret = AVERROR(ENOMEM);
563 ret = CHECK_CU(cu->cuCtxPushCurrent(s->hwctx->cuda_ctx));
567 ret = cudascale_scale(ctx, out, in);
569 CHECK_CU(cu->cuCtxPopCurrent(&dummy));
573 av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
574 (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
575 (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
579 return ff_filter_frame(outlink, out);
586 static AVFrame *cudascale_get_video_buffer(AVFilterLink *inlink, int w, int h)
588 CUDAScaleContext *s = inlink->dst->priv;
590 return s->passthrough ?
591 ff_null_get_video_buffer (inlink, w, h) :
592 ff_default_get_video_buffer(inlink, w, h);
595 #define OFFSET(x) offsetof(CUDAScaleContext, x)
596 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM)
597 static const AVOption options[] = {
598 { "w", "Output video width", OFFSET(w_expr), AV_OPT_TYPE_STRING, { .str = "iw" }, .flags = FLAGS },
599 { "h", "Output video height", OFFSET(h_expr), AV_OPT_TYPE_STRING, { .str = "ih" }, .flags = FLAGS },
600 { "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" },
601 { "nearest", "nearest neighbour", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_NEAREST }, 0, 0, FLAGS, "interp_algo" },
602 { "bilinear", "bilinear", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_BILINEAR }, 0, 0, FLAGS, "interp_algo" },
603 { "bicubic", "bicubic", 0, AV_OPT_TYPE_CONST, { .i64 = INTERP_ALGO_BICUBIC }, 0, 0, FLAGS, "interp_algo" },
604 { "passthrough", "Do not process frames at all if parameters match", OFFSET(passthrough), AV_OPT_TYPE_BOOL, { .i64 = 1 }, 0, 1, FLAGS },
605 { "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" },
606 { "disable", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, 0, 0, FLAGS, "force_oar" },
607 { "decrease", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, FLAGS, "force_oar" },
608 { "increase", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2 }, 0, 0, FLAGS, "force_oar" },
609 { "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 },
613 static const AVClass cudascale_class = {
614 .class_name = "cudascale",
615 .item_name = av_default_item_name,
617 .version = LIBAVUTIL_VERSION_INT,
620 static const AVFilterPad cudascale_inputs[] = {
623 .type = AVMEDIA_TYPE_VIDEO,
624 .filter_frame = cudascale_filter_frame,
625 .get_video_buffer = cudascale_get_video_buffer,
630 static const AVFilterPad cudascale_outputs[] = {
633 .type = AVMEDIA_TYPE_VIDEO,
634 .config_props = cudascale_config_props,
639 AVFilter ff_vf_scale_cuda = {
640 .name = "scale_cuda",
641 .description = NULL_IF_CONFIG_SMALL("GPU accelerated video resizer"),
643 .init = cudascale_init,
644 .uninit = cudascale_uninit,
645 .query_formats = cudascale_query_formats,
647 .priv_size = sizeof(CUDAScaleContext),
648 .priv_class = &cudascale_class,
650 .inputs = cudascale_inputs,
651 .outputs = cudascale_outputs,
653 .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,