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