2 * This file is part of FFmpeg.
4 * FFmpeg is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
9 * FFmpeg is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * Lesser General Public License for more details.
14 * You should have received a copy of the GNU Lesser General Public
15 * License along with FFmpeg; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21 * scale video filter - QSV
24 #include <mfx/mfxvideo.h>
29 #include "libavutil/avstring.h"
30 #include "libavutil/common.h"
31 #include "libavutil/eval.h"
32 #include "libavutil/hwcontext.h"
33 #include "libavutil/hwcontext_qsv.h"
34 #include "libavutil/internal.h"
35 #include "libavutil/mathematics.h"
36 #include "libavutil/opt.h"
37 #include "libavutil/pixdesc.h"
38 #include "libavutil/time.h"
39 #include "libavfilter/qsvvpp.h"
46 static const char *const var_names[] = {
72 #define QSV_HAVE_SCALING_CONFIG QSV_VERSION_ATLEAST(1, 19)
74 typedef struct QSVScaleContext {
77 /* a clone of the main session, used internally for scaling */
83 mfxMemId *mem_ids_out;
86 mfxFrameSurface1 **surface_ptrs_in;
87 int nb_surface_ptrs_in;
89 mfxFrameSurface1 **surface_ptrs_out;
90 int nb_surface_ptrs_out;
92 mfxExtOpaqueSurfaceAlloc opaque_alloc;
94 #if QSV_HAVE_SCALING_CONFIG
95 mfxExtVPPScaling scale_conf;
99 mfxExtBuffer *ext_buffers[1 + QSV_HAVE_SCALING_CONFIG];
102 int shift_width, shift_height;
105 * New dimensions. Special values are:
106 * 0 = original width/height
107 * -1 = keep original aspect
112 * Output sw format. AV_PIX_FMT_NONE for no conversion.
114 enum AVPixelFormat format;
116 char *w_expr; ///< width expression string
117 char *h_expr; ///< height expression string
121 static av_cold int qsvscale_init(AVFilterContext *ctx)
123 QSVScaleContext *s = ctx->priv;
125 if (!strcmp(s->format_str, "same")) {
126 s->format = AV_PIX_FMT_NONE;
128 s->format = av_get_pix_fmt(s->format_str);
129 if (s->format == AV_PIX_FMT_NONE) {
130 av_log(ctx, AV_LOG_ERROR, "Unrecognized pixel format: %s\n", s->format_str);
131 return AVERROR(EINVAL);
138 static av_cold void qsvscale_uninit(AVFilterContext *ctx)
140 QSVScaleContext *s = ctx->priv;
143 MFXClose(s->session);
147 av_freep(&s->mem_ids_in);
148 av_freep(&s->mem_ids_out);
149 s->nb_mem_ids_in = 0;
150 s->nb_mem_ids_out = 0;
152 av_freep(&s->surface_ptrs_in);
153 av_freep(&s->surface_ptrs_out);
154 s->nb_surface_ptrs_in = 0;
155 s->nb_surface_ptrs_out = 0;
158 static int qsvscale_query_formats(AVFilterContext *ctx)
160 static const enum AVPixelFormat pixel_formats[] = {
161 AV_PIX_FMT_QSV, AV_PIX_FMT_NONE,
163 AVFilterFormats *pix_fmts = ff_make_format_list(pixel_formats);
166 if ((ret = ff_set_common_formats(ctx, pix_fmts)) < 0)
172 static int init_out_pool(AVFilterContext *ctx,
173 int out_width, int out_height)
175 QSVScaleContext *s = ctx->priv;
176 AVFilterLink *outlink = ctx->outputs[0];
178 AVHWFramesContext *in_frames_ctx;
179 AVHWFramesContext *out_frames_ctx;
180 AVQSVFramesContext *in_frames_hwctx;
181 AVQSVFramesContext *out_frames_hwctx;
182 enum AVPixelFormat in_format;
183 enum AVPixelFormat out_format;
186 /* check that we have a hw context */
187 if (!ctx->inputs[0]->hw_frames_ctx) {
188 av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
189 return AVERROR(EINVAL);
191 in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
192 in_frames_hwctx = in_frames_ctx->hwctx;
194 in_format = in_frames_ctx->sw_format;
195 out_format = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;
197 outlink->hw_frames_ctx = av_hwframe_ctx_alloc(in_frames_ctx->device_ref);
198 if (!outlink->hw_frames_ctx)
199 return AVERROR(ENOMEM);
200 out_frames_ctx = (AVHWFramesContext*)outlink->hw_frames_ctx->data;
201 out_frames_hwctx = out_frames_ctx->hwctx;
203 out_frames_ctx->format = AV_PIX_FMT_QSV;
204 out_frames_ctx->width = FFALIGN(out_width, 16);
205 out_frames_ctx->height = FFALIGN(out_height, 16);
206 out_frames_ctx->sw_format = out_format;
207 out_frames_ctx->initial_pool_size = 4;
209 out_frames_hwctx->frame_type = in_frames_hwctx->frame_type;
211 ret = ff_filter_init_hw_frames(ctx, outlink, 32);
215 ret = av_hwframe_ctx_init(outlink->hw_frames_ctx);
219 for (i = 0; i < out_frames_hwctx->nb_surfaces; i++) {
220 mfxFrameInfo *info = &out_frames_hwctx->surfaces[i].Info;
221 info->CropW = out_width;
222 info->CropH = out_height;
228 static mfxStatus frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
229 mfxFrameAllocResponse *resp)
231 AVFilterContext *ctx = pthis;
232 QSVScaleContext *s = ctx->priv;
234 if (!(req->Type & MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET) ||
235 !(req->Type & (MFX_MEMTYPE_FROM_VPPIN | MFX_MEMTYPE_FROM_VPPOUT)) ||
236 !(req->Type & MFX_MEMTYPE_EXTERNAL_FRAME))
237 return MFX_ERR_UNSUPPORTED;
239 if (req->Type & MFX_MEMTYPE_FROM_VPPIN) {
240 resp->mids = s->mem_ids_in;
241 resp->NumFrameActual = s->nb_mem_ids_in;
243 resp->mids = s->mem_ids_out;
244 resp->NumFrameActual = s->nb_mem_ids_out;
250 static mfxStatus frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
255 static mfxStatus frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
257 return MFX_ERR_UNSUPPORTED;
260 static mfxStatus frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
262 return MFX_ERR_UNSUPPORTED;
265 static mfxStatus frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
271 static const mfxHandleType handle_types[] = {
272 MFX_HANDLE_VA_DISPLAY,
273 MFX_HANDLE_D3D9_DEVICE_MANAGER,
274 MFX_HANDLE_D3D11_DEVICE,
277 static int init_out_session(AVFilterContext *ctx)
280 QSVScaleContext *s = ctx->priv;
281 AVHWFramesContext *in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
282 AVHWFramesContext *out_frames_ctx = (AVHWFramesContext*)ctx->outputs[0]->hw_frames_ctx->data;
283 AVQSVFramesContext *in_frames_hwctx = in_frames_ctx->hwctx;
284 AVQSVFramesContext *out_frames_hwctx = out_frames_ctx->hwctx;
285 AVQSVDeviceContext *device_hwctx = in_frames_ctx->device_ctx->hwctx;
287 int opaque = !!(in_frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME);
289 mfxHDL handle = NULL;
290 mfxHandleType handle_type;
299 /* extract the properties of the "master" session given to us */
300 err = MFXQueryIMPL(device_hwctx->session, &impl);
301 if (err == MFX_ERR_NONE)
302 err = MFXQueryVersion(device_hwctx->session, &ver);
303 if (err != MFX_ERR_NONE) {
304 av_log(ctx, AV_LOG_ERROR, "Error querying the session attributes\n");
305 return AVERROR_UNKNOWN;
308 for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
309 err = MFXVideoCORE_GetHandle(device_hwctx->session, handle_types[i], &handle);
310 if (err == MFX_ERR_NONE) {
311 handle_type = handle_types[i];
317 return ff_qsvvpp_print_error(ctx, err, "Error getting the session handle");
319 ff_qsvvpp_print_warning(ctx, err, "Warning in getting the session handle");
320 return AVERROR_UNKNOWN;
323 /* create a "slave" session with those same properties, to be used for
325 err = MFXInit(impl, &ver, &s->session);
326 if (err != MFX_ERR_NONE) {
327 av_log(ctx, AV_LOG_ERROR, "Error initializing a session for scaling\n");
328 return AVERROR_UNKNOWN;
332 err = MFXVideoCORE_SetHandle(s->session, handle_type, handle);
333 if (err != MFX_ERR_NONE)
334 return AVERROR_UNKNOWN;
337 if (QSV_RUNTIME_VERSION_ATLEAST(ver, 1, 25)) {
338 err = MFXJoinSession(device_hwctx->session, s->session);
339 if (err != MFX_ERR_NONE)
340 return AVERROR_UNKNOWN;
343 memset(&par, 0, sizeof(par));
346 s->surface_ptrs_in = av_mallocz_array(in_frames_hwctx->nb_surfaces,
347 sizeof(*s->surface_ptrs_in));
348 if (!s->surface_ptrs_in)
349 return AVERROR(ENOMEM);
350 for (i = 0; i < in_frames_hwctx->nb_surfaces; i++)
351 s->surface_ptrs_in[i] = in_frames_hwctx->surfaces + i;
352 s->nb_surface_ptrs_in = in_frames_hwctx->nb_surfaces;
354 s->surface_ptrs_out = av_mallocz_array(out_frames_hwctx->nb_surfaces,
355 sizeof(*s->surface_ptrs_out));
356 if (!s->surface_ptrs_out)
357 return AVERROR(ENOMEM);
358 for (i = 0; i < out_frames_hwctx->nb_surfaces; i++)
359 s->surface_ptrs_out[i] = out_frames_hwctx->surfaces + i;
360 s->nb_surface_ptrs_out = out_frames_hwctx->nb_surfaces;
362 s->opaque_alloc.In.Surfaces = s->surface_ptrs_in;
363 s->opaque_alloc.In.NumSurface = s->nb_surface_ptrs_in;
364 s->opaque_alloc.In.Type = in_frames_hwctx->frame_type;
366 s->opaque_alloc.Out.Surfaces = s->surface_ptrs_out;
367 s->opaque_alloc.Out.NumSurface = s->nb_surface_ptrs_out;
368 s->opaque_alloc.Out.Type = out_frames_hwctx->frame_type;
370 s->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
371 s->opaque_alloc.Header.BufferSz = sizeof(s->opaque_alloc);
373 s->ext_buffers[s->num_ext_buf++] = (mfxExtBuffer*)&s->opaque_alloc;
375 par.IOPattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY | MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
377 mfxFrameAllocator frame_allocator = {
379 .Alloc = frame_alloc,
381 .Unlock = frame_unlock,
382 .GetHDL = frame_get_hdl,
386 s->mem_ids_in = av_mallocz_array(in_frames_hwctx->nb_surfaces,
387 sizeof(*s->mem_ids_in));
389 return AVERROR(ENOMEM);
390 for (i = 0; i < in_frames_hwctx->nb_surfaces; i++)
391 s->mem_ids_in[i] = in_frames_hwctx->surfaces[i].Data.MemId;
392 s->nb_mem_ids_in = in_frames_hwctx->nb_surfaces;
394 s->mem_ids_out = av_mallocz_array(out_frames_hwctx->nb_surfaces,
395 sizeof(*s->mem_ids_out));
397 return AVERROR(ENOMEM);
398 for (i = 0; i < out_frames_hwctx->nb_surfaces; i++)
399 s->mem_ids_out[i] = out_frames_hwctx->surfaces[i].Data.MemId;
400 s->nb_mem_ids_out = out_frames_hwctx->nb_surfaces;
402 err = MFXVideoCORE_SetFrameAllocator(s->session, &frame_allocator);
403 if (err != MFX_ERR_NONE)
404 return AVERROR_UNKNOWN;
406 par.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
409 #if QSV_HAVE_SCALING_CONFIG
410 memset(&s->scale_conf, 0, sizeof(mfxExtVPPScaling));
411 s->scale_conf.Header.BufferId = MFX_EXTBUFF_VPP_SCALING;
412 s->scale_conf.Header.BufferSz = sizeof(mfxExtVPPScaling);
413 s->scale_conf.ScalingMode = s->mode;
414 s->ext_buffers[s->num_ext_buf++] = (mfxExtBuffer*)&s->scale_conf;
415 av_log(ctx, AV_LOG_VERBOSE, "Scaling mode: %d\n", s->mode);
418 par.ExtParam = s->ext_buffers;
419 par.NumExtParam = s->num_ext_buf;
421 par.AsyncDepth = 1; // TODO async
423 par.vpp.In = in_frames_hwctx->surfaces[0].Info;
424 par.vpp.Out = out_frames_hwctx->surfaces[0].Info;
426 /* Apparently VPP requires the frame rate to be set to some value, otherwise
427 * init will fail (probably for the framerate conversion filter). Since we
428 * are only doing scaling here, we just invent an arbitrary
430 par.vpp.In.FrameRateExtN = 25;
431 par.vpp.In.FrameRateExtD = 1;
432 par.vpp.Out.FrameRateExtN = 25;
433 par.vpp.Out.FrameRateExtD = 1;
435 /* Print input memory mode */
436 ff_qsvvpp_print_iopattern(ctx, par.IOPattern & 0x0F, "VPP");
437 /* Print output memory mode */
438 ff_qsvvpp_print_iopattern(ctx, par.IOPattern & 0xF0, "VPP");
439 err = MFXVideoVPP_Init(s->session, &par);
441 return ff_qsvvpp_print_error(ctx, err,
442 "Error opening the VPP for scaling");
444 ff_qsvvpp_print_warning(ctx, err,
445 "Warning in VPP initialization");
446 return AVERROR_UNKNOWN;
452 static int init_scale_session(AVFilterContext *ctx, int in_width, int in_height,
453 int out_width, int out_height)
457 qsvscale_uninit(ctx);
459 ret = init_out_pool(ctx, out_width, out_height);
463 ret = init_out_session(ctx);
470 static int qsvscale_config_props(AVFilterLink *outlink)
472 AVFilterContext *ctx = outlink->src;
473 AVFilterLink *inlink = outlink->src->inputs[0];
474 QSVScaleContext *s = ctx->priv;
476 double var_values[VARS_NB], res;
480 var_values[VAR_PI] = M_PI;
481 var_values[VAR_PHI] = M_PHI;
482 var_values[VAR_E] = M_E;
483 var_values[VAR_IN_W] = var_values[VAR_IW] = inlink->w;
484 var_values[VAR_IN_H] = var_values[VAR_IH] = inlink->h;
485 var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
486 var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
487 var_values[VAR_A] = (double) inlink->w / inlink->h;
488 var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ?
489 (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
490 var_values[VAR_DAR] = var_values[VAR_A] * var_values[VAR_SAR];
492 /* evaluate width and height */
493 av_expr_parse_and_eval(&res, (expr = s->w_expr),
494 var_names, var_values,
495 NULL, NULL, NULL, NULL, NULL, 0, ctx);
496 s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
497 if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
498 var_names, var_values,
499 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
501 s->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
502 /* evaluate again the width, as it may depend on the output height */
503 if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
504 var_names, var_values,
505 NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
512 /* sanity check params */
513 if (w < -1 || h < -1) {
514 av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
515 return AVERROR(EINVAL);
517 if (w == -1 && h == -1)
525 w = av_rescale(h, inlink->w, inlink->h);
527 h = av_rescale(w, inlink->h, inlink->w);
529 if (w > INT_MAX || h > INT_MAX ||
530 (h * inlink->w) > INT_MAX ||
531 (w * inlink->h) > INT_MAX)
532 av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
537 ret = init_scale_session(ctx, inlink->w, inlink->h, w, h);
541 av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d\n",
542 inlink->w, inlink->h, outlink->w, outlink->h);
544 if (inlink->sample_aspect_ratio.num)
545 outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h*inlink->w,
546 outlink->w*inlink->h},
547 inlink->sample_aspect_ratio);
549 outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
554 av_log(ctx, AV_LOG_ERROR,
555 "Error when evaluating the expression '%s'\n", expr);
559 static int qsvscale_filter_frame(AVFilterLink *link, AVFrame *in)
561 AVFilterContext *ctx = link->dst;
562 QSVScaleContext *s = ctx->priv;
563 AVFilterLink *outlink = ctx->outputs[0];
565 mfxSyncPoint sync = NULL;
571 out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
573 ret = AVERROR(ENOMEM);
578 err = MFXVideoVPP_RunFrameVPPAsync(s->session,
579 (mfxFrameSurface1*)in->data[3],
580 (mfxFrameSurface1*)out->data[3],
582 if (err == MFX_WRN_DEVICE_BUSY)
584 } while (err == MFX_WRN_DEVICE_BUSY);
587 ret = ff_qsvvpp_print_error(ctx, err, "Error during scaling");
592 av_log(ctx, AV_LOG_ERROR, "No sync during scaling\n");
593 ret = AVERROR_UNKNOWN;
598 err = MFXVideoCORE_SyncOperation(s->session, sync, 1000);
599 } while (err == MFX_WRN_IN_EXECUTION);
601 ret = ff_qsvvpp_print_error(ctx, err, "Error synchronizing the operation");
605 ret = av_frame_copy_props(out, in);
609 out->width = outlink->w;
610 out->height = outlink->h;
612 av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
613 (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
614 (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
618 return ff_filter_frame(outlink, out);
625 #define OFFSET(x) offsetof(QSVScaleContext, x)
626 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
627 static const AVOption options[] = {
628 { "w", "Output video width", OFFSET(w_expr), AV_OPT_TYPE_STRING, { .str = "iw" }, .flags = FLAGS },
629 { "h", "Output video height", OFFSET(h_expr), AV_OPT_TYPE_STRING, { .str = "ih" }, .flags = FLAGS },
630 { "format", "Output pixel format", OFFSET(format_str), AV_OPT_TYPE_STRING, { .str = "same" }, .flags = FLAGS },
632 #if QSV_HAVE_SCALING_CONFIG
633 { "mode", "set scaling mode", OFFSET(mode), AV_OPT_TYPE_INT, { .i64 = MFX_SCALING_MODE_DEFAULT}, MFX_SCALING_MODE_DEFAULT, MFX_SCALING_MODE_QUALITY, FLAGS, "mode"},
634 { "low_power", "low power mode", 0, AV_OPT_TYPE_CONST, { .i64 = MFX_SCALING_MODE_LOWPOWER}, INT_MIN, INT_MAX, FLAGS, "mode"},
635 { "hq", "high quality mode", 0, AV_OPT_TYPE_CONST, { .i64 = MFX_SCALING_MODE_QUALITY}, INT_MIN, INT_MAX, FLAGS, "mode"},
637 { "mode", "(not supported)", OFFSET(mode), AV_OPT_TYPE_INT, { .i64 = 0}, 0, INT_MAX, FLAGS, "mode"},
638 { "low_power", "", 0, AV_OPT_TYPE_CONST, { .i64 = 1}, 0, 0, FLAGS, "mode"},
639 { "hq", "", 0, AV_OPT_TYPE_CONST, { .i64 = 2}, 0, 0, FLAGS, "mode"},
645 static const AVClass qsvscale_class = {
646 .class_name = "scale_qsv",
647 .item_name = av_default_item_name,
649 .version = LIBAVUTIL_VERSION_INT,
652 static const AVFilterPad qsvscale_inputs[] = {
655 .type = AVMEDIA_TYPE_VIDEO,
656 .filter_frame = qsvscale_filter_frame,
661 static const AVFilterPad qsvscale_outputs[] = {
664 .type = AVMEDIA_TYPE_VIDEO,
665 .config_props = qsvscale_config_props,
670 const AVFilter ff_vf_scale_qsv = {
672 .description = NULL_IF_CONFIG_SMALL("QuickSync video scaling and format conversion"),
674 .init = qsvscale_init,
675 .uninit = qsvscale_uninit,
676 .query_formats = qsvscale_query_formats,
678 .priv_size = sizeof(QSVScaleContext),
679 .priv_class = &qsvscale_class,
681 .inputs = qsvscale_inputs,
682 .outputs = qsvscale_outputs,
684 .flags_internal = FF_FILTER_FLAG_HWFRAME_AWARE,