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