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