]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale.c
avfilter/scale: separate exprs parse and eval
[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 "scale_eval.h"
33 #include "video.h"
34 #include "libavutil/avstring.h"
35 #include "libavutil/eval.h"
36 #include "libavutil/internal.h"
37 #include "libavutil/mathematics.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/parseutils.h"
40 #include "libavutil/pixdesc.h"
41 #include "libavutil/imgutils.h"
42 #include "libavutil/avassert.h"
43 #include "libswscale/swscale.h"
44
45 static const char *const var_names[] = {
46     "in_w",   "iw",
47     "in_h",   "ih",
48     "out_w",  "ow",
49     "out_h",  "oh",
50     "a",
51     "sar",
52     "dar",
53     "hsub",
54     "vsub",
55     "ohsub",
56     "ovsub",
57     NULL
58 };
59
60 enum var_name {
61     VAR_IN_W,   VAR_IW,
62     VAR_IN_H,   VAR_IH,
63     VAR_OUT_W,  VAR_OW,
64     VAR_OUT_H,  VAR_OH,
65     VAR_A,
66     VAR_SAR,
67     VAR_DAR,
68     VAR_HSUB,
69     VAR_VSUB,
70     VAR_OHSUB,
71     VAR_OVSUB,
72     VARS_NB
73 };
74
75 /**
76  * This must be kept in sync with var_names so that it is always a
77  * complete list of var_names with the scale2ref specific names
78  * appended. scale2ref values must appear in the order they appear
79  * in the var_name_scale2ref enum but also be below all of the
80  * non-scale2ref specific values.
81  */
82 static const char *const var_names_scale2ref[] = {
83     "in_w",   "iw",
84     "in_h",   "ih",
85     "out_w",  "ow",
86     "out_h",  "oh",
87     "a",
88     "sar",
89     "dar",
90     "hsub",
91     "vsub",
92     "ohsub",
93     "ovsub",
94     "main_w",
95     "main_h",
96     "main_a",
97     "main_sar",
98     "main_dar", "mdar",
99     "main_hsub",
100     "main_vsub",
101     NULL
102 };
103
104 enum var_name_scale2ref {
105     VAR_S2R_MAIN_W,
106     VAR_S2R_MAIN_H,
107     VAR_S2R_MAIN_A,
108     VAR_S2R_MAIN_SAR,
109     VAR_S2R_MAIN_DAR, VAR_S2R_MDAR,
110     VAR_S2R_MAIN_HSUB,
111     VAR_S2R_MAIN_VSUB,
112     VARS_S2R_NB
113 };
114
115 enum EvalMode {
116     EVAL_MODE_INIT,
117     EVAL_MODE_FRAME,
118     EVAL_MODE_NB
119 };
120
121 typedef struct ScaleContext {
122     const AVClass *class;
123     struct SwsContext *sws;     ///< software scaler context
124     struct SwsContext *isws[2]; ///< software scaler context for interlaced material
125     AVDictionary *opts;
126
127     /**
128      * New dimensions. Special values are:
129      *   0 = original width/height
130      *  -1 = keep original aspect
131      *  -N = try to keep aspect but make sure it is divisible by N
132      */
133     int w, h;
134     char *size_str;
135     unsigned int flags;         ///sws flags
136     double param[2];            // sws params
137
138     int hsub, vsub;             ///< chroma subsampling
139     int slice_y;                ///< top of current output slice
140     int input_is_pal;           ///< set to 1 if the input format is paletted
141     int output_is_pal;          ///< set to 1 if the output format is paletted
142     int interlaced;
143
144     char *w_expr;               ///< width  expression string
145     char *h_expr;               ///< height expression string
146     AVExpr *w_pexpr;
147     AVExpr *h_pexpr;
148     double var_values[VARS_NB + VARS_S2R_NB];
149
150     char *flags_str;
151
152     char *in_color_matrix;
153     char *out_color_matrix;
154
155     int in_range;
156     int out_range;
157
158     int out_h_chr_pos;
159     int out_v_chr_pos;
160     int in_h_chr_pos;
161     int in_v_chr_pos;
162
163     int force_original_aspect_ratio;
164     int force_divisible_by;
165
166     int nb_slices;
167
168     int eval_mode;              ///< expression evaluation mode
169
170 } ScaleContext;
171
172 AVFilter ff_vf_scale2ref;
173
174 static int config_props(AVFilterLink *outlink);
175
176 static int scale_parse_expr(AVFilterContext *ctx, char *str_expr, AVExpr **pexpr_ptr, const char *var, const char *args)
177 {
178     ScaleContext *scale = ctx->priv;
179     int ret, is_inited = 0;
180     char *old_str_expr = NULL;
181     AVExpr *old_pexpr = NULL;
182     const char scale2ref = ctx->filter == &ff_vf_scale2ref;
183     const char *const *names = scale2ref ? var_names_scale2ref : var_names;
184
185     if (str_expr) {
186         old_str_expr = av_strdup(str_expr);
187         if (!old_str_expr)
188             return AVERROR(ENOMEM);
189         av_opt_set(scale, var, args, 0);
190     }
191
192     if (*pexpr_ptr) {
193         old_pexpr = *pexpr_ptr;
194         *pexpr_ptr = NULL;
195         is_inited = 1;
196     }
197
198     ret = av_expr_parse(pexpr_ptr, args, names,
199                         NULL, NULL, NULL, NULL, 0, ctx);
200     if (ret < 0) {
201         av_log(ctx, AV_LOG_ERROR, "Cannot parse expression for %s: '%s'\n", var, args);
202         goto revert;
203     }
204
205     if (is_inited && (ret = config_props(ctx->outputs[0])) < 0)
206         goto revert;
207
208     av_expr_free(old_pexpr);
209     old_pexpr = NULL;
210     av_freep(&old_str_expr);
211
212     return 0;
213
214 revert:
215     av_expr_free(*pexpr_ptr);
216     *pexpr_ptr = NULL;
217     if (old_str_expr) {
218         av_opt_set(scale, var, old_str_expr, 0);
219         av_free(old_str_expr);
220     }
221     if (old_pexpr)
222         *pexpr_ptr = old_pexpr;
223
224     return ret;
225 }
226
227 static av_cold int init_dict(AVFilterContext *ctx, AVDictionary **opts)
228 {
229     ScaleContext *scale = ctx->priv;
230     int ret;
231
232     if (scale->size_str && (scale->w_expr || scale->h_expr)) {
233         av_log(ctx, AV_LOG_ERROR,
234                "Size and width/height expressions cannot be set at the same time.\n");
235             return AVERROR(EINVAL);
236     }
237
238     if (scale->w_expr && !scale->h_expr)
239         FFSWAP(char *, scale->w_expr, scale->size_str);
240
241     if (scale->size_str) {
242         char buf[32];
243         if ((ret = av_parse_video_size(&scale->w, &scale->h, scale->size_str)) < 0) {
244             av_log(ctx, AV_LOG_ERROR,
245                    "Invalid size '%s'\n", scale->size_str);
246             return ret;
247         }
248         snprintf(buf, sizeof(buf)-1, "%d", scale->w);
249         av_opt_set(scale, "w", buf, 0);
250         snprintf(buf, sizeof(buf)-1, "%d", scale->h);
251         av_opt_set(scale, "h", buf, 0);
252     }
253     if (!scale->w_expr)
254         av_opt_set(scale, "w", "iw", 0);
255     if (!scale->h_expr)
256         av_opt_set(scale, "h", "ih", 0);
257
258     ret = scale_parse_expr(ctx, NULL, &scale->w_pexpr, "width", scale->w_expr);
259     if (ret < 0)
260         return ret;
261
262     ret = scale_parse_expr(ctx, NULL, &scale->h_pexpr, "height", scale->h_expr);
263     if (ret < 0)
264         return ret;
265
266     av_log(ctx, AV_LOG_VERBOSE, "w:%s h:%s flags:'%s' interl:%d\n",
267            scale->w_expr, scale->h_expr, (char *)av_x_if_null(scale->flags_str, ""), scale->interlaced);
268
269     scale->flags = 0;
270
271     if (scale->flags_str) {
272         const AVClass *class = sws_get_class();
273         const AVOption    *o = av_opt_find(&class, "sws_flags", NULL, 0,
274                                            AV_OPT_SEARCH_FAKE_OBJ);
275         int ret = av_opt_eval_flags(&class, o, scale->flags_str, &scale->flags);
276         if (ret < 0)
277             return ret;
278     }
279     scale->opts = *opts;
280     *opts = NULL;
281
282     return 0;
283 }
284
285 static av_cold void uninit(AVFilterContext *ctx)
286 {
287     ScaleContext *scale = ctx->priv;
288     av_expr_free(scale->w_pexpr);
289     av_expr_free(scale->h_pexpr);
290     scale->w_pexpr = scale->h_pexpr = NULL;
291     sws_freeContext(scale->sws);
292     sws_freeContext(scale->isws[0]);
293     sws_freeContext(scale->isws[1]);
294     scale->sws = NULL;
295     av_dict_free(&scale->opts);
296 }
297
298 static int query_formats(AVFilterContext *ctx)
299 {
300     AVFilterFormats *formats;
301     enum AVPixelFormat pix_fmt;
302     int ret;
303
304     if (ctx->inputs[0]) {
305         const AVPixFmtDescriptor *desc = NULL;
306         formats = NULL;
307         while ((desc = av_pix_fmt_desc_next(desc))) {
308             pix_fmt = av_pix_fmt_desc_get_id(desc);
309             if ((sws_isSupportedInput(pix_fmt) ||
310                  sws_isSupportedEndiannessConversion(pix_fmt))
311                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
312                 return ret;
313             }
314         }
315         if ((ret = ff_formats_ref(formats, &ctx->inputs[0]->out_formats)) < 0)
316             return ret;
317     }
318     if (ctx->outputs[0]) {
319         const AVPixFmtDescriptor *desc = NULL;
320         formats = NULL;
321         while ((desc = av_pix_fmt_desc_next(desc))) {
322             pix_fmt = av_pix_fmt_desc_get_id(desc);
323             if ((sws_isSupportedOutput(pix_fmt) || pix_fmt == AV_PIX_FMT_PAL8 ||
324                  sws_isSupportedEndiannessConversion(pix_fmt))
325                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
326                 return ret;
327             }
328         }
329         if ((ret = ff_formats_ref(formats, &ctx->outputs[0]->in_formats)) < 0)
330             return ret;
331     }
332
333     return 0;
334 }
335
336 static const int *parse_yuv_type(const char *s, enum AVColorSpace colorspace)
337 {
338     if (!s)
339         s = "bt601";
340
341     if (s && strstr(s, "bt709")) {
342         colorspace = AVCOL_SPC_BT709;
343     } else if (s && strstr(s, "fcc")) {
344         colorspace = AVCOL_SPC_FCC;
345     } else if (s && strstr(s, "smpte240m")) {
346         colorspace = AVCOL_SPC_SMPTE240M;
347     } else if (s && (strstr(s, "bt601") || strstr(s, "bt470") || strstr(s, "smpte170m"))) {
348         colorspace = AVCOL_SPC_BT470BG;
349     } else if (s && strstr(s, "bt2020")) {
350         colorspace = AVCOL_SPC_BT2020_NCL;
351     }
352
353     if (colorspace < 1 || colorspace > 10 || colorspace == 8) {
354         colorspace = AVCOL_SPC_BT470BG;
355     }
356
357     return sws_getCoefficients(colorspace);
358 }
359
360 static int scale_eval_dimensions(AVFilterContext *ctx)
361 {
362     ScaleContext *scale = ctx->priv;
363     const char scale2ref = ctx->filter == &ff_vf_scale2ref;
364     const AVFilterLink *inlink = scale2ref ? ctx->inputs[1] : ctx->inputs[0];
365     const AVFilterLink *outlink = ctx->outputs[0];
366     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
367     const AVPixFmtDescriptor *out_desc = av_pix_fmt_desc_get(outlink->format);
368     char *expr;
369     int eval_w, eval_h;
370     int ret;
371     double res;
372     const AVPixFmtDescriptor *main_desc;
373     const AVFilterLink *main_link;
374
375     if (scale2ref) {
376         main_link = ctx->inputs[0];
377         main_desc = av_pix_fmt_desc_get(main_link->format);
378     }
379
380     scale->var_values[VAR_IN_W]  = scale->var_values[VAR_IW] = inlink->w;
381     scale->var_values[VAR_IN_H]  = scale->var_values[VAR_IH] = inlink->h;
382     scale->var_values[VAR_OUT_W] = scale->var_values[VAR_OW] = NAN;
383     scale->var_values[VAR_OUT_H] = scale->var_values[VAR_OH] = NAN;
384     scale->var_values[VAR_A]     = (double) inlink->w / inlink->h;
385     scale->var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
386         (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
387     scale->var_values[VAR_DAR]   = scale->var_values[VAR_A] * scale->var_values[VAR_SAR];
388     scale->var_values[VAR_HSUB]  = 1 << desc->log2_chroma_w;
389     scale->var_values[VAR_VSUB]  = 1 << desc->log2_chroma_h;
390     scale->var_values[VAR_OHSUB] = 1 << out_desc->log2_chroma_w;
391     scale->var_values[VAR_OVSUB] = 1 << out_desc->log2_chroma_h;
392
393     if (scale2ref) {
394         scale->var_values[VARS_NB + VAR_S2R_MAIN_W] = main_link->w;
395         scale->var_values[VARS_NB + VAR_S2R_MAIN_H] = main_link->h;
396         scale->var_values[VARS_NB + VAR_S2R_MAIN_A] = (double) main_link->w / main_link->h;
397         scale->var_values[VARS_NB + VAR_S2R_MAIN_SAR] = main_link->sample_aspect_ratio.num ?
398             (double) main_link->sample_aspect_ratio.num / main_link->sample_aspect_ratio.den : 1;
399         scale->var_values[VARS_NB + VAR_S2R_MAIN_DAR] = scale->var_values[VARS_NB + VAR_S2R_MDAR] =
400             scale->var_values[VARS_NB + VAR_S2R_MAIN_A] * scale->var_values[VARS_NB + VAR_S2R_MAIN_SAR];
401         scale->var_values[VARS_NB + VAR_S2R_MAIN_HSUB] = 1 << main_desc->log2_chroma_w;
402         scale->var_values[VARS_NB + VAR_S2R_MAIN_VSUB] = 1 << main_desc->log2_chroma_h;
403     }
404
405     res = av_expr_eval(scale->w_pexpr, scale->var_values, NULL);
406     eval_w = scale->var_values[VAR_OUT_W] = scale->var_values[VAR_OW] = (int) res == 0 ? inlink->w : (int) res;
407
408     res = av_expr_eval(scale->h_pexpr, scale->var_values, NULL);
409     if (isnan(res)) {
410         expr = scale->h_expr;
411         ret = AVERROR(EINVAL);
412         goto fail;
413     }
414     eval_h = scale->var_values[VAR_OUT_H] = scale->var_values[VAR_OH] = (int) res == 0 ? inlink->h : (int) res;
415
416     res = av_expr_eval(scale->w_pexpr, scale->var_values, NULL);
417     if (isnan(res)) {
418         expr = scale->w_expr;
419         ret = AVERROR(EINVAL);
420         goto fail;
421     }
422     eval_w = scale->var_values[VAR_OUT_W] = scale->var_values[VAR_OW] = (int) res == 0 ? inlink->w : (int) res;
423
424     scale->w = eval_w;
425     scale->h = eval_h;
426
427     return 0;
428
429 fail:
430     av_log(ctx, AV_LOG_ERROR,
431            "Error when evaluating the expression '%s'.\n", expr);
432     return ret;
433 }
434
435 static int config_props(AVFilterLink *outlink)
436 {
437     AVFilterContext *ctx = outlink->src;
438     AVFilterLink *inlink0 = outlink->src->inputs[0];
439     AVFilterLink *inlink  = ctx->filter == &ff_vf_scale2ref ?
440                             outlink->src->inputs[1] :
441                             outlink->src->inputs[0];
442     enum AVPixelFormat outfmt = outlink->format;
443     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
444     ScaleContext *scale = ctx->priv;
445     int ret;
446
447     if ((ret = scale_eval_dimensions(ctx)) < 0)
448         goto fail;
449
450     ff_scale_adjust_dimensions(inlink, &scale->w, &scale->h,
451                                scale->force_original_aspect_ratio,
452                                scale->force_divisible_by);
453
454     if (scale->w > INT_MAX ||
455         scale->h > INT_MAX ||
456         (scale->h * inlink->w) > INT_MAX ||
457         (scale->w * inlink->h) > INT_MAX)
458         av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
459
460     outlink->w = scale->w;
461     outlink->h = scale->h;
462
463     /* TODO: make algorithm configurable */
464
465     scale->input_is_pal = desc->flags & AV_PIX_FMT_FLAG_PAL;
466     if (outfmt == AV_PIX_FMT_PAL8) outfmt = AV_PIX_FMT_BGR8;
467     scale->output_is_pal = av_pix_fmt_desc_get(outfmt)->flags & AV_PIX_FMT_FLAG_PAL ||
468                            av_pix_fmt_desc_get(outfmt)->flags & FF_PSEUDOPAL;
469
470     if (scale->sws)
471         sws_freeContext(scale->sws);
472     if (scale->isws[0])
473         sws_freeContext(scale->isws[0]);
474     if (scale->isws[1])
475         sws_freeContext(scale->isws[1]);
476     scale->isws[0] = scale->isws[1] = scale->sws = NULL;
477     if (inlink0->w == outlink->w &&
478         inlink0->h == outlink->h &&
479         !scale->out_color_matrix &&
480         scale->in_range == scale->out_range &&
481         inlink0->format == outlink->format)
482         ;
483     else {
484         struct SwsContext **swscs[3] = {&scale->sws, &scale->isws[0], &scale->isws[1]};
485         int i;
486
487         for (i = 0; i < 3; i++) {
488             int in_v_chr_pos = scale->in_v_chr_pos, out_v_chr_pos = scale->out_v_chr_pos;
489             struct SwsContext **s = swscs[i];
490             *s = sws_alloc_context();
491             if (!*s)
492                 return AVERROR(ENOMEM);
493
494             av_opt_set_int(*s, "srcw", inlink0 ->w, 0);
495             av_opt_set_int(*s, "srch", inlink0 ->h >> !!i, 0);
496             av_opt_set_int(*s, "src_format", inlink0->format, 0);
497             av_opt_set_int(*s, "dstw", outlink->w, 0);
498             av_opt_set_int(*s, "dsth", outlink->h >> !!i, 0);
499             av_opt_set_int(*s, "dst_format", outfmt, 0);
500             av_opt_set_int(*s, "sws_flags", scale->flags, 0);
501             av_opt_set_int(*s, "param0", scale->param[0], 0);
502             av_opt_set_int(*s, "param1", scale->param[1], 0);
503             if (scale->in_range != AVCOL_RANGE_UNSPECIFIED)
504                 av_opt_set_int(*s, "src_range",
505                                scale->in_range == AVCOL_RANGE_JPEG, 0);
506             if (scale->out_range != AVCOL_RANGE_UNSPECIFIED)
507                 av_opt_set_int(*s, "dst_range",
508                                scale->out_range == AVCOL_RANGE_JPEG, 0);
509
510             if (scale->opts) {
511                 AVDictionaryEntry *e = NULL;
512                 while ((e = av_dict_get(scale->opts, "", e, AV_DICT_IGNORE_SUFFIX))) {
513                     if ((ret = av_opt_set(*s, e->key, e->value, 0)) < 0)
514                         return ret;
515                 }
516             }
517             /* Override YUV420P default settings to have the correct (MPEG-2) chroma positions
518              * MPEG-2 chroma positions are used by convention
519              * XXX: support other 4:2:0 pixel formats */
520             if (inlink0->format == AV_PIX_FMT_YUV420P && scale->in_v_chr_pos == -513) {
521                 in_v_chr_pos = (i == 0) ? 128 : (i == 1) ? 64 : 192;
522             }
523
524             if (outlink->format == AV_PIX_FMT_YUV420P && scale->out_v_chr_pos == -513) {
525                 out_v_chr_pos = (i == 0) ? 128 : (i == 1) ? 64 : 192;
526             }
527
528             av_opt_set_int(*s, "src_h_chr_pos", scale->in_h_chr_pos, 0);
529             av_opt_set_int(*s, "src_v_chr_pos", in_v_chr_pos, 0);
530             av_opt_set_int(*s, "dst_h_chr_pos", scale->out_h_chr_pos, 0);
531             av_opt_set_int(*s, "dst_v_chr_pos", out_v_chr_pos, 0);
532
533             if ((ret = sws_init_context(*s, NULL, NULL)) < 0)
534                 return ret;
535             if (!scale->interlaced)
536                 break;
537         }
538     }
539
540     if (inlink0->sample_aspect_ratio.num){
541         outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h * inlink0->w, outlink->w * inlink0->h}, inlink0->sample_aspect_ratio);
542     } else
543         outlink->sample_aspect_ratio = inlink0->sample_aspect_ratio;
544
545     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",
546            inlink ->w, inlink ->h, av_get_pix_fmt_name( inlink->format),
547            inlink->sample_aspect_ratio.num, inlink->sample_aspect_ratio.den,
548            outlink->w, outlink->h, av_get_pix_fmt_name(outlink->format),
549            outlink->sample_aspect_ratio.num, outlink->sample_aspect_ratio.den,
550            scale->flags);
551     return 0;
552
553 fail:
554     return ret;
555 }
556
557 static int config_props_ref(AVFilterLink *outlink)
558 {
559     AVFilterLink *inlink = outlink->src->inputs[1];
560
561     outlink->w = inlink->w;
562     outlink->h = inlink->h;
563     outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
564     outlink->time_base = inlink->time_base;
565     outlink->frame_rate = inlink->frame_rate;
566
567     return 0;
568 }
569
570 static int request_frame(AVFilterLink *outlink)
571 {
572     return ff_request_frame(outlink->src->inputs[0]);
573 }
574
575 static int request_frame_ref(AVFilterLink *outlink)
576 {
577     return ff_request_frame(outlink->src->inputs[1]);
578 }
579
580 static int scale_slice(AVFilterLink *link, AVFrame *out_buf, AVFrame *cur_pic, struct SwsContext *sws, int y, int h, int mul, int field)
581 {
582     ScaleContext *scale = link->dst->priv;
583     const uint8_t *in[4];
584     uint8_t *out[4];
585     int in_stride[4],out_stride[4];
586     int i;
587
588     for (i=0; i<4; i++) {
589         int vsub= ((i+1)&2) ? scale->vsub : 0;
590          in_stride[i] = cur_pic->linesize[i] * mul;
591         out_stride[i] = out_buf->linesize[i] * mul;
592          in[i] = cur_pic->data[i] + ((y>>vsub)+field) * cur_pic->linesize[i];
593         out[i] = out_buf->data[i] +            field  * out_buf->linesize[i];
594     }
595     if (scale->input_is_pal)
596          in[1] = cur_pic->data[1];
597     if (scale->output_is_pal)
598         out[1] = out_buf->data[1];
599
600     return sws_scale(sws, in, in_stride, y/mul, h,
601                          out,out_stride);
602 }
603
604 static int scale_frame(AVFilterLink *link, AVFrame *in, AVFrame **frame_out)
605 {
606     AVFilterContext *ctx = link->dst;
607     ScaleContext *scale = ctx->priv;
608     AVFilterLink *outlink = ctx->outputs[0];
609     AVFrame *out;
610     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
611     char buf[32];
612     int in_range;
613     int frame_changed;
614
615     *frame_out = NULL;
616     if (in->colorspace == AVCOL_SPC_YCGCO)
617         av_log(link->dst, AV_LOG_WARNING, "Detected unsupported YCgCo colorspace.\n");
618
619     frame_changed = in->width  != link->w ||
620                     in->height != link->h ||
621                     in->format != link->format ||
622                     in->sample_aspect_ratio.den != link->sample_aspect_ratio.den ||
623                     in->sample_aspect_ratio.num != link->sample_aspect_ratio.num;
624
625     if (frame_changed ||
626         (scale->eval_mode == EVAL_MODE_FRAME &&
627          ctx->filter == &ff_vf_scale2ref) ) {
628         int ret;
629
630         if (scale->eval_mode == EVAL_MODE_INIT) {
631             snprintf(buf, sizeof(buf)-1, "%d", outlink->w);
632             av_opt_set(scale, "w", buf, 0);
633             snprintf(buf, sizeof(buf)-1, "%d", outlink->h);
634             av_opt_set(scale, "h", buf, 0);
635
636             ret = scale_parse_expr(ctx, NULL, &scale->w_pexpr, "width", scale->w_expr);
637             if (ret < 0)
638                 return ret;
639
640             ret = scale_parse_expr(ctx, NULL, &scale->h_pexpr, "height", scale->h_expr);
641             if (ret < 0)
642                 return ret;
643         }
644
645         link->dst->inputs[0]->format = in->format;
646         link->dst->inputs[0]->w      = in->width;
647         link->dst->inputs[0]->h      = in->height;
648
649         link->dst->inputs[0]->sample_aspect_ratio.den = in->sample_aspect_ratio.den;
650         link->dst->inputs[0]->sample_aspect_ratio.num = in->sample_aspect_ratio.num;
651
652         if ((ret = config_props(outlink)) < 0)
653             return ret;
654     }
655
656     if (!scale->sws) {
657         *frame_out = in;
658         return 0;
659     }
660
661     scale->hsub = desc->log2_chroma_w;
662     scale->vsub = desc->log2_chroma_h;
663
664     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
665     if (!out) {
666         av_frame_free(&in);
667         return AVERROR(ENOMEM);
668     }
669     *frame_out = out;
670
671     av_frame_copy_props(out, in);
672     out->width  = outlink->w;
673     out->height = outlink->h;
674
675     if (scale->output_is_pal)
676         avpriv_set_systematic_pal2((uint32_t*)out->data[1], outlink->format == AV_PIX_FMT_PAL8 ? AV_PIX_FMT_BGR8 : outlink->format);
677
678     in_range = in->color_range;
679
680     if (   scale->in_color_matrix
681         || scale->out_color_matrix
682         || scale-> in_range != AVCOL_RANGE_UNSPECIFIED
683         || in_range != AVCOL_RANGE_UNSPECIFIED
684         || scale->out_range != AVCOL_RANGE_UNSPECIFIED) {
685         int in_full, out_full, brightness, contrast, saturation;
686         const int *inv_table, *table;
687
688         sws_getColorspaceDetails(scale->sws, (int **)&inv_table, &in_full,
689                                  (int **)&table, &out_full,
690                                  &brightness, &contrast, &saturation);
691
692         if (scale->in_color_matrix)
693             inv_table = parse_yuv_type(scale->in_color_matrix, in->colorspace);
694         if (scale->out_color_matrix)
695             table     = parse_yuv_type(scale->out_color_matrix, AVCOL_SPC_UNSPECIFIED);
696         else if (scale->in_color_matrix)
697             table = inv_table;
698
699         if (scale-> in_range != AVCOL_RANGE_UNSPECIFIED)
700             in_full  = (scale-> in_range == AVCOL_RANGE_JPEG);
701         else if (in_range != AVCOL_RANGE_UNSPECIFIED)
702             in_full  = (in_range == AVCOL_RANGE_JPEG);
703         if (scale->out_range != AVCOL_RANGE_UNSPECIFIED)
704             out_full = (scale->out_range == AVCOL_RANGE_JPEG);
705
706         sws_setColorspaceDetails(scale->sws, inv_table, in_full,
707                                  table, out_full,
708                                  brightness, contrast, saturation);
709         if (scale->isws[0])
710             sws_setColorspaceDetails(scale->isws[0], inv_table, in_full,
711                                      table, out_full,
712                                      brightness, contrast, saturation);
713         if (scale->isws[1])
714             sws_setColorspaceDetails(scale->isws[1], inv_table, in_full,
715                                      table, out_full,
716                                      brightness, contrast, saturation);
717
718         out->color_range = out_full ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
719     }
720
721     av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
722               (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
723               (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
724               INT_MAX);
725
726     if (scale->interlaced>0 || (scale->interlaced<0 && in->interlaced_frame)) {
727         scale_slice(link, out, in, scale->isws[0], 0, (link->h+1)/2, 2, 0);
728         scale_slice(link, out, in, scale->isws[1], 0,  link->h   /2, 2, 1);
729     } else if (scale->nb_slices) {
730         int i, slice_h, slice_start, slice_end = 0;
731         const int nb_slices = FFMIN(scale->nb_slices, link->h);
732         for (i = 0; i < nb_slices; i++) {
733             slice_start = slice_end;
734             slice_end   = (link->h * (i+1)) / nb_slices;
735             slice_h     = slice_end - slice_start;
736             scale_slice(link, out, in, scale->sws, slice_start, slice_h, 1, 0);
737         }
738     } else {
739         scale_slice(link, out, in, scale->sws, 0, link->h, 1, 0);
740     }
741
742     av_frame_free(&in);
743     return 0;
744 }
745
746 static int filter_frame(AVFilterLink *link, AVFrame *in)
747 {
748     AVFilterContext *ctx = link->dst;
749     AVFilterLink *outlink = ctx->outputs[0];
750     AVFrame *out;
751     int ret;
752
753     ret = scale_frame(link, in, &out);
754     if (out)
755         return ff_filter_frame(outlink, out);
756
757     return ret;
758 }
759
760 static int filter_frame_ref(AVFilterLink *link, AVFrame *in)
761 {
762     AVFilterLink *outlink = link->dst->outputs[1];
763     int frame_changed;
764
765     frame_changed = in->width  != link->w ||
766                     in->height != link->h ||
767                     in->format != link->format ||
768                     in->sample_aspect_ratio.den != link->sample_aspect_ratio.den ||
769                     in->sample_aspect_ratio.num != link->sample_aspect_ratio.num;
770
771     if (frame_changed) {
772         link->format = in->format;
773         link->w = in->width;
774         link->h = in->height;
775         link->sample_aspect_ratio.num = in->sample_aspect_ratio.num;
776         link->sample_aspect_ratio.den = in->sample_aspect_ratio.den;
777
778         config_props_ref(outlink);
779     }
780
781     return ff_filter_frame(outlink, in);
782 }
783
784 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
785                            char *res, int res_len, int flags)
786 {
787     ScaleContext *scale = ctx->priv;
788     char *str_expr;
789     AVExpr **pexpr_ptr;
790     int ret, w, h;
791
792     w = !strcmp(cmd, "width")  || !strcmp(cmd, "w");
793     h = !strcmp(cmd, "height")  || !strcmp(cmd, "h");
794
795     if (w || h) {
796         str_expr = w ? scale->w_expr : scale->h_expr;
797         pexpr_ptr = w ? &scale->w_pexpr : &scale->h_pexpr;
798
799         ret = scale_parse_expr(ctx, str_expr, pexpr_ptr, cmd, args);
800     } else
801         ret = AVERROR(ENOSYS);
802
803     if (ret < 0)
804         av_log(ctx, AV_LOG_ERROR, "Failed to process command. Continuing with existing parameters.\n");
805
806     return ret;
807 }
808
809 static const AVClass *child_class_next(const AVClass *prev)
810 {
811     return prev ? NULL : sws_get_class();
812 }
813
814 #define OFFSET(x) offsetof(ScaleContext, x)
815 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
816 #define TFLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
817
818 static const AVOption scale_options[] = {
819     { "w",     "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING,        .flags = TFLAGS },
820     { "width", "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING,        .flags = TFLAGS },
821     { "h",     "Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING,        .flags = TFLAGS },
822     { "height","Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING,        .flags = TFLAGS },
823     { "flags", "Flags to pass to libswscale", OFFSET(flags_str), AV_OPT_TYPE_STRING, { .str = "bilinear" }, .flags = FLAGS },
824     { "interl", "set interlacing", OFFSET(interlaced), AV_OPT_TYPE_BOOL, {.i64 = 0 }, -1, 1, FLAGS },
825     { "size",   "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
826     { "s",      "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
827     {  "in_color_matrix", "set input YCbCr type",   OFFSET(in_color_matrix),  AV_OPT_TYPE_STRING, { .str = "auto" }, .flags = FLAGS, "color" },
828     { "out_color_matrix", "set output YCbCr type",  OFFSET(out_color_matrix), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = FLAGS,  "color"},
829         { "auto",        NULL, 0, AV_OPT_TYPE_CONST, { .str = "auto" },      0, 0, FLAGS, "color" },
830         { "bt601",       NULL, 0, AV_OPT_TYPE_CONST, { .str = "bt601" },     0, 0, FLAGS, "color" },
831         { "bt470",       NULL, 0, AV_OPT_TYPE_CONST, { .str = "bt470" },     0, 0, FLAGS, "color" },
832         { "smpte170m",   NULL, 0, AV_OPT_TYPE_CONST, { .str = "smpte170m" }, 0, 0, FLAGS, "color" },
833         { "bt709",       NULL, 0, AV_OPT_TYPE_CONST, { .str = "bt709" },     0, 0, FLAGS, "color" },
834         { "fcc",         NULL, 0, AV_OPT_TYPE_CONST, { .str = "fcc" },       0, 0, FLAGS, "color" },
835         { "smpte240m",   NULL, 0, AV_OPT_TYPE_CONST, { .str = "smpte240m" }, 0, 0, FLAGS, "color" },
836         { "bt2020",      NULL, 0, AV_OPT_TYPE_CONST, { .str = "bt2020" },    0, 0, FLAGS, "color" },
837     {  "in_range", "set input color range",  OFFSET( in_range), AV_OPT_TYPE_INT, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 2, FLAGS, "range" },
838     { "out_range", "set output color range", OFFSET(out_range), AV_OPT_TYPE_INT, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 2, FLAGS, "range" },
839     { "auto",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 0, FLAGS, "range" },
840     { "unknown", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 0, FLAGS, "range" },
841     { "full",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG}, 0, 0, FLAGS, "range" },
842     { "limited",NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG}, 0, 0, FLAGS, "range" },
843     { "jpeg",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG}, 0, 0, FLAGS, "range" },
844     { "mpeg",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG}, 0, 0, FLAGS, "range" },
845     { "tv",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG}, 0, 0, FLAGS, "range" },
846     { "pc",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG}, 0, 0, FLAGS, "range" },
847     { "in_v_chr_pos",   "input vertical chroma position in luma grid/256"  ,   OFFSET(in_v_chr_pos),  AV_OPT_TYPE_INT, { .i64 = -513}, -513, 512, FLAGS },
848     { "in_h_chr_pos",   "input horizontal chroma position in luma grid/256",   OFFSET(in_h_chr_pos),  AV_OPT_TYPE_INT, { .i64 = -513}, -513, 512, FLAGS },
849     { "out_v_chr_pos",   "output vertical chroma position in luma grid/256"  , OFFSET(out_v_chr_pos), AV_OPT_TYPE_INT, { .i64 = -513}, -513, 512, FLAGS },
850     { "out_h_chr_pos",   "output horizontal chroma position in luma grid/256", OFFSET(out_h_chr_pos), AV_OPT_TYPE_INT, { .i64 = -513}, -513, 512, FLAGS },
851     { "force_original_aspect_ratio", "decrease or increase w/h if necessary to keep the original AR", OFFSET(force_original_aspect_ratio), AV_OPT_TYPE_INT, { .i64 = 0}, 0, 2, FLAGS, "force_oar" },
852     { "disable",  NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 0 }, 0, 0, FLAGS, "force_oar" },
853     { "decrease", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 1 }, 0, 0, FLAGS, "force_oar" },
854     { "increase", NULL, 0, AV_OPT_TYPE_CONST, {.i64 = 2 }, 0, 0, FLAGS, "force_oar" },
855     { "force_divisible_by", "enforce that the output resolution is divisible by a defined integer when force_original_aspect_ratio is used", OFFSET(force_divisible_by), AV_OPT_TYPE_INT, { .i64 = 1}, 1, 256, FLAGS },
856     { "param0", "Scaler param 0",             OFFSET(param[0]),  AV_OPT_TYPE_DOUBLE, { .dbl = SWS_PARAM_DEFAULT  }, INT_MIN, INT_MAX, FLAGS },
857     { "param1", "Scaler param 1",             OFFSET(param[1]),  AV_OPT_TYPE_DOUBLE, { .dbl = SWS_PARAM_DEFAULT  }, INT_MIN, INT_MAX, FLAGS },
858     { "nb_slices", "set the number of slices (debug purpose only)", OFFSET(nb_slices), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, INT_MAX, FLAGS },
859     { "eval", "specify when to evaluate expressions", OFFSET(eval_mode), AV_OPT_TYPE_INT, {.i64 = EVAL_MODE_INIT}, 0, EVAL_MODE_NB-1, FLAGS, "eval" },
860          { "init",  "eval expressions once during initialization", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_INIT},  .flags = FLAGS, .unit = "eval" },
861          { "frame", "eval expressions during initialization and per-frame", 0, AV_OPT_TYPE_CONST, {.i64=EVAL_MODE_FRAME}, .flags = FLAGS, .unit = "eval" },
862     { NULL }
863 };
864
865 static const AVClass scale_class = {
866     .class_name       = "scale",
867     .item_name        = av_default_item_name,
868     .option           = scale_options,
869     .version          = LIBAVUTIL_VERSION_INT,
870     .category         = AV_CLASS_CATEGORY_FILTER,
871     .child_class_next = child_class_next,
872 };
873
874 static const AVFilterPad avfilter_vf_scale_inputs[] = {
875     {
876         .name         = "default",
877         .type         = AVMEDIA_TYPE_VIDEO,
878         .filter_frame = filter_frame,
879     },
880     { NULL }
881 };
882
883 static const AVFilterPad avfilter_vf_scale_outputs[] = {
884     {
885         .name         = "default",
886         .type         = AVMEDIA_TYPE_VIDEO,
887         .config_props = config_props,
888     },
889     { NULL }
890 };
891
892 AVFilter ff_vf_scale = {
893     .name            = "scale",
894     .description     = NULL_IF_CONFIG_SMALL("Scale the input video size and/or convert the image format."),
895     .init_dict       = init_dict,
896     .uninit          = uninit,
897     .query_formats   = query_formats,
898     .priv_size       = sizeof(ScaleContext),
899     .priv_class      = &scale_class,
900     .inputs          = avfilter_vf_scale_inputs,
901     .outputs         = avfilter_vf_scale_outputs,
902     .process_command = process_command,
903 };
904
905 static const AVClass scale2ref_class = {
906     .class_name       = "scale2ref",
907     .item_name        = av_default_item_name,
908     .option           = scale_options,
909     .version          = LIBAVUTIL_VERSION_INT,
910     .category         = AV_CLASS_CATEGORY_FILTER,
911     .child_class_next = child_class_next,
912 };
913
914 static const AVFilterPad avfilter_vf_scale2ref_inputs[] = {
915     {
916         .name         = "default",
917         .type         = AVMEDIA_TYPE_VIDEO,
918         .filter_frame = filter_frame,
919     },
920     {
921         .name         = "ref",
922         .type         = AVMEDIA_TYPE_VIDEO,
923         .filter_frame = filter_frame_ref,
924     },
925     { NULL }
926 };
927
928 static const AVFilterPad avfilter_vf_scale2ref_outputs[] = {
929     {
930         .name         = "default",
931         .type         = AVMEDIA_TYPE_VIDEO,
932         .config_props = config_props,
933         .request_frame= request_frame,
934     },
935     {
936         .name         = "ref",
937         .type         = AVMEDIA_TYPE_VIDEO,
938         .config_props = config_props_ref,
939         .request_frame= request_frame_ref,
940     },
941     { NULL }
942 };
943
944 AVFilter ff_vf_scale2ref = {
945     .name            = "scale2ref",
946     .description     = NULL_IF_CONFIG_SMALL("Scale the input video size and/or convert the image format to the given reference."),
947     .init_dict       = init_dict,
948     .uninit          = uninit,
949     .query_formats   = query_formats,
950     .priv_size       = sizeof(ScaleContext),
951     .priv_class      = &scale2ref_class,
952     .inputs          = avfilter_vf_scale2ref_inputs,
953     .outputs         = avfilter_vf_scale2ref_outputs,
954     .process_command = process_command,
955 };