]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale.c
Merge commit '111367263af41c88a44bd763ceefc11d53a7f655'
[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, const char *args)
96 {
97     ScaleContext *scale = ctx->priv;
98 #if 1
99     static const char *shorthand[] = { "w", "h", NULL };
100     int ret;
101     const char *args0 = args;
102
103     if (args && (scale->size_str = av_get_token(&args, ":"))) {
104         if (av_parse_video_size(&scale->w, &scale->h, scale->size_str) < 0) {
105             av_freep(&scale->size_str);
106             args = args0;
107         } else if (*args)
108             args++;
109     }
110
111     if ((ret = av_opt_set_from_string(scale, args, shorthand, "=", ":")) < 0)
112         return ret;
113
114     if (scale->size_str && (scale->w_expr || scale->h_expr)) {
115         av_log(ctx, AV_LOG_ERROR,
116                "Size and width/height expressions cannot be set at the same time.\n");
117             return AVERROR(EINVAL);
118     }
119
120     if (scale->size_str) {
121         char buf[32];
122         if ((ret = av_parse_video_size(&scale->w, &scale->h, scale->size_str)) < 0) {
123             av_log(ctx, AV_LOG_ERROR,
124                    "Invalid size '%s'\n", scale->size_str);
125             return ret;
126         }
127         snprintf(buf, sizeof(buf)-1, "%d", scale->w);
128         av_opt_set(scale, "w", buf, 0);
129         snprintf(buf, sizeof(buf)-1, "%d", scale->h);
130         av_opt_set(scale, "h", buf, 0);
131     }
132     if (!scale->w_expr)
133         av_opt_set(scale, "w", "iw", 0);
134     if (!scale->h_expr)
135         av_opt_set(scale, "h", "ih", 0);
136
137     av_log(ctx, AV_LOG_VERBOSE, "w:%s h:%s flags:'%s' interl:%d\n",
138            scale->w_expr, scale->h_expr, (char *)av_x_if_null(scale->flags_str, ""), scale->interlaced);
139
140     scale->flags = SWS_BILINEAR;
141 #endif
142     if (scale->flags_str) {
143         const AVClass *class = sws_get_class();
144         const AVOption    *o = av_opt_find(&class, "sws_flags", NULL, 0,
145                                            AV_OPT_SEARCH_FAKE_OBJ);
146         int ret = av_opt_eval_flags(&class, o, scale->flags_str, &scale->flags);
147         if (ret < 0)
148             return ret;
149     }
150
151     return 0;
152 }
153
154 static av_cold void uninit(AVFilterContext *ctx)
155 {
156     ScaleContext *scale = ctx->priv;
157     sws_freeContext(scale->sws);
158     sws_freeContext(scale->isws[0]);
159     sws_freeContext(scale->isws[1]);
160     scale->sws = NULL;
161     av_opt_free(scale);
162 }
163
164 static int query_formats(AVFilterContext *ctx)
165 {
166     AVFilterFormats *formats;
167     enum AVPixelFormat pix_fmt;
168     int ret;
169
170     if (ctx->inputs[0]) {
171         formats = NULL;
172         for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
173             if (   sws_isSupportedInput(pix_fmt)
174                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
175                 ff_formats_unref(&formats);
176                 return ret;
177             }
178         ff_formats_ref(formats, &ctx->inputs[0]->out_formats);
179     }
180     if (ctx->outputs[0]) {
181         formats = NULL;
182         for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
183             if (   (sws_isSupportedOutput(pix_fmt) || pix_fmt == AV_PIX_FMT_PAL8)
184                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
185                 ff_formats_unref(&formats);
186                 return ret;
187             }
188         ff_formats_ref(formats, &ctx->outputs[0]->in_formats);
189     }
190
191     return 0;
192 }
193
194 static int config_props(AVFilterLink *outlink)
195 {
196     AVFilterContext *ctx = outlink->src;
197     AVFilterLink *inlink = outlink->src->inputs[0];
198     enum AVPixelFormat outfmt = outlink->format;
199     ScaleContext *scale = ctx->priv;
200     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
201     int64_t w, h;
202     double var_values[VARS_NB], res;
203     char *expr;
204     int ret;
205
206     var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
207     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
208     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
209     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
210     var_values[VAR_A]     = (double) inlink->w / inlink->h;
211     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
212         (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
213     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
214     var_values[VAR_HSUB]  = 1 << desc->log2_chroma_w;
215     var_values[VAR_VSUB]  = 1 << desc->log2_chroma_h;
216
217     /* evaluate width and height */
218     av_expr_parse_and_eval(&res, (expr = scale->w_expr),
219                            var_names, var_values,
220                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
221     scale->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
222     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->h_expr),
223                                       var_names, var_values,
224                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
225         goto fail;
226     scale->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
227     /* evaluate again the width, as it may depend on the output height */
228     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->w_expr),
229                                       var_names, var_values,
230                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
231         goto fail;
232     scale->w = res;
233
234     w = scale->w;
235     h = scale->h;
236
237     /* sanity check params */
238     if (w <  -1 || h <  -1) {
239         av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
240         return AVERROR(EINVAL);
241     }
242     if (w == -1 && h == -1)
243         scale->w = scale->h = 0;
244
245     if (!(w = scale->w))
246         w = inlink->w;
247     if (!(h = scale->h))
248         h = inlink->h;
249     if (w == -1)
250         w = av_rescale(h, inlink->w, inlink->h);
251     if (h == -1)
252         h = av_rescale(w, inlink->h, inlink->w);
253
254     if (w > INT_MAX || h > INT_MAX ||
255         (h * inlink->w) > INT_MAX  ||
256         (w * inlink->h) > INT_MAX)
257         av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
258
259     outlink->w = w;
260     outlink->h = h;
261
262     /* TODO: make algorithm configurable */
263
264     scale->input_is_pal = desc->flags & PIX_FMT_PAL ||
265                           desc->flags & PIX_FMT_PSEUDOPAL;
266     if (outfmt == AV_PIX_FMT_PAL8) outfmt = AV_PIX_FMT_BGR8;
267     scale->output_is_pal = av_pix_fmt_desc_get(outfmt)->flags & PIX_FMT_PAL ||
268                            av_pix_fmt_desc_get(outfmt)->flags & PIX_FMT_PSEUDOPAL;
269
270     if (scale->sws)
271         sws_freeContext(scale->sws);
272     if (inlink->w == outlink->w && inlink->h == outlink->h &&
273         inlink->format == outlink->format)
274         scale->sws = NULL;
275     else {
276         scale->sws = sws_getContext(inlink ->w, inlink ->h, inlink ->format,
277                                     outlink->w, outlink->h, outfmt,
278                                     scale->flags, NULL, NULL, NULL);
279         if (scale->isws[0])
280             sws_freeContext(scale->isws[0]);
281         scale->isws[0] = sws_getContext(inlink ->w, inlink ->h/2, inlink ->format,
282                                         outlink->w, outlink->h/2, outfmt,
283                                         scale->flags, NULL, NULL, NULL);
284         if (scale->isws[1])
285             sws_freeContext(scale->isws[1]);
286         scale->isws[1] = sws_getContext(inlink ->w, inlink ->h/2, inlink ->format,
287                                         outlink->w, outlink->h/2, outfmt,
288                                         scale->flags, NULL, NULL, NULL);
289         if (!scale->sws || !scale->isws[0] || !scale->isws[1])
290             return AVERROR(EINVAL);
291     }
292
293     if (inlink->sample_aspect_ratio.num){
294         outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h * inlink->w, outlink->w * inlink->h}, inlink->sample_aspect_ratio);
295     } else
296         outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
297
298     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",
299            inlink ->w, inlink ->h, av_get_pix_fmt_name( inlink->format),
300            inlink->sample_aspect_ratio.num, inlink->sample_aspect_ratio.den,
301            outlink->w, outlink->h, av_get_pix_fmt_name(outlink->format),
302            outlink->sample_aspect_ratio.num, outlink->sample_aspect_ratio.den,
303            scale->flags);
304     return 0;
305
306 fail:
307     av_log(NULL, AV_LOG_ERROR,
308            "Error when evaluating the expression '%s'.\n"
309            "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
310            expr, scale->w_expr, scale->h_expr);
311     return ret;
312 }
313
314 static int scale_slice(AVFilterLink *link, AVFrame *out_buf, AVFrame *cur_pic, struct SwsContext *sws, int y, int h, int mul, int field)
315 {
316     ScaleContext *scale = link->dst->priv;
317     const uint8_t *in[4];
318     uint8_t *out[4];
319     int in_stride[4],out_stride[4];
320     int i;
321
322     for(i=0; i<4; i++){
323         int vsub= ((i+1)&2) ? scale->vsub : 0;
324          in_stride[i] = cur_pic->linesize[i] * mul;
325         out_stride[i] = out_buf->linesize[i] * mul;
326          in[i] = cur_pic->data[i] + ((y>>vsub)+field) * cur_pic->linesize[i];
327         out[i] = out_buf->data[i] +            field  * out_buf->linesize[i];
328     }
329     if(scale->input_is_pal)
330          in[1] = cur_pic->data[1];
331     if(scale->output_is_pal)
332         out[1] = out_buf->data[1];
333
334     return sws_scale(sws, in, in_stride, y/mul, h,
335                          out,out_stride);
336 }
337
338 static int filter_frame(AVFilterLink *link, AVFrame *in)
339 {
340     ScaleContext *scale = link->dst->priv;
341     AVFilterLink *outlink = link->dst->outputs[0];
342     AVFrame *out;
343     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
344     char buf[32];
345
346     if(   in->width  != link->w
347        || in->height != link->h
348        || in->format != link->format) {
349         int ret;
350         snprintf(buf, sizeof(buf)-1, "%d", outlink->w);
351         av_opt_set(scale, "w", buf, 0);
352         snprintf(buf, sizeof(buf)-1, "%d", outlink->h);
353         av_opt_set(scale, "h", buf, 0);
354
355         link->dst->inputs[0]->format = in->format;
356         link->dst->inputs[0]->w      = in->width;
357         link->dst->inputs[0]->h      = in->height;
358
359         if ((ret = config_props(outlink)) < 0)
360             return ret;
361     }
362
363     if (!scale->sws)
364         return ff_filter_frame(outlink, in);
365
366     scale->hsub = desc->log2_chroma_w;
367     scale->vsub = desc->log2_chroma_h;
368
369     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
370     if (!out) {
371         av_frame_free(&in);
372         return AVERROR(ENOMEM);
373     }
374
375     av_frame_copy_props(out, in);
376     out->width  = outlink->w;
377     out->height = outlink->h;
378
379     if(scale->output_is_pal)
380         avpriv_set_systematic_pal2((uint32_t*)out->data[1], outlink->format == AV_PIX_FMT_PAL8 ? AV_PIX_FMT_BGR8 : outlink->format);
381
382     av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
383               (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
384               (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
385               INT_MAX);
386
387     if(scale->interlaced>0 || (scale->interlaced<0 && in->interlaced_frame)){
388         scale_slice(link, out, in, scale->isws[0], 0, (link->h+1)/2, 2, 0);
389         scale_slice(link, out, in, scale->isws[1], 0,  link->h   /2, 2, 1);
390     }else{
391         scale_slice(link, out, in, scale->sws, 0, link->h, 1, 0);
392     }
393
394     av_frame_free(&in);
395     return ff_filter_frame(outlink, out);
396 }
397
398 #define OFFSET(x) offsetof(ScaleContext, x)
399 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
400
401 static const AVOption scale_options[] = {
402     { "w",     "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING, { .str = "iw" },       .flags = FLAGS },
403     { "width", "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING, { .str = "iw" },       .flags = FLAGS },
404     { "h",     "Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING, { .str = "ih" },       .flags = FLAGS },
405     { "height","Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING, { .str = "ih" },       .flags = FLAGS },
406     { "flags", "Flags to pass to libswscale", OFFSET(flags_str), AV_OPT_TYPE_STRING, { .str = "bilinear" }, .flags = FLAGS },
407     { "interl", "set interlacing", OFFSET(interlaced), AV_OPT_TYPE_INT, {.i64 = 0 }, -1, 1, FLAGS },
408     { "size",   "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
409     { "s",      "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
410     { NULL },
411 };
412
413 AVFILTER_DEFINE_CLASS(scale);
414
415 static const AVFilterPad avfilter_vf_scale_inputs[] = {
416     {
417         .name        = "default",
418         .type        = AVMEDIA_TYPE_VIDEO,
419         .filter_frame = filter_frame,
420     },
421     { NULL }
422 };
423
424 static const AVFilterPad avfilter_vf_scale_outputs[] = {
425     {
426         .name         = "default",
427         .type         = AVMEDIA_TYPE_VIDEO,
428         .config_props = config_props,
429     },
430     { NULL }
431 };
432
433 AVFilter avfilter_vf_scale = {
434     .name      = "scale",
435     .description = NULL_IF_CONFIG_SMALL("Scale the input video to width:height size and/or convert the image format."),
436
437     .init      = init,
438     .uninit    = uninit,
439
440     .query_formats = query_formats,
441
442     .priv_size = sizeof(ScaleContext),
443     .priv_class = &scale_class,
444
445     .inputs    = avfilter_vf_scale_inputs,
446     .outputs   = avfilter_vf_scale_outputs,
447 };