]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale.c
lavf/matroskaenc: return an error for unsupported types.
[ffmpeg] / libavfilter / vf_scale.c
1 /*
2  * Copyright (c) 2007 Bobby Bingham
3  *
4  * This file is part of FFmpeg.
5  *
6  * FFmpeg is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * FFmpeg is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with FFmpeg; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19  */
20
21 /**
22  * @file
23  * scale video filter
24  */
25
26 #include <stdio.h>
27 #include <string.h>
28
29 #include "avfilter.h"
30 #include "formats.h"
31 #include "internal.h"
32 #include "video.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/eval.h"
35 #include "libavutil/internal.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/opt.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/imgutils.h"
41 #include "libavutil/avassert.h"
42 #include "libswscale/swscale.h"
43
44 static const char *const var_names[] = {
45     "in_w",   "iw",
46     "in_h",   "ih",
47     "out_w",  "ow",
48     "out_h",  "oh",
49     "a",
50     "sar",
51     "dar",
52     "hsub",
53     "vsub",
54     NULL
55 };
56
57 enum var_name {
58     VAR_IN_W,   VAR_IW,
59     VAR_IN_H,   VAR_IH,
60     VAR_OUT_W,  VAR_OW,
61     VAR_OUT_H,  VAR_OH,
62     VAR_A,
63     VAR_SAR,
64     VAR_DAR,
65     VAR_HSUB,
66     VAR_VSUB,
67     VARS_NB
68 };
69
70 typedef struct {
71     const AVClass *class;
72     struct SwsContext *sws;     ///< software scaler context
73     struct SwsContext *isws[2]; ///< software scaler context for interlaced material
74
75     /**
76      * New dimensions. Special values are:
77      *   0 = original width/height
78      *  -1 = keep original aspect
79      */
80     int w, h;
81     char *size_str;
82     unsigned int flags;         ///sws flags
83
84     int hsub, vsub;             ///< chroma subsampling
85     int slice_y;                ///< top of current output slice
86     int input_is_pal;           ///< set to 1 if the input format is paletted
87     int output_is_pal;          ///< set to 1 if the output format is paletted
88     int interlaced;
89
90     char *w_expr;               ///< width  expression string
91     char *h_expr;               ///< height expression string
92     char *flags_str;
93 } ScaleContext;
94
95 static av_cold int init(AVFilterContext *ctx)
96 {
97     ScaleContext *scale = ctx->priv;
98     int ret;
99
100     if (scale->size_str && (scale->w_expr || scale->h_expr)) {
101         av_log(ctx, AV_LOG_ERROR,
102                "Size and width/height expressions cannot be set at the same time.\n");
103             return AVERROR(EINVAL);
104     }
105
106     if (scale->w_expr && !scale->h_expr)
107         FFSWAP(char *, scale->w_expr, scale->size_str);
108
109     if (scale->size_str) {
110         char buf[32];
111         if ((ret = av_parse_video_size(&scale->w, &scale->h, scale->size_str)) < 0) {
112             av_log(ctx, AV_LOG_ERROR,
113                    "Invalid size '%s'\n", scale->size_str);
114             return ret;
115         }
116         snprintf(buf, sizeof(buf)-1, "%d", scale->w);
117         av_opt_set(scale, "w", buf, 0);
118         snprintf(buf, sizeof(buf)-1, "%d", scale->h);
119         av_opt_set(scale, "h", buf, 0);
120     }
121     if (!scale->w_expr)
122         av_opt_set(scale, "w", "iw", 0);
123     if (!scale->h_expr)
124         av_opt_set(scale, "h", "ih", 0);
125
126     av_log(ctx, AV_LOG_VERBOSE, "w:%s h:%s flags:'%s' interl:%d\n",
127            scale->w_expr, scale->h_expr, (char *)av_x_if_null(scale->flags_str, ""), scale->interlaced);
128
129     scale->flags = SWS_BILINEAR;
130
131     if (scale->flags_str) {
132         const AVClass *class = sws_get_class();
133         const AVOption    *o = av_opt_find(&class, "sws_flags", NULL, 0,
134                                            AV_OPT_SEARCH_FAKE_OBJ);
135         int ret = av_opt_eval_flags(&class, o, scale->flags_str, &scale->flags);
136         if (ret < 0)
137             return ret;
138     }
139
140     return 0;
141 }
142
143 static av_cold void uninit(AVFilterContext *ctx)
144 {
145     ScaleContext *scale = ctx->priv;
146     sws_freeContext(scale->sws);
147     sws_freeContext(scale->isws[0]);
148     sws_freeContext(scale->isws[1]);
149     scale->sws = NULL;
150     av_opt_free(scale);
151 }
152
153 static int query_formats(AVFilterContext *ctx)
154 {
155     AVFilterFormats *formats;
156     enum AVPixelFormat pix_fmt;
157     int ret;
158
159     if (ctx->inputs[0]) {
160         formats = NULL;
161         for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
162             if (   sws_isSupportedInput(pix_fmt)
163                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
164                 ff_formats_unref(&formats);
165                 return ret;
166             }
167         ff_formats_ref(formats, &ctx->inputs[0]->out_formats);
168     }
169     if (ctx->outputs[0]) {
170         formats = NULL;
171         for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
172             if (   (sws_isSupportedOutput(pix_fmt) || pix_fmt == AV_PIX_FMT_PAL8)
173                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
174                 ff_formats_unref(&formats);
175                 return ret;
176             }
177         ff_formats_ref(formats, &ctx->outputs[0]->in_formats);
178     }
179
180     return 0;
181 }
182
183 static int config_props(AVFilterLink *outlink)
184 {
185     AVFilterContext *ctx = outlink->src;
186     AVFilterLink *inlink = outlink->src->inputs[0];
187     enum AVPixelFormat outfmt = outlink->format;
188     ScaleContext *scale = ctx->priv;
189     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
190     int64_t w, h;
191     double var_values[VARS_NB], res;
192     char *expr;
193     int ret;
194
195     var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
196     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
197     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
198     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
199     var_values[VAR_A]     = (double) inlink->w / inlink->h;
200     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
201         (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
202     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
203     var_values[VAR_HSUB]  = 1 << desc->log2_chroma_w;
204     var_values[VAR_VSUB]  = 1 << desc->log2_chroma_h;
205
206     /* evaluate width and height */
207     av_expr_parse_and_eval(&res, (expr = scale->w_expr),
208                            var_names, var_values,
209                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
210     scale->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
211     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->h_expr),
212                                       var_names, var_values,
213                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
214         goto fail;
215     scale->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
216     /* evaluate again the width, as it may depend on the output height */
217     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->w_expr),
218                                       var_names, var_values,
219                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
220         goto fail;
221     scale->w = res;
222
223     w = scale->w;
224     h = scale->h;
225
226     /* sanity check params */
227     if (w <  -1 || h <  -1) {
228         av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
229         return AVERROR(EINVAL);
230     }
231     if (w == -1 && h == -1)
232         scale->w = scale->h = 0;
233
234     if (!(w = scale->w))
235         w = inlink->w;
236     if (!(h = scale->h))
237         h = inlink->h;
238     if (w == -1)
239         w = av_rescale(h, inlink->w, inlink->h);
240     if (h == -1)
241         h = av_rescale(w, inlink->h, inlink->w);
242
243     if (w > INT_MAX || h > INT_MAX ||
244         (h * inlink->w) > INT_MAX  ||
245         (w * inlink->h) > INT_MAX)
246         av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
247
248     outlink->w = w;
249     outlink->h = h;
250
251     /* TODO: make algorithm configurable */
252
253     scale->input_is_pal = desc->flags & PIX_FMT_PAL ||
254                           desc->flags & PIX_FMT_PSEUDOPAL;
255     if (outfmt == AV_PIX_FMT_PAL8) outfmt = AV_PIX_FMT_BGR8;
256     scale->output_is_pal = av_pix_fmt_desc_get(outfmt)->flags & PIX_FMT_PAL ||
257                            av_pix_fmt_desc_get(outfmt)->flags & PIX_FMT_PSEUDOPAL;
258
259     if (scale->sws)
260         sws_freeContext(scale->sws);
261     if (inlink->w == outlink->w && inlink->h == outlink->h &&
262         inlink->format == outlink->format)
263         scale->sws = NULL;
264     else {
265         scale->sws = sws_getContext(inlink ->w, inlink ->h, inlink ->format,
266                                     outlink->w, outlink->h, outfmt,
267                                     scale->flags, NULL, NULL, NULL);
268         if (scale->isws[0])
269             sws_freeContext(scale->isws[0]);
270         scale->isws[0] = sws_getContext(inlink ->w, inlink ->h/2, inlink ->format,
271                                         outlink->w, outlink->h/2, outfmt,
272                                         scale->flags, NULL, NULL, NULL);
273         if (scale->isws[1])
274             sws_freeContext(scale->isws[1]);
275         scale->isws[1] = sws_getContext(inlink ->w, inlink ->h/2, inlink ->format,
276                                         outlink->w, outlink->h/2, outfmt,
277                                         scale->flags, NULL, NULL, NULL);
278         if (!scale->sws || !scale->isws[0] || !scale->isws[1])
279             return AVERROR(EINVAL);
280     }
281
282     if (inlink->sample_aspect_ratio.num){
283         outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h * inlink->w, outlink->w * inlink->h}, inlink->sample_aspect_ratio);
284     } else
285         outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
286
287     av_log(ctx, AV_LOG_VERBOSE, "w:%d h:%d fmt:%s sar:%d/%d -> w:%d h:%d fmt:%s sar:%d/%d flags:0x%0x\n",
288            inlink ->w, inlink ->h, av_get_pix_fmt_name( inlink->format),
289            inlink->sample_aspect_ratio.num, inlink->sample_aspect_ratio.den,
290            outlink->w, outlink->h, av_get_pix_fmt_name(outlink->format),
291            outlink->sample_aspect_ratio.num, outlink->sample_aspect_ratio.den,
292            scale->flags);
293     return 0;
294
295 fail:
296     av_log(NULL, AV_LOG_ERROR,
297            "Error when evaluating the expression '%s'.\n"
298            "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
299            expr, scale->w_expr, scale->h_expr);
300     return ret;
301 }
302
303 static int scale_slice(AVFilterLink *link, AVFrame *out_buf, AVFrame *cur_pic, struct SwsContext *sws, int y, int h, int mul, int field)
304 {
305     ScaleContext *scale = link->dst->priv;
306     const uint8_t *in[4];
307     uint8_t *out[4];
308     int in_stride[4],out_stride[4];
309     int i;
310
311     for(i=0; i<4; i++){
312         int vsub= ((i+1)&2) ? scale->vsub : 0;
313          in_stride[i] = cur_pic->linesize[i] * mul;
314         out_stride[i] = out_buf->linesize[i] * mul;
315          in[i] = cur_pic->data[i] + ((y>>vsub)+field) * cur_pic->linesize[i];
316         out[i] = out_buf->data[i] +            field  * out_buf->linesize[i];
317     }
318     if(scale->input_is_pal)
319          in[1] = cur_pic->data[1];
320     if(scale->output_is_pal)
321         out[1] = out_buf->data[1];
322
323     return sws_scale(sws, in, in_stride, y/mul, h,
324                          out,out_stride);
325 }
326
327 static int filter_frame(AVFilterLink *link, AVFrame *in)
328 {
329     ScaleContext *scale = link->dst->priv;
330     AVFilterLink *outlink = link->dst->outputs[0];
331     AVFrame *out;
332     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
333     char buf[32];
334
335     if(   in->width  != link->w
336        || in->height != link->h
337        || in->format != link->format) {
338         int ret;
339         snprintf(buf, sizeof(buf)-1, "%d", outlink->w);
340         av_opt_set(scale, "w", buf, 0);
341         snprintf(buf, sizeof(buf)-1, "%d", outlink->h);
342         av_opt_set(scale, "h", buf, 0);
343
344         link->dst->inputs[0]->format = in->format;
345         link->dst->inputs[0]->w      = in->width;
346         link->dst->inputs[0]->h      = in->height;
347
348         if ((ret = config_props(outlink)) < 0)
349             return ret;
350     }
351
352     if (!scale->sws)
353         return ff_filter_frame(outlink, in);
354
355     scale->hsub = desc->log2_chroma_w;
356     scale->vsub = desc->log2_chroma_h;
357
358     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
359     if (!out) {
360         av_frame_free(&in);
361         return AVERROR(ENOMEM);
362     }
363
364     av_frame_copy_props(out, in);
365     out->width  = outlink->w;
366     out->height = outlink->h;
367
368     if(scale->output_is_pal)
369         avpriv_set_systematic_pal2((uint32_t*)out->data[1], outlink->format == AV_PIX_FMT_PAL8 ? AV_PIX_FMT_BGR8 : outlink->format);
370
371     av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
372               (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
373               (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
374               INT_MAX);
375
376     if(scale->interlaced>0 || (scale->interlaced<0 && in->interlaced_frame)){
377         scale_slice(link, out, in, scale->isws[0], 0, (link->h+1)/2, 2, 0);
378         scale_slice(link, out, in, scale->isws[1], 0,  link->h   /2, 2, 1);
379     }else{
380         scale_slice(link, out, in, scale->sws, 0, link->h, 1, 0);
381     }
382
383     av_frame_free(&in);
384     return ff_filter_frame(outlink, out);
385 }
386
387 #define OFFSET(x) offsetof(ScaleContext, x)
388 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
389
390 static const AVOption scale_options[] = {
391     { "w",     "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
392     { "width", "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
393     { "h",     "Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
394     { "height","Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
395     { "flags", "Flags to pass to libswscale", OFFSET(flags_str), AV_OPT_TYPE_STRING, { .str = "bilinear" }, .flags = FLAGS },
396     { "interl", "set interlacing", OFFSET(interlaced), AV_OPT_TYPE_INT, {.i64 = 0 }, -1, 1, FLAGS },
397     { "size",   "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
398     { "s",      "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
399     { NULL },
400 };
401
402 AVFILTER_DEFINE_CLASS(scale);
403
404 static const AVFilterPad avfilter_vf_scale_inputs[] = {
405     {
406         .name        = "default",
407         .type        = AVMEDIA_TYPE_VIDEO,
408         .filter_frame = filter_frame,
409     },
410     { NULL }
411 };
412
413 static const AVFilterPad avfilter_vf_scale_outputs[] = {
414     {
415         .name         = "default",
416         .type         = AVMEDIA_TYPE_VIDEO,
417         .config_props = config_props,
418     },
419     { NULL }
420 };
421
422 AVFilter avfilter_vf_scale = {
423     .name      = "scale",
424     .description = NULL_IF_CONFIG_SMALL("Scale the input video to width:height size and/or convert the image format."),
425
426     .init      = init,
427     .uninit    = uninit,
428
429     .query_formats = query_formats,
430
431     .priv_size = sizeof(ScaleContext),
432     .priv_class = &scale_class,
433
434     .inputs    = avfilter_vf_scale_inputs,
435     .outputs   = avfilter_vf_scale_outputs,
436 };