Browse code

lavfi: add a QSV scaling filter

Anton Khirnov authored on 2016/03/26 20:39:58
Showing 6 changed files
... ...
@@ -59,6 +59,7 @@ version <next>:
59 59
 - G.729 raw demuxer
60 60
 - MagicYUV decoder
61 61
 - Duck TrueMotion 2.0 Real Time decoder
62
+- Intel QSV video scaling filter
62 63
 
63 64
 
64 65
 version 11:
... ...
@@ -2409,6 +2409,7 @@ interlace_filter_deps="gpl"
2409 2409
 ocv_filter_deps="libopencv"
2410 2410
 resample_filter_deps="avresample"
2411 2411
 scale_filter_deps="swscale"
2412
+scale_qsv_filter_deps="libmfx"
2412 2413
 scale_vaapi_filter_deps="vaapi VAProcPipelineParameterBuffer"
2413 2414
 
2414 2415
 # examples
... ...
@@ -75,6 +75,7 @@ OBJS-$(CONFIG_PAD_FILTER)                    += vf_pad.o
75 75
 OBJS-$(CONFIG_PIXDESCTEST_FILTER)            += vf_pixdesctest.o
76 76
 OBJS-$(CONFIG_SCALE_FILTER)                  += vf_scale.o
77 77
 OBJS-$(CONFIG_SCALE_NPP_FILTER)              += vf_scale_npp.o
78
+OBJS-$(CONFIG_SCALE_QSV_FILTER)              += vf_scale_qsv.o
78 79
 OBJS-$(CONFIG_SCALE_VAAPI_FILTER)            += vf_scale_vaapi.o
79 80
 OBJS-$(CONFIG_SELECT_FILTER)                 += vf_select.o
80 81
 OBJS-$(CONFIG_SETDAR_FILTER)                 += vf_aspect.o
... ...
@@ -98,6 +98,7 @@ void avfilter_register_all(void)
98 98
     REGISTER_FILTER(PIXDESCTEST,    pixdesctest,    vf);
99 99
     REGISTER_FILTER(SCALE,          scale,          vf);
100 100
     REGISTER_FILTER(SCALE_NPP,      scale_npp,      vf);
101
+    REGISTER_FILTER(SCALE_QSV,      scale_qsv,      vf);
101 102
     REGISTER_FILTER(SCALE_VAAPI,    scale_vaapi,    vf);
102 103
     REGISTER_FILTER(SELECT,         select,         vf);
103 104
     REGISTER_FILTER(SETDAR,         setdar,         vf);
... ...
@@ -30,7 +30,7 @@
30 30
 #include "libavutil/version.h"
31 31
 
32 32
 #define LIBAVFILTER_VERSION_MAJOR  6
33
-#define LIBAVFILTER_VERSION_MINOR  4
33
+#define LIBAVFILTER_VERSION_MINOR  5
34 34
 #define LIBAVFILTER_VERSION_MICRO  0
35 35
 
36 36
 #define LIBAVFILTER_VERSION_INT AV_VERSION_INT(LIBAVFILTER_VERSION_MAJOR, \
37 37
new file mode 100644
... ...
@@ -0,0 +1,633 @@
0
+/*
1
+ * This file is part of Libav.
2
+ *
3
+ * Libav is free software; you can redistribute it and/or
4
+ * modify it under the terms of the GNU Lesser General Public
5
+ * License as published by the Free Software Foundation; either
6
+ * version 2.1 of the License, or (at your option) any later version.
7
+ *
8
+ * Libav is distributed in the hope that it will be useful,
9
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
10
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
11
+ * Lesser General Public License for more details.
12
+ *
13
+ * You should have received a copy of the GNU Lesser General Public
14
+ * License along with Libav; if not, write to the Free Software
15
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
+ */
17
+
18
+/**
19
+ * @file
20
+ * scale video filter - QSV
21
+ */
22
+
23
+#include <mfx/mfxvideo.h>
24
+
25
+#include <stdio.h>
26
+#include <string.h>
27
+
28
+#include "libavutil/avstring.h"
29
+#include "libavutil/common.h"
30
+#include "libavutil/eval.h"
31
+#include "libavutil/hwcontext.h"
32
+#include "libavutil/hwcontext_qsv.h"
33
+#include "libavutil/internal.h"
34
+#include "libavutil/mathematics.h"
35
+#include "libavutil/opt.h"
36
+#include "libavutil/pixdesc.h"
37
+#include "libavutil/time.h"
38
+
39
+#include "avfilter.h"
40
+#include "formats.h"
41
+#include "internal.h"
42
+#include "video.h"
43
+
44
+static const char *const var_names[] = {
45
+    "PI",
46
+    "PHI",
47
+    "E",
48
+    "in_w",   "iw",
49
+    "in_h",   "ih",
50
+    "out_w",  "ow",
51
+    "out_h",  "oh",
52
+    "a", "dar",
53
+    "sar",
54
+    NULL
55
+};
56
+
57
+enum var_name {
58
+    VAR_PI,
59
+    VAR_PHI,
60
+    VAR_E,
61
+    VAR_IN_W,   VAR_IW,
62
+    VAR_IN_H,   VAR_IH,
63
+    VAR_OUT_W,  VAR_OW,
64
+    VAR_OUT_H,  VAR_OH,
65
+    VAR_A, VAR_DAR,
66
+    VAR_SAR,
67
+    VARS_NB
68
+};
69
+
70
+typedef struct QSVScaleContext {
71
+    const AVClass *class;
72
+
73
+    AVBufferRef *out_frames_ref;
74
+    /* a clone of the main session, used internally for scaling */
75
+    mfxSession   session;
76
+
77
+    mfxMemId *mem_ids_in;
78
+    int nb_mem_ids_in;
79
+
80
+    mfxMemId *mem_ids_out;
81
+    int nb_mem_ids_out;
82
+
83
+    mfxFrameSurface1 **surface_ptrs_in;
84
+    int             nb_surface_ptrs_in;
85
+
86
+    mfxFrameSurface1 **surface_ptrs_out;
87
+    int             nb_surface_ptrs_out;
88
+
89
+    mfxExtOpaqueSurfaceAlloc opaque_alloc;
90
+    mfxExtBuffer            *ext_buffers[1];
91
+
92
+    int shift_width, shift_height;
93
+
94
+    /**
95
+     * New dimensions. Special values are:
96
+     *   0 = original width/height
97
+     *  -1 = keep original aspect
98
+     */
99
+    int w, h;
100
+
101
+    /**
102
+     * Output sw format. AV_PIX_FMT_NONE for no conversion.
103
+     */
104
+    enum AVPixelFormat format;
105
+
106
+    char *w_expr;               ///< width  expression string
107
+    char *h_expr;               ///< height expression string
108
+    char *format_str;
109
+} QSVScaleContext;
110
+
111
+static int qsvscale_init(AVFilterContext *ctx)
112
+{
113
+    QSVScaleContext *s = ctx->priv;
114
+
115
+    if (!strcmp(s->format_str, "same")) {
116
+        s->format = AV_PIX_FMT_NONE;
117
+    } else {
118
+        s->format = av_get_pix_fmt(s->format_str);
119
+        if (s->format == AV_PIX_FMT_NONE) {
120
+            av_log(ctx, AV_LOG_ERROR, "Unrecognized pixel format: %s\n", s->format_str);
121
+            return AVERROR(EINVAL);
122
+        }
123
+    }
124
+
125
+    return 0;
126
+}
127
+
128
+static void qsvscale_uninit(AVFilterContext *ctx)
129
+{
130
+    QSVScaleContext *s = ctx->priv;
131
+
132
+    if (s->session) {
133
+        MFXClose(s->session);
134
+        s->session = NULL;
135
+    }
136
+    av_buffer_unref(&s->out_frames_ref);
137
+
138
+    av_freep(&s->mem_ids_in);
139
+    av_freep(&s->mem_ids_out);
140
+    s->nb_mem_ids_in  = 0;
141
+    s->nb_mem_ids_out = 0;
142
+
143
+    av_freep(&s->surface_ptrs_in);
144
+    av_freep(&s->surface_ptrs_out);
145
+    s->nb_surface_ptrs_in  = 0;
146
+    s->nb_surface_ptrs_out = 0;
147
+}
148
+
149
+static int qsvscale_query_formats(AVFilterContext *ctx)
150
+{
151
+    static const enum AVPixelFormat pixel_formats[] = {
152
+        AV_PIX_FMT_QSV, AV_PIX_FMT_NONE,
153
+    };
154
+    AVFilterFormats *pix_fmts  = ff_make_format_list(pixel_formats);
155
+
156
+    ff_set_common_formats(ctx, pix_fmts);
157
+
158
+    return 0;
159
+}
160
+
161
+static int init_out_pool(AVFilterContext *ctx,
162
+                         int out_width, int out_height)
163
+{
164
+    QSVScaleContext *s = ctx->priv;
165
+
166
+    AVHWFramesContext *in_frames_ctx;
167
+    AVHWFramesContext *out_frames_ctx;
168
+    AVQSVFramesContext *in_frames_hwctx;
169
+    AVQSVFramesContext *out_frames_hwctx;
170
+    enum AVPixelFormat in_format;
171
+    enum AVPixelFormat out_format;
172
+    int i, ret;
173
+
174
+    /* check that we have a hw context */
175
+    if (!ctx->inputs[0]->hw_frames_ctx) {
176
+        av_log(ctx, AV_LOG_ERROR, "No hw context provided on input\n");
177
+        return AVERROR(EINVAL);
178
+    }
179
+    in_frames_ctx   = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
180
+    in_frames_hwctx = in_frames_ctx->hwctx;
181
+
182
+    in_format     = in_frames_ctx->sw_format;
183
+    out_format    = (s->format == AV_PIX_FMT_NONE) ? in_format : s->format;
184
+
185
+    s->out_frames_ref = av_hwframe_ctx_alloc(in_frames_ctx->device_ref);
186
+    if (!s->out_frames_ref)
187
+        return AVERROR(ENOMEM);
188
+    out_frames_ctx   = (AVHWFramesContext*)s->out_frames_ref->data;
189
+    out_frames_hwctx = out_frames_ctx->hwctx;
190
+
191
+    out_frames_ctx->format            = AV_PIX_FMT_QSV;
192
+    out_frames_ctx->width             = FFALIGN(out_width,  32);
193
+    out_frames_ctx->height            = FFALIGN(out_height, 32);
194
+    out_frames_ctx->sw_format         = out_format;
195
+    out_frames_ctx->initial_pool_size = 32;
196
+
197
+    out_frames_hwctx->frame_type = in_frames_hwctx->frame_type;
198
+
199
+    ret = av_hwframe_ctx_init(s->out_frames_ref);
200
+    if (ret < 0)
201
+        return ret;
202
+
203
+    for (i = 0; i < out_frames_hwctx->nb_surfaces; i++) {
204
+        mfxFrameInfo *info = &out_frames_hwctx->surfaces[i].Info;
205
+        info->CropW = out_width;
206
+        info->CropH = out_height;
207
+    }
208
+
209
+    return 0;
210
+}
211
+
212
+static mfxStatus frame_alloc(mfxHDL pthis, mfxFrameAllocRequest *req,
213
+                             mfxFrameAllocResponse *resp)
214
+{
215
+    AVFilterContext *ctx = pthis;
216
+    QSVScaleContext   *s = ctx->priv;
217
+
218
+    if (!(req->Type & MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET) ||
219
+        !(req->Type & (MFX_MEMTYPE_FROM_VPPIN | MFX_MEMTYPE_FROM_VPPOUT)) ||
220
+        !(req->Type & MFX_MEMTYPE_EXTERNAL_FRAME))
221
+        return MFX_ERR_UNSUPPORTED;
222
+
223
+    if (req->Type & MFX_MEMTYPE_FROM_VPPIN) {
224
+        resp->mids           = s->mem_ids_in;
225
+        resp->NumFrameActual = s->nb_mem_ids_in;
226
+    } else {
227
+        resp->mids           = s->mem_ids_out;
228
+        resp->NumFrameActual = s->nb_mem_ids_out;
229
+    }
230
+
231
+    return MFX_ERR_NONE;
232
+}
233
+
234
+static mfxStatus frame_free(mfxHDL pthis, mfxFrameAllocResponse *resp)
235
+{
236
+    return MFX_ERR_NONE;
237
+}
238
+
239
+static mfxStatus frame_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
240
+{
241
+    return MFX_ERR_UNSUPPORTED;
242
+}
243
+
244
+static mfxStatus frame_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr)
245
+{
246
+    return MFX_ERR_UNSUPPORTED;
247
+}
248
+
249
+static mfxStatus frame_get_hdl(mfxHDL pthis, mfxMemId mid, mfxHDL *hdl)
250
+{
251
+    *hdl = mid;
252
+    return MFX_ERR_NONE;
253
+}
254
+
255
+static const mfxHandleType handle_types[] = {
256
+    MFX_HANDLE_VA_DISPLAY,
257
+    MFX_HANDLE_D3D9_DEVICE_MANAGER,
258
+    MFX_HANDLE_D3D11_DEVICE,
259
+};
260
+
261
+static int init_out_session(AVFilterContext *ctx)
262
+{
263
+
264
+    QSVScaleContext                   *s = ctx->priv;
265
+    AVHWFramesContext     *in_frames_ctx = (AVHWFramesContext*)ctx->inputs[0]->hw_frames_ctx->data;
266
+    AVHWFramesContext    *out_frames_ctx = (AVHWFramesContext*)s->out_frames_ref->data;
267
+    AVQSVFramesContext  *in_frames_hwctx = in_frames_ctx->hwctx;
268
+    AVQSVFramesContext *out_frames_hwctx = out_frames_ctx->hwctx;
269
+    AVQSVDeviceContext     *device_hwctx = in_frames_ctx->device_ctx->hwctx;
270
+
271
+    int opaque = !!(in_frames_hwctx->frame_type & MFX_MEMTYPE_OPAQUE_FRAME);
272
+
273
+    mfxHDL handle = NULL;
274
+    mfxHandleType handle_type;
275
+    mfxVersion ver;
276
+    mfxIMPL impl;
277
+    mfxVideoParam par;
278
+    mfxStatus err;
279
+    int i;
280
+
281
+    /* extract the properties of the "master" session given to us */
282
+    err = MFXQueryIMPL(device_hwctx->session, &impl);
283
+    if (err == MFX_ERR_NONE)
284
+        err = MFXQueryVersion(device_hwctx->session, &ver);
285
+    if (err != MFX_ERR_NONE) {
286
+        av_log(ctx, AV_LOG_ERROR, "Error querying the session attributes\n");
287
+        return AVERROR_UNKNOWN;
288
+    }
289
+
290
+    for (i = 0; i < FF_ARRAY_ELEMS(handle_types); i++) {
291
+        err = MFXVideoCORE_GetHandle(device_hwctx->session, handle_types[i], &handle);
292
+        if (err == MFX_ERR_NONE) {
293
+            handle_type = handle_types[i];
294
+            break;
295
+        }
296
+    }
297
+
298
+    /* create a "slave" session with those same properties, to be used for
299
+     * actual scaling */
300
+    err = MFXInit(impl, &ver, &s->session);
301
+    if (err != MFX_ERR_NONE) {
302
+        av_log(ctx, AV_LOG_ERROR, "Error initializing a session for scaling\n");
303
+        return AVERROR_UNKNOWN;
304
+    }
305
+
306
+    if (handle) {
307
+        err = MFXVideoCORE_SetHandle(s->session, handle_type, handle);
308
+        if (err != MFX_ERR_NONE)
309
+            return AVERROR_UNKNOWN;
310
+    }
311
+
312
+    memset(&par, 0, sizeof(par));
313
+
314
+    if (opaque) {
315
+        s->surface_ptrs_in = av_mallocz_array(in_frames_hwctx->nb_surfaces,
316
+                                              sizeof(*s->surface_ptrs_in));
317
+        if (!s->surface_ptrs_in)
318
+            return AVERROR(ENOMEM);
319
+        for (i = 0; i < in_frames_hwctx->nb_surfaces; i++)
320
+            s->surface_ptrs_in[i] = in_frames_hwctx->surfaces + i;
321
+        s->nb_surface_ptrs_in = in_frames_hwctx->nb_surfaces;
322
+
323
+        s->surface_ptrs_out = av_mallocz_array(out_frames_hwctx->nb_surfaces,
324
+                                               sizeof(*s->surface_ptrs_out));
325
+        if (!s->surface_ptrs_out)
326
+            return AVERROR(ENOMEM);
327
+        for (i = 0; i < out_frames_hwctx->nb_surfaces; i++)
328
+            s->surface_ptrs_out[i] = out_frames_hwctx->surfaces + i;
329
+        s->nb_surface_ptrs_out = out_frames_hwctx->nb_surfaces;
330
+
331
+        s->opaque_alloc.In.Surfaces   = s->surface_ptrs_in;
332
+        s->opaque_alloc.In.NumSurface = s->nb_surface_ptrs_in;
333
+        s->opaque_alloc.In.Type       = in_frames_hwctx->frame_type;
334
+
335
+        s->opaque_alloc.Out.Surfaces   = s->surface_ptrs_out;
336
+        s->opaque_alloc.Out.NumSurface = s->nb_surface_ptrs_out;
337
+        s->opaque_alloc.Out.Type       = out_frames_hwctx->frame_type;
338
+
339
+        s->opaque_alloc.Header.BufferId = MFX_EXTBUFF_OPAQUE_SURFACE_ALLOCATION;
340
+        s->opaque_alloc.Header.BufferSz = sizeof(s->opaque_alloc);
341
+
342
+        s->ext_buffers[0] = (mfxExtBuffer*)&s->opaque_alloc;
343
+
344
+        par.ExtParam    = s->ext_buffers;
345
+        par.NumExtParam = FF_ARRAY_ELEMS(s->ext_buffers);
346
+
347
+        par.IOPattern = MFX_IOPATTERN_IN_OPAQUE_MEMORY | MFX_IOPATTERN_OUT_OPAQUE_MEMORY;
348
+    } else {
349
+        mfxFrameAllocator frame_allocator = {
350
+            .pthis  = ctx,
351
+            .Alloc  = frame_alloc,
352
+            .Lock   = frame_lock,
353
+            .Unlock = frame_unlock,
354
+            .GetHDL = frame_get_hdl,
355
+            .Free   = frame_free,
356
+        };
357
+
358
+        s->mem_ids_in = av_mallocz_array(in_frames_hwctx->nb_surfaces,
359
+                                         sizeof(*s->mem_ids_in));
360
+        if (!s->mem_ids_in)
361
+            return AVERROR(ENOMEM);
362
+        for (i = 0; i < in_frames_hwctx->nb_surfaces; i++)
363
+            s->mem_ids_in[i] = in_frames_hwctx->surfaces[i].Data.MemId;
364
+        s->nb_mem_ids_in = in_frames_hwctx->nb_surfaces;
365
+
366
+        s->mem_ids_out = av_mallocz_array(out_frames_hwctx->nb_surfaces,
367
+                                          sizeof(*s->mem_ids_out));
368
+        if (!s->mem_ids_out)
369
+            return AVERROR(ENOMEM);
370
+        for (i = 0; i < out_frames_hwctx->nb_surfaces; i++)
371
+            s->mem_ids_out[i] = out_frames_hwctx->surfaces[i].Data.MemId;
372
+        s->nb_mem_ids_out = out_frames_hwctx->nb_surfaces;
373
+
374
+        err = MFXVideoCORE_SetFrameAllocator(s->session, &frame_allocator);
375
+        if (err != MFX_ERR_NONE)
376
+            return AVERROR_UNKNOWN;
377
+
378
+        par.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY | MFX_IOPATTERN_OUT_VIDEO_MEMORY;
379
+    }
380
+
381
+    par.AsyncDepth = 1;    // TODO async
382
+
383
+    par.vpp.In  = in_frames_hwctx->surfaces[0].Info;
384
+    par.vpp.Out = out_frames_hwctx->surfaces[0].Info;
385
+
386
+    /* Apparently VPP requires the frame rate to be set to some value, otherwise
387
+     * init will fail (probably for the framerate conversion filter). Since we
388
+     * are only doing scaling here, we just invent an arbitrary
389
+     * value */
390
+    par.vpp.In.FrameRateExtN  = 25;
391
+    par.vpp.In.FrameRateExtD  = 1;
392
+    par.vpp.Out.FrameRateExtN = 25;
393
+    par.vpp.Out.FrameRateExtD = 1;
394
+
395
+    err = MFXVideoVPP_Init(s->session, &par);
396
+    if (err != MFX_ERR_NONE) {
397
+        av_log(ctx, AV_LOG_ERROR, "Error opening the VPP for scaling\n");
398
+        return AVERROR_UNKNOWN;
399
+    }
400
+
401
+    return 0;
402
+}
403
+
404
+static int init_scale_session(AVFilterContext *ctx, int in_width, int in_height,
405
+                              int out_width, int out_height)
406
+{
407
+    QSVScaleContext *s = ctx->priv;
408
+
409
+    int ret;
410
+
411
+    qsvscale_uninit(ctx);
412
+
413
+    ret = init_out_pool(ctx, out_width, out_height);
414
+    if (ret < 0)
415
+        return ret;
416
+
417
+    ret = init_out_session(ctx);
418
+    if (ret < 0)
419
+        return ret;
420
+
421
+    av_buffer_unref(&ctx->outputs[0]->hw_frames_ctx);
422
+    ctx->outputs[0]->hw_frames_ctx = av_buffer_ref(s->out_frames_ref);
423
+    if (!ctx->outputs[0]->hw_frames_ctx)
424
+        return AVERROR(ENOMEM);
425
+
426
+    return 0;
427
+}
428
+
429
+static int qsvscale_config_props(AVFilterLink *outlink)
430
+{
431
+    AVFilterContext *ctx = outlink->src;
432
+    AVFilterLink *inlink = outlink->src->inputs[0];
433
+    QSVScaleContext  *s = ctx->priv;
434
+    int64_t w, h;
435
+    double var_values[VARS_NB], res;
436
+    char *expr;
437
+    int ret;
438
+
439
+    var_values[VAR_PI]    = M_PI;
440
+    var_values[VAR_PHI]   = M_PHI;
441
+    var_values[VAR_E]     = M_E;
442
+    var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
443
+    var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
444
+    var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
445
+    var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
446
+    var_values[VAR_A]     = (double) inlink->w / inlink->h;
447
+    var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
448
+        (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
449
+    var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
450
+
451
+    /* evaluate width and height */
452
+    av_expr_parse_and_eval(&res, (expr = s->w_expr),
453
+                           var_names, var_values,
454
+                           NULL, NULL, NULL, NULL, NULL, 0, ctx);
455
+    s->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
456
+    if ((ret = av_expr_parse_and_eval(&res, (expr = s->h_expr),
457
+                                      var_names, var_values,
458
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
459
+        goto fail;
460
+    s->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
461
+    /* evaluate again the width, as it may depend on the output height */
462
+    if ((ret = av_expr_parse_and_eval(&res, (expr = s->w_expr),
463
+                                      var_names, var_values,
464
+                                      NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
465
+        goto fail;
466
+    s->w = res;
467
+
468
+    w = s->w;
469
+    h = s->h;
470
+
471
+    /* sanity check params */
472
+    if (w <  -1 || h <  -1) {
473
+        av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
474
+        return AVERROR(EINVAL);
475
+    }
476
+    if (w == -1 && h == -1)
477
+        s->w = s->h = 0;
478
+
479
+    if (!(w = s->w))
480
+        w = inlink->w;
481
+    if (!(h = s->h))
482
+        h = inlink->h;
483
+    if (w == -1)
484
+        w = av_rescale(h, inlink->w, inlink->h);
485
+    if (h == -1)
486
+        h = av_rescale(w, inlink->h, inlink->w);
487
+
488
+    if (w > INT_MAX || h > INT_MAX ||
489
+        (h * inlink->w) > INT_MAX  ||
490
+        (w * inlink->h) > INT_MAX)
491
+        av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
492
+
493
+    outlink->w = w;
494
+    outlink->h = h;
495
+
496
+    ret = init_scale_session(ctx, inlink->w, inlink->h, w, h);
497
+    if (ret < 0)
498
+        return ret;
499
+
500
+    av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d -> w:%d h:%d\n",
501
+           inlink->w, inlink->h, outlink->w, outlink->h);
502
+
503
+    if (inlink->sample_aspect_ratio.num)
504
+        outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h*inlink->w,
505
+                                                             outlink->w*inlink->h},
506
+                                                inlink->sample_aspect_ratio);
507
+    else
508
+        outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
509
+
510
+    return 0;
511
+
512
+fail:
513
+    av_log(NULL, AV_LOG_ERROR,
514
+           "Error when evaluating the expression '%s'\n", expr);
515
+    return ret;
516
+}
517
+
518
+static int qsvscale_filter_frame(AVFilterLink *link, AVFrame *in)
519
+{
520
+    AVFilterContext             *ctx = link->dst;
521
+    QSVScaleContext               *s = ctx->priv;
522
+    AVFilterLink            *outlink = ctx->outputs[0];
523
+
524
+    mfxSyncPoint sync = NULL;
525
+    mfxStatus err;
526
+
527
+    AVFrame *out = NULL;
528
+    int ret = 0;
529
+
530
+    out = av_frame_alloc();
531
+    if (!out) {
532
+        ret = AVERROR(ENOMEM);
533
+        goto fail;
534
+    }
535
+
536
+    ret = av_hwframe_get_buffer(s->out_frames_ref, out, 0);
537
+    if (ret < 0)
538
+        goto fail;
539
+
540
+    do {
541
+        err = MFXVideoVPP_RunFrameVPPAsync(s->session,
542
+                                           (mfxFrameSurface1*)in->data[3],
543
+                                           (mfxFrameSurface1*)out->data[3],
544
+                                           NULL, &sync);
545
+        if (err == MFX_WRN_DEVICE_BUSY)
546
+            av_usleep(1);
547
+    } while (err == MFX_WRN_DEVICE_BUSY);
548
+
549
+    if (err < 0 || !sync) {
550
+        av_log(ctx, AV_LOG_ERROR, "Error during scaling\n");
551
+        ret = AVERROR_UNKNOWN;
552
+        goto fail;
553
+    }
554
+
555
+    do {
556
+        err = MFXVideoCORE_SyncOperation(s->session, sync, 1000);
557
+    } while (err == MFX_WRN_IN_EXECUTION);
558
+    if (err < 0) {
559
+        av_log(ctx, AV_LOG_ERROR, "Error synchronizing the operation: %d\n", err);
560
+        ret = AVERROR_UNKNOWN;
561
+        goto fail;
562
+    }
563
+
564
+    ret = av_frame_copy_props(out, in);
565
+    if (ret < 0)
566
+        goto fail;
567
+
568
+    out->width  = outlink->w;
569
+    out->height = outlink->h;
570
+
571
+    av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
572
+              (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
573
+              (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
574
+              INT_MAX);
575
+
576
+    av_frame_free(&in);
577
+    return ff_filter_frame(outlink, out);
578
+fail:
579
+    av_frame_free(&in);
580
+    av_frame_free(&out);
581
+    return ret;
582
+}
583
+
584
+#define OFFSET(x) offsetof(QSVScaleContext, x)
585
+#define FLAGS AV_OPT_FLAG_VIDEO_PARAM
586
+static const AVOption options[] = {
587
+    { "w",      "Output video width",  OFFSET(w_expr),     AV_OPT_TYPE_STRING, { .str = "iw"   }, .flags = FLAGS },
588
+    { "h",      "Output video height", OFFSET(h_expr),     AV_OPT_TYPE_STRING, { .str = "ih"   }, .flags = FLAGS },
589
+    { "format", "Output pixel format", OFFSET(format_str), AV_OPT_TYPE_STRING, { .str = "same" }, .flags = FLAGS },
590
+
591
+    { NULL },
592
+};
593
+
594
+static const AVClass qsvscale_class = {
595
+    .class_name = "qsvscale",
596
+    .item_name  = av_default_item_name,
597
+    .option     = options,
598
+    .version    = LIBAVUTIL_VERSION_INT,
599
+};
600
+
601
+static const AVFilterPad qsvscale_inputs[] = {
602
+    {
603
+        .name         = "default",
604
+        .type         = AVMEDIA_TYPE_VIDEO,
605
+        .filter_frame = qsvscale_filter_frame,
606
+    },
607
+    { NULL }
608
+};
609
+
610
+static const AVFilterPad qsvscale_outputs[] = {
611
+    {
612
+        .name         = "default",
613
+        .type         = AVMEDIA_TYPE_VIDEO,
614
+        .config_props = qsvscale_config_props,
615
+    },
616
+    { NULL }
617
+};
618
+
619
+AVFilter ff_vf_scale_qsv = {
620
+    .name      = "scale_qsv",
621
+    .description = NULL_IF_CONFIG_SMALL("QuickSync video scaling and format conversion"),
622
+
623
+    .init          = qsvscale_init,
624
+    .uninit        = qsvscale_uninit,
625
+    .query_formats = qsvscale_query_formats,
626
+
627
+    .priv_size = sizeof(QSVScaleContext),
628
+    .priv_class = &qsvscale_class,
629
+
630
+    .inputs    = qsvscale_inputs,
631
+    .outputs   = qsvscale_outputs,
632
+};