]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale.c
Merge remote-tracking branch 'qatar/master'
[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 "avfilter.h"
27 #include "libavutil/avstring.h"
28 #include "libavutil/eval.h"
29 #include "libavutil/mathematics.h"
30 #include "libavutil/pixdesc.h"
31 #include "libavutil/imgutils.h"
32 #include "libavutil/avassert.h"
33 #include "libswscale/swscale.h"
34
35 static const char *const var_names[] = {
36     "in_w",   "iw",
37     "in_h",   "ih",
38     "out_w",  "ow",
39     "out_h",  "oh",
40     "a",
41     "sar",
42     "dar",
43     "hsub",
44     "vsub",
45     NULL
46 };
47
48 enum var_name {
49     VAR_IN_W,   VAR_IW,
50     VAR_IN_H,   VAR_IH,
51     VAR_OUT_W,  VAR_OW,
52     VAR_OUT_H,  VAR_OH,
53     VAR_A,
54     VAR_SAR,
55     VAR_DAR,
56     VAR_HSUB,
57     VAR_VSUB,
58     VARS_NB
59 };
60
61 typedef struct {
62     struct SwsContext *sws;     ///< software scaler context
63     struct SwsContext *isws[2]; ///< software scaler context for interlaced material
64
65     /**
66      * New dimensions. Special values are:
67      *   0 = original width/height
68      *  -1 = keep original aspect
69      */
70     int w, h;
71     unsigned int flags;         ///sws flags
72
73     int hsub, vsub;             ///< chroma subsampling
74     int slice_y;                ///< top of current output slice
75     int input_is_pal;           ///< set to 1 if the input format is paletted
76     int output_is_pal;          ///< set to 1 if the output format is paletted
77     int interlaced;
78
79     char w_expr[256];           ///< width  expression string
80     char h_expr[256];           ///< height expression string
81 } ScaleContext;
82
83 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
84 {
85     ScaleContext *scale = ctx->priv;
86     const char *p;
87
88     av_strlcpy(scale->w_expr, "iw", sizeof(scale->w_expr));
89     av_strlcpy(scale->h_expr, "ih", sizeof(scale->h_expr));
90
91     scale->flags = SWS_BILINEAR;
92     if (args) {
93         sscanf(args, "%255[^:]:%255[^:]", scale->w_expr, scale->h_expr);
94         p = strstr(args,"flags=");
95         if (p) scale->flags = strtoul(p+6, NULL, 0);
96         if(strstr(args,"interl=1")){
97             scale->interlaced=1;
98         }else if(strstr(args,"interl=-1"))
99             scale->interlaced=-1;
100     }
101
102     return 0;
103 }
104
105 static av_cold void uninit(AVFilterContext *ctx)
106 {
107     ScaleContext *scale = ctx->priv;
108     sws_freeContext(scale->sws);
109     sws_freeContext(scale->isws[0]);
110     sws_freeContext(scale->isws[1]);
111     scale->sws = NULL;
112 }
113
114 static int query_formats(AVFilterContext *ctx)
115 {
116     AVFilterFormats *formats;
117     enum PixelFormat pix_fmt;
118     int ret;
119
120     if (ctx->inputs[0]) {
121         formats = NULL;
122         for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
123             if (   sws_isSupportedInput(pix_fmt)
124                 && (ret = avfilter_add_format(&formats, pix_fmt)) < 0) {
125                 avfilter_formats_unref(&formats);
126                 return ret;
127             }
128         avfilter_formats_ref(formats, &ctx->inputs[0]->out_formats);
129     }
130     if (ctx->outputs[0]) {
131         formats = NULL;
132         for (pix_fmt = 0; pix_fmt < PIX_FMT_NB; pix_fmt++)
133             if (   (sws_isSupportedOutput(pix_fmt) || pix_fmt == PIX_FMT_PAL8)
134                 && (ret = avfilter_add_format(&formats, pix_fmt)) < 0) {
135                 avfilter_formats_unref(&formats);
136                 return ret;
137             }
138         avfilter_formats_ref(formats, &ctx->outputs[0]->in_formats);
139     }
140
141     return 0;
142 }
143
144 static int config_props(AVFilterLink *outlink)
145 {
146     AVFilterContext *ctx = outlink->src;
147     AVFilterLink *inlink = outlink->src->inputs[0];
148     enum PixelFormat outfmt = outlink->format;
149     ScaleContext *scale = ctx->priv;
150     int64_t w, h;
151     double var_values[VARS_NB], res;
152     char *expr;
153     int ret;
154
155     var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
156     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
157     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
158     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
159     var_values[VAR_A]     = (float) inlink->w / inlink->h;
160     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
161         (float) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
162     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
163     var_values[VAR_HSUB]  = 1<<av_pix_fmt_descriptors[inlink->format].log2_chroma_w;
164     var_values[VAR_VSUB]  = 1<<av_pix_fmt_descriptors[inlink->format].log2_chroma_h;
165
166     /* evaluate width and height */
167     av_expr_parse_and_eval(&res, (expr = scale->w_expr),
168                            var_names, var_values,
169                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
170     scale->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
171     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->h_expr),
172                                       var_names, var_values,
173                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
174         goto fail;
175     scale->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
176     /* evaluate again the width, as it may depend on the output height */
177     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->w_expr),
178                                       var_names, var_values,
179                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
180         goto fail;
181     scale->w = res;
182
183     w = scale->w;
184     h = scale->h;
185
186     /* sanity check params */
187     if (w <  -1 || h <  -1) {
188         av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
189         return AVERROR(EINVAL);
190     }
191     if (w == -1 && h == -1)
192         scale->w = scale->h = 0;
193
194     if (!(w = scale->w))
195         w = inlink->w;
196     if (!(h = scale->h))
197         h = inlink->h;
198     if (w == -1)
199         w = av_rescale(h, inlink->w, inlink->h);
200     if (h == -1)
201         h = av_rescale(w, inlink->h, inlink->w);
202
203     if (w > INT_MAX || h > INT_MAX ||
204         (h * inlink->w) > INT_MAX  ||
205         (w * inlink->h) > INT_MAX)
206         av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
207
208     outlink->w = w;
209     outlink->h = h;
210
211     /* TODO: make algorithm configurable */
212
213     scale->input_is_pal = av_pix_fmt_descriptors[inlink->format].flags & PIX_FMT_PAL ||
214                           av_pix_fmt_descriptors[inlink->format].flags & PIX_FMT_PSEUDOPAL;
215     if (outfmt == PIX_FMT_PAL8) outfmt = PIX_FMT_BGR8;
216     scale->output_is_pal = av_pix_fmt_descriptors[outfmt].flags & PIX_FMT_PAL ||
217                            av_pix_fmt_descriptors[outfmt].flags & PIX_FMT_PSEUDOPAL;
218
219     if (scale->sws)
220         sws_freeContext(scale->sws);
221     if (inlink->w == outlink->w && inlink->h == outlink->h &&
222         inlink->format == outlink->format)
223         scale->sws = NULL;
224     else {
225         scale->sws = sws_getContext(inlink ->w, inlink ->h, inlink ->format,
226                                     outlink->w, outlink->h, outfmt,
227                                     scale->flags, NULL, NULL, NULL);
228         if (scale->isws[0])
229             sws_freeContext(scale->isws[0]);
230         scale->isws[0] = sws_getContext(inlink ->w, inlink ->h/2, inlink ->format,
231                                         outlink->w, outlink->h/2, outfmt,
232                                         scale->flags, NULL, NULL, NULL);
233         if (scale->isws[1])
234             sws_freeContext(scale->isws[1]);
235         scale->isws[1] = sws_getContext(inlink ->w, inlink ->h/2, inlink ->format,
236                                         outlink->w, outlink->h/2, outfmt,
237                                         scale->flags, NULL, NULL, NULL);
238         if (!scale->sws || !scale->isws[0] || !scale->isws[1])
239             return AVERROR(EINVAL);
240     }
241
242     if (inlink->sample_aspect_ratio.num){
243         outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h * inlink->w, outlink->w * inlink->h}, inlink->sample_aspect_ratio);
244     } else
245         outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
246
247     av_log(ctx, AV_LOG_INFO, "w:%d h:%d fmt:%s sar:%d/%d -> w:%d h:%d fmt:%s sar:%d/%d flags:0x%0x\n",
248            inlink ->w, inlink ->h, av_pix_fmt_descriptors[ inlink->format].name,
249            inlink->sample_aspect_ratio.num, inlink->sample_aspect_ratio.den,
250            outlink->w, outlink->h, av_pix_fmt_descriptors[outlink->format].name,
251            outlink->sample_aspect_ratio.num, outlink->sample_aspect_ratio.den,
252            scale->flags);
253     return 0;
254
255 fail:
256     av_log(NULL, AV_LOG_ERROR,
257            "Error when evaluating the expression '%s'.\n"
258            "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
259            expr, scale->w_expr, scale->h_expr);
260     return ret;
261 }
262
263 static void start_frame(AVFilterLink *link, AVFilterBufferRef *picref)
264 {
265     ScaleContext *scale = link->dst->priv;
266     AVFilterLink *outlink = link->dst->outputs[0];
267     AVFilterBufferRef *outpicref;
268
269     if (!scale->sws) {
270         avfilter_start_frame(outlink, avfilter_ref_buffer(picref, ~0));
271         return;
272     }
273
274     scale->hsub = av_pix_fmt_descriptors[link->format].log2_chroma_w;
275     scale->vsub = av_pix_fmt_descriptors[link->format].log2_chroma_h;
276
277     outpicref = avfilter_get_video_buffer(outlink, AV_PERM_WRITE|AV_PERM_ALIGN, outlink->w, outlink->h);
278     avfilter_copy_buffer_ref_props(outpicref, picref);
279     outpicref->video->w = outlink->w;
280     outpicref->video->h = outlink->h;
281
282     outlink->out_buf = outpicref;
283     if(scale->output_is_pal)
284         ff_set_systematic_pal2(outpicref->data[1], outlink->format == PIX_FMT_PAL8 ? PIX_FMT_BGR8 : outlink->format);
285
286     av_reduce(&outpicref->video->sample_aspect_ratio.num, &outpicref->video->sample_aspect_ratio.den,
287               (int64_t)picref->video->sample_aspect_ratio.num * outlink->h * link->w,
288               (int64_t)picref->video->sample_aspect_ratio.den * outlink->w * link->h,
289               INT_MAX);
290
291     scale->slice_y = 0;
292     avfilter_start_frame(outlink, avfilter_ref_buffer(outpicref, ~0));
293 }
294
295 static int scale_slice(AVFilterLink *link, struct SwsContext *sws, int y, int h, int mul, int field)
296 {
297     ScaleContext *scale = link->dst->priv;
298     AVFilterBufferRef *cur_pic = link->cur_buf;
299     AVFilterBufferRef *out_buf = link->dst->outputs[0]->out_buf;
300     const uint8_t *in[4];
301     uint8_t *out[4];
302     int in_stride[4],out_stride[4];
303     int i;
304
305     for(i=0; i<4; i++){
306         int vsub= ((i+1)&2) ? scale->vsub : 0;
307          in_stride[i] = cur_pic->linesize[i] * mul;
308         out_stride[i] = out_buf->linesize[i] * mul;
309          in[i] = cur_pic->data[i] + ((y>>vsub)+field) * cur_pic->linesize[i];
310         out[i] = out_buf->data[i] +            field  * out_buf->linesize[i];
311     }
312     if(scale->input_is_pal)
313          in[1] = cur_pic->data[1];
314     if(scale->output_is_pal)
315         out[1] = out_buf->data[1];
316
317     return sws_scale(sws, in, in_stride, y/mul, h,
318                          out,out_stride);
319 }
320
321 static void draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
322 {
323     ScaleContext *scale = link->dst->priv;
324     int out_h;
325
326     if (!scale->sws) {
327         avfilter_draw_slice(link->dst->outputs[0], y, h, slice_dir);
328         return;
329     }
330
331     if (scale->slice_y == 0 && slice_dir == -1)
332         scale->slice_y = link->dst->outputs[0]->h;
333
334     if(scale->interlaced>0 || (scale->interlaced<0 && link->cur_buf->video->interlaced)){
335         av_assert0(y%(2<<scale->vsub) == 0);
336         out_h = scale_slice(link, scale->isws[0], y, (h+1)/2, 2, 0);
337         out_h+= scale_slice(link, scale->isws[1], y,  h   /2, 2, 1);
338     }else{
339         out_h = scale_slice(link, scale->sws, y, h, 1, 0);
340     }
341
342     if (slice_dir == -1)
343         scale->slice_y -= out_h;
344     avfilter_draw_slice(link->dst->outputs[0], scale->slice_y, out_h, slice_dir);
345     if (slice_dir == 1)
346         scale->slice_y += out_h;
347 }
348
349 AVFilter avfilter_vf_scale = {
350     .name      = "scale",
351     .description = NULL_IF_CONFIG_SMALL("Scale the input video to width:height size and/or convert the image format."),
352
353     .init      = init,
354     .uninit    = uninit,
355
356     .query_formats = query_formats,
357
358     .priv_size = sizeof(ScaleContext),
359
360     .inputs    = (const AVFilterPad[]) {{ .name       = "default",
361                                     .type             = AVMEDIA_TYPE_VIDEO,
362                                     .start_frame      = start_frame,
363                                     .draw_slice       = draw_slice,
364                                     .min_perms        = AV_PERM_READ, },
365                                   { .name = NULL}},
366     .outputs   = (const AVFilterPad[]) {{ .name       = "default",
367                                     .type             = AVMEDIA_TYPE_VIDEO,
368                                     .config_props     = config_props, },
369                                   { .name = NULL}},
370 };