]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_rotate.c
Merge remote-tracking branch 'qatar/master'
[ffmpeg] / libavfilter / vf_rotate.c
1 /*
2  * Copyright (c) 2013 Stefano Sabatini
3  * Copyright (c) 2008 Vitor Sessak
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 /**
23  * @file
24  * rotation filter, partially based on the tests/rotozoom.c program
25 */
26
27 #include "libavutil/avstring.h"
28 #include "libavutil/eval.h"
29 #include "libavutil/opt.h"
30 #include "libavutil/intreadwrite.h"
31 #include "libavutil/parseutils.h"
32 #include "libavutil/pixdesc.h"
33
34 #include "avfilter.h"
35 #include "drawutils.h"
36 #include "internal.h"
37 #include "video.h"
38
39 static const char *var_names[] = {
40     "in_w" , "iw",  ///< width of the input video
41     "in_h" , "ih",  ///< height of the input video
42     "out_w", "ow",  ///< width of the input video
43     "out_h", "oh",  ///< height of the input video
44     "hsub", "vsub",
45     "n",            ///< number of frame
46     "t",            ///< timestamp expressed in seconds
47     NULL
48 };
49
50 enum var_name {
51     VAR_IN_W , VAR_IW,
52     VAR_IN_H , VAR_IH,
53     VAR_OUT_W, VAR_OW,
54     VAR_OUT_H, VAR_OH,
55     VAR_HSUB, VAR_VSUB,
56     VAR_N,
57     VAR_T,
58     VAR_VARS_NB
59 };
60
61 typedef struct {
62     const AVClass *class;
63     double angle;
64     char *angle_expr_str;   ///< expression for the angle
65     AVExpr *angle_expr;     ///< parsed expression for the angle
66     char *outw_expr_str, *outh_expr_str;
67     int outh, outw;
68     uint8_t fillcolor[4];   ///< color expressed either in YUVA or RGBA colorspace for the padding area
69     char *fillcolor_str;
70     int fillcolor_enable;
71     int hsub, vsub;
72     int nb_planes;
73     int use_bilinear;
74     uint8_t *line[4];
75     int linestep[4];
76     float sinx, cosx;
77     double var_values[VAR_VARS_NB];
78 } RotContext;
79
80 #define OFFSET(x) offsetof(RotContext, x)
81 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
82
83 static const AVOption rotate_options[] = {
84     { "angle",     "set angle (in radians)",       OFFSET(angle_expr_str), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
85     { "a",         "set angle (in radians)",       OFFSET(angle_expr_str), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
86     { "out_w",     "set output width expression",  OFFSET(outw_expr_str), AV_OPT_TYPE_STRING, {.str="iw"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
87     { "ow",        "set output width expression",  OFFSET(outw_expr_str), AV_OPT_TYPE_STRING, {.str="iw"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
88     { "out_h",     "set output height expression", OFFSET(outh_expr_str), AV_OPT_TYPE_STRING, {.str="ih"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
89     { "oh",        "set output width expression",  OFFSET(outh_expr_str), AV_OPT_TYPE_STRING, {.str="ih"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
90     { "fillcolor", "set background fill color",    OFFSET(fillcolor_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
91     { "c",         "set background fill color",    OFFSET(fillcolor_str), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, .flags=FLAGS },
92     { "bilinear",  "use bilinear interpolation",   OFFSET(use_bilinear),  AV_OPT_TYPE_INT, {.i64=1}, 0, 1, .flags=FLAGS },
93     { NULL }
94 };
95
96 AVFILTER_DEFINE_CLASS(rotate);
97
98 static av_cold int init(AVFilterContext *ctx)
99 {
100     RotContext *rot = ctx->priv;
101
102     if (!strcmp(rot->fillcolor_str, "none"))
103         rot->fillcolor_enable = 0;
104     else if (av_parse_color(rot->fillcolor, rot->fillcolor_str, -1, ctx) >= 0)
105         rot->fillcolor_enable = 1;
106     else
107         return AVERROR(EINVAL);
108     return 0;
109 }
110
111 static av_cold void uninit(AVFilterContext *ctx)
112 {
113     RotContext *rot = ctx->priv;
114     int i;
115
116     for (i = 0; i < 4; i++)
117         av_freep(&rot->line[i]);
118
119     av_expr_free(rot->angle_expr);
120     rot->angle_expr = NULL;
121 }
122
123 static int query_formats(AVFilterContext *ctx)
124 {
125     static enum PixelFormat pix_fmts[] = {
126         AV_PIX_FMT_ARGB,   AV_PIX_FMT_RGBA,
127         AV_PIX_FMT_ABGR,   AV_PIX_FMT_BGRA,
128         AV_PIX_FMT_RGB24,  AV_PIX_FMT_BGR24,
129         AV_PIX_FMT_GRAY8,
130         AV_PIX_FMT_YUV444P,  AV_PIX_FMT_YUVJ444P,
131         AV_PIX_FMT_YUV420P,  AV_PIX_FMT_YUVJ420P,
132         AV_PIX_FMT_YUVA444P, AV_PIX_FMT_YUVA420P,
133         AV_PIX_FMT_NONE
134     };
135
136     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
137     return 0;
138 }
139
140 static double get_rotated_w(void *opaque, double angle)
141 {
142     RotContext *rot = opaque;
143     double inw = rot->var_values[VAR_IN_W];
144     double inh = rot->var_values[VAR_IN_H];
145     float sinx = sin(angle);
146     float cosx = cos(angle);
147
148     return FFMAX(0, inh * sinx) + FFMAX(0, -inw * cosx) +
149            FFMAX(0, inw * cosx) + FFMAX(0, -inh * sinx);
150 }
151
152 static double get_rotated_h(void *opaque, double angle)
153 {
154     RotContext *rot = opaque;
155     double inw = rot->var_values[VAR_IN_W];
156     double inh = rot->var_values[VAR_IN_H];
157     float sinx = sin(angle);
158     float cosx = cos(angle);
159
160     return FFMAX(0, -inh * cosx) + FFMAX(0, -inw * sinx) +
161            FFMAX(0,  inh * cosx) + FFMAX(0,  inw * sinx);
162 }
163
164 static double (* const func1[])(void *, double) = {
165     get_rotated_w,
166     get_rotated_h,
167     NULL
168 };
169
170 static const char * const func1_names[] = {
171     "rotw",
172     "roth",
173     NULL
174 };
175
176 static int config_props(AVFilterLink *outlink)
177 {
178     AVFilterContext *ctx = outlink->src;
179     RotContext *rot = ctx->priv;
180     AVFilterLink *inlink = ctx->inputs[0];
181     const AVPixFmtDescriptor *pixdesc = av_pix_fmt_desc_get(inlink->format);
182     uint8_t rgba_color[4];
183     int is_packed_rgba, ret;
184     double res;
185     char *expr;
186
187     rot->hsub = pixdesc->log2_chroma_w;
188     rot->vsub = pixdesc->log2_chroma_h;
189
190     rot->var_values[VAR_IN_W] = rot->var_values[VAR_IW] = inlink->w;
191     rot->var_values[VAR_IN_H] = rot->var_values[VAR_IH] = inlink->h;
192     rot->var_values[VAR_HSUB] = 1<<rot->hsub;
193     rot->var_values[VAR_VSUB] = 1<<rot->vsub;
194     rot->var_values[VAR_N] = NAN;
195     rot->var_values[VAR_T] = NAN;
196     rot->var_values[VAR_OUT_W] = rot->var_values[VAR_OW] = NAN;
197     rot->var_values[VAR_OUT_H] = rot->var_values[VAR_OH] = NAN;
198
199     av_expr_free(rot->angle_expr);
200     rot->angle_expr = NULL;
201     if ((ret = av_expr_parse(&rot->angle_expr, expr = rot->angle_expr_str, var_names,
202                              func1_names, func1, NULL, NULL, 0, ctx)) < 0) {
203         av_log(ctx, AV_LOG_ERROR,
204                "Error occurred parsing angle expression '%s'\n", rot->angle_expr_str);
205         return ret;
206     }
207
208 #define SET_SIZE_EXPR(name, opt_name) do {                                         \
209     ret = av_expr_parse_and_eval(&res, expr = rot->name##_expr_str,                \
210                                  var_names, rot->var_values,                       \
211                                  func1_names, func1, NULL, NULL, rot, 0, ctx);     \
212     if (ret < 0 || isnan(res) || isinf(res) || res <= 0) {                         \
213         av_log(ctx, AV_LOG_ERROR,                                                  \
214                "Error parsing or evaluating expression for option %s: "            \
215                "invalid expression '%s' or non-positive or indefinite value %f\n", \
216                opt_name, expr, res);                                               \
217         return ret;                                                                \
218     }                                                                              \
219 } while (0)
220
221     /* evaluate width and height */
222     av_expr_parse_and_eval(&res, expr = rot->outw_expr_str, var_names, rot->var_values,
223                            func1_names, func1, NULL, NULL, rot, 0, ctx);
224     rot->var_values[VAR_OUT_W] = rot->var_values[VAR_OW] = res;
225     rot->outw = res + 0.5;
226     SET_SIZE_EXPR(outh, "out_w");
227     rot->var_values[VAR_OUT_H] = rot->var_values[VAR_OH] = res;
228     rot->outh = res + 0.5;
229
230     /* evaluate the width again, as it may depend on the evaluated output height */
231     SET_SIZE_EXPR(outw, "out_h");
232     rot->var_values[VAR_OUT_W] = rot->var_values[VAR_OW] = res;
233     rot->outw = res + 0.5;
234
235     /* compute number of planes */
236     rot->nb_planes = av_pix_fmt_count_planes(inlink->format);
237     outlink->w = rot->outw;
238     outlink->h = rot->outh;
239
240     memcpy(rgba_color, rot->fillcolor, sizeof(rgba_color));
241     ff_fill_line_with_color(rot->line, rot->linestep, outlink->w, rot->fillcolor,
242                             outlink->format, rgba_color, &is_packed_rgba, NULL);
243     av_log(ctx, AV_LOG_INFO,
244            "w:%d h:%d -> w:%d h:%d bgcolor:0x%02X%02X%02X%02X[%s]\n",
245            inlink->w, inlink->h, outlink->w, outlink->h,
246            rot->fillcolor[0], rot->fillcolor[1], rot->fillcolor[2], rot->fillcolor[3],
247            is_packed_rgba ? "rgba" : "yuva");
248
249     return 0;
250 }
251
252 #define FIXP (1<<16)
253 #define INT_PI 205887 //(M_PI * FIXP)
254
255 /**
256  * Compute the sin of a using integer values.
257  * Input and output values are scaled by FIXP.
258  */
259 static int64_t int_sin(int64_t a)
260 {
261     int64_t a2, res = 0;
262     int i;
263     if (a < 0) a = INT_PI-a; // 0..inf
264     a %= 2 * INT_PI;         // 0..2PI
265
266     if (a >= INT_PI*3/2) a -= 2*INT_PI;  // -PI/2 .. 3PI/2
267     if (a >= INT_PI/2  ) a = INT_PI - a; // -PI/2 ..  PI/2
268
269     /* compute sin using Taylor series approximated to the third term */
270     a2 = (a*a)/FIXP;
271     for (i = 2; i < 7; i += 2) {
272         res += a;
273         a = -a*a2 / (FIXP*i*(i+1));
274     }
275     return res;
276 }
277
278 /**
279  * Interpolate the color in src at position x and y using bilinear
280  * interpolation.
281  */
282 static uint8_t *interpolate_bilinear(uint8_t *dst_color,
283                                      const uint8_t *src, int src_linesize, int src_linestep,
284                                      int x, int y, int max_x, int max_y)
285 {
286     int int_x = av_clip(x>>16, 0, max_x);
287     int int_y = av_clip(y>>16, 0, max_y);
288     int frac_x = x&0xFFFF;
289     int frac_y = y&0xFFFF;
290     int i;
291     int int_x1 = FFMIN(int_x+1, max_x);
292     int int_y1 = FFMIN(int_y+1, max_y);
293
294     for (i = 0; i < src_linestep; i++) {
295         int s00 = src[src_linestep * int_x  + i + src_linesize * int_y ];
296         int s01 = src[src_linestep * int_x1 + i + src_linesize * int_y ];
297         int s10 = src[src_linestep * int_x  + i + src_linesize * int_y1];
298         int s11 = src[src_linestep * int_x1 + i + src_linesize * int_y1];
299         int s0 = (((1<<16) - frac_x)*s00 + frac_x*s01);
300         int s1 = (((1<<16) - frac_x)*s10 + frac_x*s11);
301
302         dst_color[i] = ((int64_t)((1<<16) - frac_y)*s0 + (int64_t)frac_y*s1) >> 32;
303     }
304
305     return dst_color;
306 }
307
308 #define TS2T(ts, tb) ((ts) == AV_NOPTS_VALUE ? NAN : (double)(ts)*av_q2d(tb))
309
310 static int filter_frame(AVFilterLink *inlink, AVFrame *in)
311 {
312     AVFilterContext *ctx = inlink->dst;
313     AVFilterLink *outlink = ctx->outputs[0];
314     AVFrame *out;
315     RotContext *rot = ctx->priv;
316     int angle_int, s, c, plane;
317     double res;
318
319     out = ff_get_video_buffer(outlink, outlink->w, outlink->h);
320     if (!out) {
321         av_frame_free(&in);
322         return AVERROR(ENOMEM);
323     }
324     av_frame_copy_props(out, in);
325
326     rot->var_values[VAR_N] = inlink->frame_count;
327     rot->var_values[VAR_T] = TS2T(in->pts, inlink->time_base);
328     rot->angle = res = av_expr_eval(rot->angle_expr, rot->var_values, rot);
329
330     av_log(ctx, AV_LOG_DEBUG, "n:%f time:%f angle:%f/PI\n",
331            rot->var_values[VAR_N], rot->var_values[VAR_T], rot->angle/M_PI);
332
333     angle_int = res * FIXP;
334     s = int_sin(angle_int);
335     c = int_sin(angle_int + INT_PI/2);
336
337     /* fill background */
338     if (rot->fillcolor_enable)
339         ff_draw_rectangle(out->data, out->linesize,
340                           rot->line, rot->linestep, rot->hsub, rot->vsub,
341                           0, 0, outlink->w, outlink->h);
342
343     for (plane = 0; plane < rot->nb_planes; plane++) {
344         int hsub = plane == 1 || plane == 2 ? rot->hsub : 0;
345         int vsub = plane == 1 || plane == 2 ? rot->vsub : 0;
346         int inw  = FF_CEIL_RSHIFT(inlink->w, hsub);
347         int inh  = FF_CEIL_RSHIFT(inlink->h, vsub);
348         int outw = FF_CEIL_RSHIFT(outlink->w, hsub);
349         int outh = FF_CEIL_RSHIFT(outlink->h, hsub);
350
351         const int xi = -outw/2 * c;
352         const int yi =  outw/2 * s;
353         int xprime = -outh/2 * s;
354         int yprime = -outh/2 * c;
355         int i, j, x, y;
356
357         for (j = 0; j < outh; j++) {
358             x = xprime + xi + FIXP*inw/2;
359             y = yprime + yi + FIXP*inh/2;
360
361             for (i = 0; i < outw; i++) {
362                 int32_t v;
363                 int x1, y1;
364                 uint8_t *pin, *pout;
365                 x += c;
366                 y -= s;
367                 x1 = x>>16;
368                 y1 = y>>16;
369
370                 /* the out-of-range values avoid border artifacts */
371                 if (x1 >= -1 && x1 <= inw && y1 >= -1 && y1 <= inh) {
372                     uint8_t inp_inv[4]; /* interpolated input value */
373                     pout = out->data[plane] + j * out->linesize[plane] + i * rot->linestep[plane];
374                     if (rot->use_bilinear) {
375                         pin = interpolate_bilinear(inp_inv,
376                                                    in->data[plane], in->linesize[plane], rot->linestep[plane],
377                                                    x, y, inw-1, inh-1);
378                     } else {
379                         int x2 = av_clip(x1, 0, inw-1);
380                         int y2 = av_clip(y1, 0, inh-1);
381                         pin = in->data[plane] + y2 * in->linesize[plane] + x2 * rot->linestep[plane];
382                     }
383                     switch (rot->linestep[plane]) {
384                     case 1:
385                         *pout = *pin;
386                         break;
387                     case 2:
388                         *((uint16_t *)pout) = *((uint16_t *)pin);
389                         break;
390                     case 3:
391                         v = AV_RB24(pin);
392                         AV_WB24(pout, v);
393                         break;
394                     case 4:
395                         *((uint32_t *)pout) = *((uint32_t *)pin);
396                         break;
397                     default:
398                         memcpy(pout, pin, rot->linestep[plane]);
399                         break;
400                     }
401                 }
402             }
403             xprime += s;
404             yprime += c;
405         }
406     }
407
408     av_frame_free(&in);
409     return ff_filter_frame(outlink, out);
410 }
411
412 static int process_command(AVFilterContext *ctx, const char *cmd, const char *args,
413                            char *res, int res_len, int flags)
414 {
415     RotContext *rot = ctx->priv;
416     int ret;
417
418     if (!strcmp(cmd, "angle") || !strcmp(cmd, "a")) {
419         AVExpr *old = rot->angle_expr;
420         ret = av_expr_parse(&rot->angle_expr, args, var_names,
421                             NULL, NULL, NULL, NULL, 0, ctx);
422         if (ret < 0) {
423             av_log(ctx, AV_LOG_ERROR,
424                    "Error when parsing the expression '%s' for angle command\n", args);
425             rot->angle_expr = old;
426             return ret;
427         }
428         av_expr_free(old);
429     } else
430         ret = AVERROR(ENOSYS);
431
432     return ret;
433 }
434
435 static const AVFilterPad rotate_inputs[] = {
436     {
437         .name         = "default",
438         .type         = AVMEDIA_TYPE_VIDEO,
439         .filter_frame = filter_frame,
440     },
441     { NULL }
442 };
443
444 static const AVFilterPad rotate_outputs[] = {
445     {
446         .name         = "default",
447         .type         = AVMEDIA_TYPE_VIDEO,
448         .config_props = config_props,
449     },
450     { NULL }
451 };
452
453 AVFilter avfilter_vf_rotate = {
454     .name          = "rotate",
455     .description   = NULL_IF_CONFIG_SMALL("Rotate the input image."),
456     .priv_size     = sizeof(RotContext),
457     .init          = init,
458     .uninit        = uninit,
459     .query_formats = query_formats,
460     .process_command = process_command,
461     .inputs        = rotate_inputs,
462     .outputs       = rotate_outputs,
463     .priv_class    = &rotate_class,
464     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
465 };