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