]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale_vaapi.c
doc/muxers: remove confusing example for segment muxer option clocktime_wrap_duration
[ffmpeg] / libavfilter / vf_scale_vaapi.c
1 /*
2  * This file is part of FFmpeg.
3  *
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.
8  *
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.
13  *
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
17  */
18
19 #include <string.h>
20
21 #include <va/va.h>
22 #include <va/va_vpp.h>
23
24 #include "libavutil/avassert.h"
25 #include "libavutil/hwcontext.h"
26 #include "libavutil/hwcontext_vaapi.h"
27 #include "libavutil/mem.h"
28 #include "libavutil/opt.h"
29 #include "libavutil/pixdesc.h"
30
31 #include "avfilter.h"
32 #include "formats.h"
33 #include "internal.h"
34 #include "scale.h"
35
36 typedef struct ScaleVAAPIContext {
37     const AVClass *class;
38
39     AVVAAPIDeviceContext *hwctx;
40     AVBufferRef *device_ref;
41
42     int valid_ids;
43     VAConfigID  va_config;
44     VAContextID va_context;
45
46     AVBufferRef       *input_frames_ref;
47     AVHWFramesContext *input_frames;
48
49     AVBufferRef       *output_frames_ref;
50     AVHWFramesContext *output_frames;
51
52     char *output_format_string;
53     enum AVPixelFormat output_format;
54
55     char *w_expr;      // width expression string
56     char *h_expr;      // height expression string
57
58     int output_width;  // computed width
59     int output_height; // computed height
60 } ScaleVAAPIContext;
61
62
63 static int scale_vaapi_query_formats(AVFilterContext *avctx)
64 {
65     enum AVPixelFormat pix_fmts[] = {
66         AV_PIX_FMT_VAAPI, AV_PIX_FMT_NONE,
67     };
68
69     ff_formats_ref(ff_make_format_list(pix_fmts),
70                    &avctx->inputs[0]->out_formats);
71     ff_formats_ref(ff_make_format_list(pix_fmts),
72                    &avctx->outputs[0]->in_formats);
73
74     return 0;
75 }
76
77 static int scale_vaapi_pipeline_uninit(ScaleVAAPIContext *ctx)
78 {
79     if (ctx->va_context != VA_INVALID_ID) {
80         vaDestroyContext(ctx->hwctx->display, ctx->va_context);
81         ctx->va_context = VA_INVALID_ID;
82     }
83
84     if (ctx->va_config != VA_INVALID_ID) {
85         vaDestroyConfig(ctx->hwctx->display, ctx->va_config);
86         ctx->va_config = VA_INVALID_ID;
87     }
88
89     av_buffer_unref(&ctx->output_frames_ref);
90     av_buffer_unref(&ctx->device_ref);
91     ctx->hwctx = 0;
92
93     return 0;
94 }
95
96 static int scale_vaapi_config_input(AVFilterLink *inlink)
97 {
98     AVFilterContext *avctx = inlink->dst;
99     ScaleVAAPIContext *ctx = avctx->priv;
100
101     scale_vaapi_pipeline_uninit(ctx);
102
103     if (!inlink->hw_frames_ctx) {
104         av_log(avctx, AV_LOG_ERROR, "A hardware frames reference is "
105                "required to associate the processing device.\n");
106         return AVERROR(EINVAL);
107     }
108
109     ctx->input_frames_ref = av_buffer_ref(inlink->hw_frames_ctx);
110     ctx->input_frames = (AVHWFramesContext*)ctx->input_frames_ref->data;
111
112     return 0;
113 }
114
115 static int scale_vaapi_config_output(AVFilterLink *outlink)
116 {
117     AVFilterLink *inlink = outlink->src->inputs[0];
118     AVFilterContext *avctx = outlink->src;
119     ScaleVAAPIContext *ctx = avctx->priv;
120     AVVAAPIHWConfig *hwconfig = NULL;
121     AVHWFramesConstraints *constraints = NULL;
122     AVVAAPIFramesContext *va_frames;
123     VAStatus vas;
124     int err, i;
125
126     scale_vaapi_pipeline_uninit(ctx);
127
128     ctx->device_ref = av_buffer_ref(ctx->input_frames->device_ref);
129     ctx->hwctx = ((AVHWDeviceContext*)ctx->device_ref->data)->hwctx;
130
131     av_assert0(ctx->va_config == VA_INVALID_ID);
132     vas = vaCreateConfig(ctx->hwctx->display, VAProfileNone,
133                          VAEntrypointVideoProc, 0, 0, &ctx->va_config);
134     if (vas != VA_STATUS_SUCCESS) {
135         av_log(ctx, AV_LOG_ERROR, "Failed to create processing pipeline "
136                "config: %d (%s).\n", vas, vaErrorStr(vas));
137         err = AVERROR(EIO);
138         goto fail;
139     }
140
141     hwconfig = av_hwdevice_hwconfig_alloc(ctx->device_ref);
142     if (!hwconfig) {
143         err = AVERROR(ENOMEM);
144         goto fail;
145     }
146     hwconfig->config_id = ctx->va_config;
147
148     constraints = av_hwdevice_get_hwframe_constraints(ctx->device_ref,
149                                                       hwconfig);
150     if (!constraints) {
151         err = AVERROR(ENOMEM);
152         goto fail;
153     }
154
155     if (ctx->output_format == AV_PIX_FMT_NONE)
156         ctx->output_format = ctx->input_frames->sw_format;
157     if (constraints->valid_sw_formats) {
158         for (i = 0; constraints->valid_sw_formats[i] != AV_PIX_FMT_NONE; i++) {
159             if (ctx->output_format == constraints->valid_sw_formats[i])
160                 break;
161         }
162         if (constraints->valid_sw_formats[i] == AV_PIX_FMT_NONE) {
163             av_log(ctx, AV_LOG_ERROR, "Hardware does not support output "
164                    "format %s.\n", av_get_pix_fmt_name(ctx->output_format));
165             err = AVERROR(EINVAL);
166             goto fail;
167         }
168     }
169
170     if ((err = ff_scale_eval_dimensions(ctx,
171                                         ctx->w_expr, ctx->h_expr,
172                                         inlink, outlink,
173                                         &ctx->output_width, &ctx->output_height)) < 0)
174         goto fail;
175
176     if (ctx->output_width  < constraints->min_width  ||
177         ctx->output_height < constraints->min_height ||
178         ctx->output_width  > constraints->max_width  ||
179         ctx->output_height > constraints->max_height) {
180         av_log(ctx, AV_LOG_ERROR, "Hardware does not support scaling to "
181                "size %dx%d (constraints: width %d-%d height %d-%d).\n",
182                ctx->output_width, ctx->output_height,
183                constraints->min_width,  constraints->max_width,
184                constraints->min_height, constraints->max_height);
185         err = AVERROR(EINVAL);
186         goto fail;
187     }
188
189     ctx->output_frames_ref = av_hwframe_ctx_alloc(ctx->device_ref);
190     if (!ctx->output_frames_ref) {
191         av_log(ctx, AV_LOG_ERROR, "Failed to create HW frame context "
192                "for output.\n");
193         err = AVERROR(ENOMEM);
194         goto fail;
195     }
196
197     ctx->output_frames = (AVHWFramesContext*)ctx->output_frames_ref->data;
198
199     ctx->output_frames->format    = AV_PIX_FMT_VAAPI;
200     ctx->output_frames->sw_format = ctx->output_format;
201     ctx->output_frames->width     = ctx->output_width;
202     ctx->output_frames->height    = ctx->output_height;
203
204     // The number of output frames we need is determined by what follows
205     // the filter.  If it's an encoder with complex frame reference
206     // structures then this could be very high.
207     ctx->output_frames->initial_pool_size = 10;
208
209     err = av_hwframe_ctx_init(ctx->output_frames_ref);
210     if (err < 0) {
211         av_log(ctx, AV_LOG_ERROR, "Failed to initialise VAAPI frame "
212                "context for output: %d\n", err);
213         goto fail;
214     }
215
216     va_frames = ctx->output_frames->hwctx;
217
218     av_assert0(ctx->va_context == VA_INVALID_ID);
219     vas = vaCreateContext(ctx->hwctx->display, ctx->va_config,
220                           ctx->output_width, ctx->output_height,
221                           VA_PROGRESSIVE,
222                           va_frames->surface_ids, va_frames->nb_surfaces,
223                           &ctx->va_context);
224     if (vas != VA_STATUS_SUCCESS) {
225         av_log(ctx, AV_LOG_ERROR, "Failed to create processing pipeline "
226                "context: %d (%s).\n", vas, vaErrorStr(vas));
227         return AVERROR(EIO);
228     }
229
230     outlink->w = ctx->output_width;
231     outlink->h = ctx->output_height;
232
233     outlink->hw_frames_ctx = av_buffer_ref(ctx->output_frames_ref);
234     if (!outlink->hw_frames_ctx) {
235         err = AVERROR(ENOMEM);
236         goto fail;
237     }
238
239     av_freep(&hwconfig);
240     av_hwframe_constraints_free(&constraints);
241     return 0;
242
243 fail:
244     av_buffer_unref(&ctx->output_frames_ref);
245     av_freep(&hwconfig);
246     av_hwframe_constraints_free(&constraints);
247     return err;
248 }
249
250 static int vaapi_proc_colour_standard(enum AVColorSpace av_cs)
251 {
252     switch(av_cs) {
253 #define CS(av, va) case AVCOL_SPC_ ## av: return VAProcColorStandard ## va;
254         CS(BT709,     BT709);
255         CS(BT470BG,   BT601);
256         CS(SMPTE170M, SMPTE170M);
257         CS(SMPTE240M, SMPTE240M);
258 #undef CS
259     default:
260         return VAProcColorStandardNone;
261     }
262 }
263
264 static int scale_vaapi_filter_frame(AVFilterLink *inlink, AVFrame *input_frame)
265 {
266     AVFilterContext *avctx = inlink->dst;
267     AVFilterLink *outlink = avctx->outputs[0];
268     ScaleVAAPIContext *ctx = avctx->priv;
269     AVFrame *output_frame = NULL;
270     VASurfaceID input_surface, output_surface;
271     VAProcPipelineParameterBuffer params;
272     VABufferID params_id;
273     VAStatus vas;
274     int err;
275
276     av_log(ctx, AV_LOG_DEBUG, "Filter input: %s, %ux%u (%"PRId64").\n",
277            av_get_pix_fmt_name(input_frame->format),
278            input_frame->width, input_frame->height, input_frame->pts);
279
280     if (ctx->va_context == VA_INVALID_ID)
281         return AVERROR(EINVAL);
282
283     input_surface = (VASurfaceID)(uintptr_t)input_frame->data[3];
284     av_log(ctx, AV_LOG_DEBUG, "Using surface %#x for scale input.\n",
285            input_surface);
286
287     output_frame = av_frame_alloc();
288     if (!output_frame) {
289         av_log(ctx, AV_LOG_ERROR, "Failed to allocate output frame.");
290         err = AVERROR(ENOMEM);
291         goto fail;
292     }
293
294     err = av_hwframe_get_buffer(ctx->output_frames_ref, output_frame, 0);
295     if (err < 0) {
296         av_log(ctx, AV_LOG_ERROR, "Failed to get surface for "
297                "output: %d\n.", err);
298     }
299
300     output_surface = (VASurfaceID)(uintptr_t)output_frame->data[3];
301     av_log(ctx, AV_LOG_DEBUG, "Using surface %#x for scale output.\n",
302            output_surface);
303
304     memset(&params, 0, sizeof(params));
305
306     params.surface = input_surface;
307     params.surface_region = 0;
308     params.surface_color_standard =
309         vaapi_proc_colour_standard(input_frame->colorspace);
310
311     params.output_region = 0;
312     params.output_background_color = 0xff000000;
313     params.output_color_standard = params.surface_color_standard;
314
315     params.pipeline_flags = 0;
316     params.filter_flags = VA_FILTER_SCALING_HQ;
317
318     vas = vaBeginPicture(ctx->hwctx->display,
319                          ctx->va_context, output_surface);
320     if (vas != VA_STATUS_SUCCESS) {
321         av_log(ctx, AV_LOG_ERROR, "Failed to attach new picture: "
322                "%d (%s).\n", vas, vaErrorStr(vas));
323         err = AVERROR(EIO);
324         goto fail;
325     }
326
327     vas = vaCreateBuffer(ctx->hwctx->display, ctx->va_context,
328                          VAProcPipelineParameterBufferType,
329                          sizeof(params), 1, &params, &params_id);
330     if (vas != VA_STATUS_SUCCESS) {
331         av_log(ctx, AV_LOG_ERROR, "Failed to create parameter buffer: "
332                "%d (%s).\n", vas, vaErrorStr(vas));
333         err = AVERROR(EIO);
334         goto fail_after_begin;
335     }
336     av_log(ctx, AV_LOG_DEBUG, "Pipeline parameter buffer is %#x.\n",
337            params_id);
338
339     vas = vaRenderPicture(ctx->hwctx->display, ctx->va_context,
340                           &params_id, 1);
341     if (vas != VA_STATUS_SUCCESS) {
342         av_log(ctx, AV_LOG_ERROR, "Failed to render parameter buffer: "
343                "%d (%s).\n", vas, vaErrorStr(vas));
344         err = AVERROR(EIO);
345         goto fail_after_begin;
346     }
347
348     vas = vaEndPicture(ctx->hwctx->display, ctx->va_context);
349     if (vas != VA_STATUS_SUCCESS) {
350         av_log(ctx, AV_LOG_ERROR, "Failed to start picture processing: "
351                "%d (%s).\n", vas, vaErrorStr(vas));
352         err = AVERROR(EIO);
353         goto fail_after_render;
354     }
355
356     if (ctx->hwctx->driver_quirks &
357         AV_VAAPI_DRIVER_QUIRK_RENDER_PARAM_BUFFERS) {
358         vas = vaDestroyBuffer(ctx->hwctx->display, params_id);
359         if (vas != VA_STATUS_SUCCESS) {
360             av_log(ctx, AV_LOG_ERROR, "Failed to free parameter buffer: "
361                    "%d (%s).\n", vas, vaErrorStr(vas));
362             // And ignore.
363         }
364     }
365
366     av_frame_copy_props(output_frame, input_frame);
367     av_frame_free(&input_frame);
368
369     av_log(ctx, AV_LOG_DEBUG, "Filter output: %s, %ux%u (%"PRId64").\n",
370            av_get_pix_fmt_name(output_frame->format),
371            output_frame->width, output_frame->height, output_frame->pts);
372
373     return ff_filter_frame(outlink, output_frame);
374
375     // We want to make sure that if vaBeginPicture has been called, we also
376     // call vaRenderPicture and vaEndPicture.  These calls may well fail or
377     // do something else nasty, but once we're in this failure case there
378     // isn't much else we can do.
379 fail_after_begin:
380     vaRenderPicture(ctx->hwctx->display, ctx->va_context, &params_id, 1);
381 fail_after_render:
382     vaEndPicture(ctx->hwctx->display, ctx->va_context);
383 fail:
384     av_frame_free(&input_frame);
385     av_frame_free(&output_frame);
386     return err;
387 }
388
389 static av_cold int scale_vaapi_init(AVFilterContext *avctx)
390 {
391     ScaleVAAPIContext *ctx = avctx->priv;
392
393     ctx->va_config  = VA_INVALID_ID;
394     ctx->va_context = VA_INVALID_ID;
395     ctx->valid_ids  = 1;
396
397     if (ctx->output_format_string) {
398         ctx->output_format = av_get_pix_fmt(ctx->output_format_string);
399         if (ctx->output_format == AV_PIX_FMT_NONE) {
400             av_log(ctx, AV_LOG_ERROR, "Invalid output format.\n");
401             return AVERROR(EINVAL);
402         }
403     } else {
404         // Use the input format once that is configured.
405         ctx->output_format = AV_PIX_FMT_NONE;
406     }
407
408     return 0;
409 }
410
411 static av_cold void scale_vaapi_uninit(AVFilterContext *avctx)
412 {
413     ScaleVAAPIContext *ctx = avctx->priv;
414
415     if (ctx->valid_ids)
416         scale_vaapi_pipeline_uninit(ctx);
417
418     av_buffer_unref(&ctx->input_frames_ref);
419     av_buffer_unref(&ctx->output_frames_ref);
420     av_buffer_unref(&ctx->device_ref);
421 }
422
423
424 #define OFFSET(x) offsetof(ScaleVAAPIContext, x)
425 #define FLAGS (AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM)
426 static const AVOption scale_vaapi_options[] = {
427     { "w", "Output video width",
428       OFFSET(w_expr), AV_OPT_TYPE_STRING, {.str = "iw"}, .flags = FLAGS },
429     { "h", "Output video height",
430       OFFSET(h_expr), AV_OPT_TYPE_STRING, {.str = "ih"}, .flags = FLAGS },
431     { "format", "Output video format (software format of hardware frames)",
432       OFFSET(output_format_string), AV_OPT_TYPE_STRING, .flags = FLAGS },
433     { NULL },
434 };
435
436 static const AVClass scale_vaapi_class = {
437     .class_name = "scale_vaapi",
438     .item_name  = av_default_item_name,
439     .option     = scale_vaapi_options,
440     .version    = LIBAVUTIL_VERSION_INT,
441 };
442
443 static const AVFilterPad scale_vaapi_inputs[] = {
444     {
445         .name         = "default",
446         .type         = AVMEDIA_TYPE_VIDEO,
447         .filter_frame = &scale_vaapi_filter_frame,
448         .config_props = &scale_vaapi_config_input,
449     },
450     { NULL }
451 };
452
453 static const AVFilterPad scale_vaapi_outputs[] = {
454     {
455         .name = "default",
456         .type = AVMEDIA_TYPE_VIDEO,
457         .config_props = &scale_vaapi_config_output,
458     },
459     { NULL }
460 };
461
462 AVFilter ff_vf_scale_vaapi = {
463     .name          = "scale_vaapi",
464     .description   = NULL_IF_CONFIG_SMALL("Scale to/from VAAPI surfaces."),
465     .priv_size     = sizeof(ScaleVAAPIContext),
466     .init          = &scale_vaapi_init,
467     .uninit        = &scale_vaapi_uninit,
468     .query_formats = &scale_vaapi_query_formats,
469     .inputs        = scale_vaapi_inputs,
470     .outputs       = scale_vaapi_outputs,
471     .priv_class    = &scale_vaapi_class,
472 };