]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_scale.c
Merge commit 'ca488ad480360dfafcb5766f7bfbb567a0638979'
[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 *size_str;
82     unsigned int flags;         ///sws flags
83
84     int hsub, vsub;             ///< chroma subsampling
85     int slice_y;                ///< top of current output slice
86     int input_is_pal;           ///< set to 1 if the input format is paletted
87     int output_is_pal;          ///< set to 1 if the output format is paletted
88     int interlaced;
89
90     char *w_expr;               ///< width  expression string
91     char *h_expr;               ///< height expression string
92     char *flags_str;
93
94     char *in_color_matrix;
95     char *out_color_matrix;
96
97     int in_range;
98     int out_range;
99 } ScaleContext;
100
101 static av_cold int init(AVFilterContext *ctx)
102 {
103     ScaleContext *scale = ctx->priv;
104     int ret;
105
106     if (scale->size_str && (scale->w_expr || scale->h_expr)) {
107         av_log(ctx, AV_LOG_ERROR,
108                "Size and width/height expressions cannot be set at the same time.\n");
109             return AVERROR(EINVAL);
110     }
111
112     if (scale->w_expr && !scale->h_expr)
113         FFSWAP(char *, scale->w_expr, scale->size_str);
114
115     if (scale->size_str) {
116         char buf[32];
117         if ((ret = av_parse_video_size(&scale->w, &scale->h, scale->size_str)) < 0) {
118             av_log(ctx, AV_LOG_ERROR,
119                    "Invalid size '%s'\n", scale->size_str);
120             return ret;
121         }
122         snprintf(buf, sizeof(buf)-1, "%d", scale->w);
123         av_opt_set(scale, "w", buf, 0);
124         snprintf(buf, sizeof(buf)-1, "%d", scale->h);
125         av_opt_set(scale, "h", buf, 0);
126     }
127     if (!scale->w_expr)
128         av_opt_set(scale, "w", "iw", 0);
129     if (!scale->h_expr)
130         av_opt_set(scale, "h", "ih", 0);
131
132     av_log(ctx, AV_LOG_VERBOSE, "w:%s h:%s flags:'%s' interl:%d\n",
133            scale->w_expr, scale->h_expr, (char *)av_x_if_null(scale->flags_str, ""), scale->interlaced);
134
135     scale->flags = SWS_BILINEAR;
136
137     if (scale->flags_str) {
138         const AVClass *class = sws_get_class();
139         const AVOption    *o = av_opt_find(&class, "sws_flags", NULL, 0,
140                                            AV_OPT_SEARCH_FAKE_OBJ);
141         int ret = av_opt_eval_flags(&class, o, scale->flags_str, &scale->flags);
142         if (ret < 0)
143             return ret;
144     }
145
146     return 0;
147 }
148
149 static av_cold void uninit(AVFilterContext *ctx)
150 {
151     ScaleContext *scale = ctx->priv;
152     sws_freeContext(scale->sws);
153     sws_freeContext(scale->isws[0]);
154     sws_freeContext(scale->isws[1]);
155     scale->sws = NULL;
156 }
157
158 static int query_formats(AVFilterContext *ctx)
159 {
160     AVFilterFormats *formats;
161     enum AVPixelFormat pix_fmt;
162     int ret;
163
164     if (ctx->inputs[0]) {
165         formats = NULL;
166         for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
167             if ((sws_isSupportedInput(pix_fmt) ||
168                  sws_isSupportedEndiannessConversion(pix_fmt))
169                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
170                 ff_formats_unref(&formats);
171                 return ret;
172             }
173         ff_formats_ref(formats, &ctx->inputs[0]->out_formats);
174     }
175     if (ctx->outputs[0]) {
176         formats = NULL;
177         for (pix_fmt = 0; pix_fmt < AV_PIX_FMT_NB; pix_fmt++)
178             if ((sws_isSupportedOutput(pix_fmt) || pix_fmt == AV_PIX_FMT_PAL8 ||
179                  sws_isSupportedEndiannessConversion(pix_fmt))
180                 && (ret = ff_add_format(&formats, pix_fmt)) < 0) {
181                 ff_formats_unref(&formats);
182                 return ret;
183             }
184         ff_formats_ref(formats, &ctx->outputs[0]->in_formats);
185     }
186
187     return 0;
188 }
189
190 static const int *parse_yuv_type(const char *s, enum AVColorSpace colorspace)
191 {
192     const static int32_t yuv2rgb_coeffs[8][4] = {
193         { 117504, 138453, 13954, 34903 },
194         { 117504, 138453, 13954, 34903 }, /* ITU-R Rec. 709 (1990) */
195         { 104597, 132201, 25675, 53279 }, /* unspecified */
196         { 104597, 132201, 25675, 53279 }, /* reserved */
197         { 104448, 132798, 24759, 53109 }, /* FCC */
198         { 104597, 132201, 25675, 53279 }, /* ITU-R Rec. 624-4 System B, G */
199         { 104597, 132201, 25675, 53279 }, /* SMPTE 170M */
200         { 117579, 136230, 16907, 35559 }  /* SMPTE 240M (1987) */
201     };
202     if (!s)
203         s = "bt601";
204
205     if (s && strstr(s, "bt709")) {
206         colorspace = AVCOL_SPC_BT709;
207     } else if (s && strstr(s, "fcc")) {
208         colorspace = AVCOL_SPC_FCC;
209     } else if (s && strstr(s, "smpte240m")) {
210         colorspace = AVCOL_SPC_SMPTE240M;
211     } else if (s && (strstr(s, "bt601") || strstr(s, "bt470") || strstr(s, "smpte170m"))) {
212         colorspace = AVCOL_SPC_BT470BG;
213     }
214
215     if (colorspace < 1 || colorspace > 7) {
216         colorspace = AVCOL_SPC_BT470BG;
217     }
218
219     return yuv2rgb_coeffs[colorspace];
220 }
221
222 static int config_props(AVFilterLink *outlink)
223 {
224     AVFilterContext *ctx = outlink->src;
225     AVFilterLink *inlink = outlink->src->inputs[0];
226     enum AVPixelFormat outfmt = outlink->format;
227     ScaleContext *scale = ctx->priv;
228     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(inlink->format);
229     int64_t w, h;
230     double var_values[VARS_NB], res;
231     char *expr;
232     int ret;
233
234     var_values[VAR_IN_W]  = var_values[VAR_IW] = inlink->w;
235     var_values[VAR_IN_H]  = var_values[VAR_IH] = inlink->h;
236     var_values[VAR_OUT_W] = var_values[VAR_OW] = NAN;
237     var_values[VAR_OUT_H] = var_values[VAR_OH] = NAN;
238     var_values[VAR_A]     = (double) inlink->w / inlink->h;
239     var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ?
240         (double) inlink->sample_aspect_ratio.num / inlink->sample_aspect_ratio.den : 1;
241     var_values[VAR_DAR]   = var_values[VAR_A] * var_values[VAR_SAR];
242     var_values[VAR_HSUB]  = 1 << desc->log2_chroma_w;
243     var_values[VAR_VSUB]  = 1 << desc->log2_chroma_h;
244
245     /* evaluate width and height */
246     av_expr_parse_and_eval(&res, (expr = scale->w_expr),
247                            var_names, var_values,
248                            NULL, NULL, NULL, NULL, NULL, 0, ctx);
249     scale->w = var_values[VAR_OUT_W] = var_values[VAR_OW] = res;
250     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->h_expr),
251                                       var_names, var_values,
252                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
253         goto fail;
254     scale->h = var_values[VAR_OUT_H] = var_values[VAR_OH] = res;
255     /* evaluate again the width, as it may depend on the output height */
256     if ((ret = av_expr_parse_and_eval(&res, (expr = scale->w_expr),
257                                       var_names, var_values,
258                                       NULL, NULL, NULL, NULL, NULL, 0, ctx)) < 0)
259         goto fail;
260     scale->w = res;
261
262     w = scale->w;
263     h = scale->h;
264
265     /* sanity check params */
266     if (w <  -1 || h <  -1) {
267         av_log(ctx, AV_LOG_ERROR, "Size values less than -1 are not acceptable.\n");
268         return AVERROR(EINVAL);
269     }
270     if (w == -1 && h == -1)
271         scale->w = scale->h = 0;
272
273     if (!(w = scale->w))
274         w = inlink->w;
275     if (!(h = scale->h))
276         h = inlink->h;
277     if (w == -1)
278         w = av_rescale(h, inlink->w, inlink->h);
279     if (h == -1)
280         h = av_rescale(w, inlink->h, inlink->w);
281
282     if (w > INT_MAX || h > INT_MAX ||
283         (h * inlink->w) > INT_MAX  ||
284         (w * inlink->h) > INT_MAX)
285         av_log(ctx, AV_LOG_ERROR, "Rescaled value for width or height is too big.\n");
286
287     outlink->w = w;
288     outlink->h = h;
289
290     /* TODO: make algorithm configurable */
291
292     scale->input_is_pal = desc->flags & AV_PIX_FMT_FLAG_PAL ||
293                           desc->flags & AV_PIX_FMT_FLAG_PSEUDOPAL;
294     if (outfmt == AV_PIX_FMT_PAL8) outfmt = AV_PIX_FMT_BGR8;
295     scale->output_is_pal = av_pix_fmt_desc_get(outfmt)->flags & AV_PIX_FMT_FLAG_PAL ||
296                            av_pix_fmt_desc_get(outfmt)->flags & AV_PIX_FMT_FLAG_PSEUDOPAL;
297
298     if (scale->sws)
299         sws_freeContext(scale->sws);
300     if (scale->isws[0])
301         sws_freeContext(scale->isws[0]);
302     if (scale->isws[1])
303         sws_freeContext(scale->isws[1]);
304     scale->isws[0] = scale->isws[1] = scale->sws = NULL;
305     if (inlink->w == outlink->w && inlink->h == outlink->h &&
306         inlink->format == outlink->format)
307         ;
308     else {
309         struct SwsContext **swscs[3] = {&scale->sws, &scale->isws[0], &scale->isws[1]};
310         int i;
311
312         for (i = 0; i < 3; i++) {
313             struct SwsContext **s = swscs[i];
314             *s = sws_alloc_context();
315             if (!*s)
316                 return AVERROR(ENOMEM);
317
318             av_opt_set_int(*s, "srcw", inlink ->w, 0);
319             av_opt_set_int(*s, "srch", inlink ->h >> !!i, 0);
320             av_opt_set_int(*s, "src_format", inlink->format, 0);
321             av_opt_set_int(*s, "dstw", outlink->w, 0);
322             av_opt_set_int(*s, "dsth", outlink->h >> !!i, 0);
323             av_opt_set_int(*s, "dst_format", outfmt, 0);
324             av_opt_set_int(*s, "sws_flags", scale->flags, 0);
325
326             if ((ret = sws_init_context(*s, NULL, NULL)) < 0)
327                 return ret;
328             if (!scale->interlaced)
329                 break;
330         }
331     }
332
333     if (inlink->sample_aspect_ratio.num){
334         outlink->sample_aspect_ratio = av_mul_q((AVRational){outlink->h * inlink->w, outlink->w * inlink->h}, inlink->sample_aspect_ratio);
335     } else
336         outlink->sample_aspect_ratio = inlink->sample_aspect_ratio;
337
338     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",
339            inlink ->w, inlink ->h, av_get_pix_fmt_name( inlink->format),
340            inlink->sample_aspect_ratio.num, inlink->sample_aspect_ratio.den,
341            outlink->w, outlink->h, av_get_pix_fmt_name(outlink->format),
342            outlink->sample_aspect_ratio.num, outlink->sample_aspect_ratio.den,
343            scale->flags);
344     return 0;
345
346 fail:
347     av_log(NULL, AV_LOG_ERROR,
348            "Error when evaluating the expression '%s'.\n"
349            "Maybe the expression for out_w:'%s' or for out_h:'%s' is self-referencing.\n",
350            expr, scale->w_expr, scale->h_expr);
351     return ret;
352 }
353
354 static int scale_slice(AVFilterLink *link, AVFrame *out_buf, AVFrame *cur_pic, struct SwsContext *sws, int y, int h, int mul, int field)
355 {
356     ScaleContext *scale = link->dst->priv;
357     const uint8_t *in[4];
358     uint8_t *out[4];
359     int in_stride[4],out_stride[4];
360     int i;
361
362     for(i=0; i<4; i++){
363         int vsub= ((i+1)&2) ? scale->vsub : 0;
364          in_stride[i] = cur_pic->linesize[i] * mul;
365         out_stride[i] = out_buf->linesize[i] * mul;
366          in[i] = cur_pic->data[i] + ((y>>vsub)+field) * cur_pic->linesize[i];
367         out[i] = out_buf->data[i] +            field  * out_buf->linesize[i];
368     }
369     if(scale->input_is_pal)
370          in[1] = cur_pic->data[1];
371     if(scale->output_is_pal)
372         out[1] = out_buf->data[1];
373
374     return sws_scale(sws, in, in_stride, y/mul, h,
375                          out,out_stride);
376 }
377
378 static int filter_frame(AVFilterLink *link, AVFrame *in)
379 {
380     ScaleContext *scale = link->dst->priv;
381     AVFilterLink *outlink = link->dst->outputs[0];
382     AVFrame *out;
383     const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(link->format);
384     char buf[32];
385
386     if(   in->width  != link->w
387        || in->height != link->h
388        || in->format != link->format) {
389         int ret;
390         snprintf(buf, sizeof(buf)-1, "%d", outlink->w);
391         av_opt_set(scale, "w", buf, 0);
392         snprintf(buf, sizeof(buf)-1, "%d", outlink->h);
393         av_opt_set(scale, "h", buf, 0);
394
395         link->dst->inputs[0]->format = in->format;
396         link->dst->inputs[0]->w      = in->width;
397         link->dst->inputs[0]->h      = in->height;
398
399         if ((ret = config_props(outlink)) < 0)
400             return ret;
401     }
402
403     if (!scale->sws)
404         return ff_filter_frame(outlink, in);
405
406     scale->hsub = desc->log2_chroma_w;
407     scale->vsub = desc->log2_chroma_h;
408
409     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
410     if (!out) {
411         av_frame_free(&in);
412         return AVERROR(ENOMEM);
413     }
414
415     av_frame_copy_props(out, in);
416     out->width  = outlink->w;
417     out->height = outlink->h;
418
419     if(scale->output_is_pal)
420         avpriv_set_systematic_pal2((uint32_t*)out->data[1], outlink->format == AV_PIX_FMT_PAL8 ? AV_PIX_FMT_BGR8 : outlink->format);
421
422     if (   scale->in_color_matrix
423         || scale->out_color_matrix
424         || scale-> in_range != AVCOL_RANGE_UNSPECIFIED
425         || scale->out_range != AVCOL_RANGE_UNSPECIFIED) {
426         int in_full, out_full, brightness, contrast, saturation;
427         const int *inv_table, *table;
428
429         sws_getColorspaceDetails(scale->sws, (int **)&inv_table, &in_full,
430                                  (int **)&table, &out_full,
431                                  &brightness, &contrast, &saturation);
432
433         if (scale->in_color_matrix)
434             inv_table = parse_yuv_type(scale->in_color_matrix, av_frame_get_colorspace(in));
435         if (scale->out_color_matrix)
436             table     = parse_yuv_type(scale->out_color_matrix, AVCOL_SPC_UNSPECIFIED);
437
438         if (scale-> in_range != AVCOL_RANGE_UNSPECIFIED)
439             in_full  = (scale-> in_range == AVCOL_RANGE_JPEG);
440         if (scale->out_range != AVCOL_RANGE_UNSPECIFIED)
441             out_full = (scale->out_range == AVCOL_RANGE_JPEG);
442
443         sws_setColorspaceDetails(scale->sws, inv_table, in_full,
444                                  table, out_full,
445                                  brightness, contrast, saturation);
446         if (scale->isws[0])
447             sws_setColorspaceDetails(scale->isws[0], inv_table, in_full,
448                                      table, out_full,
449                                      brightness, contrast, saturation);
450         if (scale->isws[1])
451             sws_setColorspaceDetails(scale->isws[1], inv_table, in_full,
452                                      table, out_full,
453                                      brightness, contrast, saturation);
454     }
455
456     av_reduce(&out->sample_aspect_ratio.num, &out->sample_aspect_ratio.den,
457               (int64_t)in->sample_aspect_ratio.num * outlink->h * link->w,
458               (int64_t)in->sample_aspect_ratio.den * outlink->w * link->h,
459               INT_MAX);
460
461     if(scale->interlaced>0 || (scale->interlaced<0 && in->interlaced_frame)){
462         scale_slice(link, out, in, scale->isws[0], 0, (link->h+1)/2, 2, 0);
463         scale_slice(link, out, in, scale->isws[1], 0,  link->h   /2, 2, 1);
464     }else{
465         scale_slice(link, out, in, scale->sws, 0, link->h, 1, 0);
466     }
467
468     av_frame_free(&in);
469     return ff_filter_frame(outlink, out);
470 }
471
472 #define OFFSET(x) offsetof(ScaleContext, x)
473 #define FLAGS AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_FILTERING_PARAM
474
475 static const AVOption scale_options[] = {
476     { "w",     "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
477     { "width", "Output video width",          OFFSET(w_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
478     { "h",     "Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
479     { "height","Output video height",         OFFSET(h_expr),    AV_OPT_TYPE_STRING,        .flags = FLAGS },
480     { "flags", "Flags to pass to libswscale", OFFSET(flags_str), AV_OPT_TYPE_STRING, { .str = "bilinear" }, .flags = FLAGS },
481     { "interl", "set interlacing", OFFSET(interlaced), AV_OPT_TYPE_INT, {.i64 = 0 }, -1, 1, FLAGS },
482     { "size",   "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
483     { "s",      "set video size",          OFFSET(size_str), AV_OPT_TYPE_STRING, {.str = NULL}, 0, FLAGS },
484     {  "in_color_matrix", "set input YCbCr type",   OFFSET(in_color_matrix),  AV_OPT_TYPE_STRING, { .str = NULL }, .flags = FLAGS },
485     { "out_color_matrix", "set output YCbCr type",  OFFSET(out_color_matrix), AV_OPT_TYPE_STRING, { .str = NULL }, .flags = FLAGS },
486     {  "in_range", "set input color range",  OFFSET( in_range), AV_OPT_TYPE_INT, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 2, FLAGS, "range" },
487     { "out_range", "set output color range", OFFSET(out_range), AV_OPT_TYPE_INT, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 2, FLAGS, "range" },
488     { "auto",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_UNSPECIFIED }, 0, 0, FLAGS, "range" },
489     { "full",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG}, 0, 0, FLAGS, "range" },
490     { "jpeg",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG}, 0, 0, FLAGS, "range" },
491     { "mpeg",   NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG}, 0, 0, FLAGS, "range" },
492     { "tv",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_JPEG}, 0, 0, FLAGS, "range" },
493     { "pc",     NULL, 0, AV_OPT_TYPE_CONST, {.i64 = AVCOL_RANGE_MPEG}, 0, 0, FLAGS, "range" },
494     { NULL },
495 };
496
497 AVFILTER_DEFINE_CLASS(scale);
498
499 static const AVFilterPad avfilter_vf_scale_inputs[] = {
500     {
501         .name        = "default",
502         .type        = AVMEDIA_TYPE_VIDEO,
503         .filter_frame = filter_frame,
504     },
505     { NULL }
506 };
507
508 static const AVFilterPad avfilter_vf_scale_outputs[] = {
509     {
510         .name         = "default",
511         .type         = AVMEDIA_TYPE_VIDEO,
512         .config_props = config_props,
513     },
514     { NULL }
515 };
516
517 AVFilter avfilter_vf_scale = {
518     .name      = "scale",
519     .description = NULL_IF_CONFIG_SMALL("Scale the input video to width:height size and/or convert the image format."),
520
521     .init      = init,
522     .uninit    = uninit,
523
524     .query_formats = query_formats,
525
526     .priv_size = sizeof(ScaleContext),
527     .priv_class = &scale_class,
528
529     .inputs    = avfilter_vf_scale_inputs,
530     .outputs   = avfilter_vf_scale_outputs,
531 };