]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_drawtext.c
Merge commit 'c8bca9fe466f810fd484e2c6db7ef7bc83b5a943'
[ffmpeg] / libavfilter / vf_drawtext.c
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
3  * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
4  * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22
23 /**
24  * @file
25  * drawtext filter, based on the original vhook/drawtext.c
26  * filter by Gustavo Sverzut Barbieri
27  */
28
29 #include "config.h"
30
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <time.h>
37 #if HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #include <fenv.h>
41
42 #if CONFIG_LIBFONTCONFIG
43 #include <fontconfig/fontconfig.h>
44 #endif
45
46 #include "libavutil/avstring.h"
47 #include "libavutil/bprint.h"
48 #include "libavutil/common.h"
49 #include "libavutil/file.h"
50 #include "libavutil/eval.h"
51 #include "libavutil/opt.h"
52 #include "libavutil/random_seed.h"
53 #include "libavutil/parseutils.h"
54 #include "libavutil/timecode.h"
55 #include "libavutil/time_internal.h"
56 #include "libavutil/tree.h"
57 #include "libavutil/lfg.h"
58 #include "avfilter.h"
59 #include "drawutils.h"
60 #include "formats.h"
61 #include "internal.h"
62 #include "video.h"
63
64 #if CONFIG_LIBFRIBIDI
65 #include <fribidi.h>
66 #endif
67
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #include FT_GLYPH_H
71 #include FT_STROKER_H
72
73 static const char *const var_names[] = {
74     "dar",
75     "hsub", "vsub",
76     "line_h", "lh",           ///< line height, same as max_glyph_h
77     "main_h", "h", "H",       ///< height of the input video
78     "main_w", "w", "W",       ///< width  of the input video
79     "max_glyph_a", "ascent",  ///< max glyph ascent
80     "max_glyph_d", "descent", ///< min glyph descent
81     "max_glyph_h",            ///< max glyph height
82     "max_glyph_w",            ///< max glyph width
83     "n",                      ///< number of frame
84     "sar",
85     "t",                      ///< timestamp expressed in seconds
86     "text_h", "th",           ///< height of the rendered text
87     "text_w", "tw",           ///< width  of the rendered text
88     "x",
89     "y",
90     "pict_type",
91     NULL
92 };
93
94 static const char *const fun2_names[] = {
95     "rand"
96 };
97
98 static double drand(void *opaque, double min, double max)
99 {
100     return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
101 }
102
103 typedef double (*eval_func2)(void *, double a, double b);
104
105 static const eval_func2 fun2[] = {
106     drand,
107     NULL
108 };
109
110 enum var_name {
111     VAR_DAR,
112     VAR_HSUB, VAR_VSUB,
113     VAR_LINE_H, VAR_LH,
114     VAR_MAIN_H, VAR_h, VAR_H,
115     VAR_MAIN_W, VAR_w, VAR_W,
116     VAR_MAX_GLYPH_A, VAR_ASCENT,
117     VAR_MAX_GLYPH_D, VAR_DESCENT,
118     VAR_MAX_GLYPH_H,
119     VAR_MAX_GLYPH_W,
120     VAR_N,
121     VAR_SAR,
122     VAR_T,
123     VAR_TEXT_H, VAR_TH,
124     VAR_TEXT_W, VAR_TW,
125     VAR_X,
126     VAR_Y,
127     VAR_PICT_TYPE,
128     VAR_VARS_NB
129 };
130
131 enum expansion_mode {
132     EXP_NONE,
133     EXP_NORMAL,
134     EXP_STRFTIME,
135 };
136
137 typedef struct DrawTextContext {
138     const AVClass *class;
139     int exp_mode;                   ///< expansion mode to use for the text
140     int reinit;                     ///< tells if the filter is being reinited
141 #if CONFIG_LIBFONTCONFIG
142     uint8_t *font;              ///< font to be used
143 #endif
144     uint8_t *fontfile;              ///< font to be used
145     uint8_t *text;                  ///< text to be drawn
146     AVBPrint expanded_text;         ///< used to contain the expanded text
147     uint8_t *fontcolor_expr;        ///< fontcolor expression to evaluate
148     AVBPrint expanded_fontcolor;    ///< used to contain the expanded fontcolor spec
149     int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
150     FT_Vector *positions;           ///< positions for each element in the text
151     size_t nb_positions;            ///< number of elements of positions array
152     char *textfile;                 ///< file with text to be drawn
153     int x;                          ///< x position to start drawing text
154     int y;                          ///< y position to start drawing text
155     int max_glyph_w;                ///< max glyph width
156     int max_glyph_h;                ///< max glyph height
157     int shadowx, shadowy;
158     int borderw;                    ///< border width
159     char *fontsize_expr;            ///< expression for fontsize
160     AVExpr *fontsize_pexpr;         ///< parsed expressions for fontsize
161     unsigned int fontsize;          ///< font size to use
162     unsigned int default_fontsize;  ///< default font size to use
163
164     int line_spacing;               ///< lines spacing in pixels
165     short int draw_box;             ///< draw box around text - true or false
166     int boxborderw;                 ///< box border width
167     int use_kerning;                ///< font kerning is used - true/false
168     int tabsize;                    ///< tab size
169     int fix_bounds;                 ///< do we let it go out of frame bounds - t/f
170
171     FFDrawContext dc;
172     FFDrawColor fontcolor;          ///< foreground color
173     FFDrawColor shadowcolor;        ///< shadow color
174     FFDrawColor bordercolor;        ///< border color
175     FFDrawColor boxcolor;           ///< background color
176
177     FT_Library library;             ///< freetype font library handle
178     FT_Face face;                   ///< freetype font face handle
179     FT_Stroker stroker;             ///< freetype stroker handle
180     struct AVTreeNode *glyphs;      ///< rendered glyphs, stored using the UTF-32 char code
181     char *x_expr;                   ///< expression for x position
182     char *y_expr;                   ///< expression for y position
183     AVExpr *x_pexpr, *y_pexpr;      ///< parsed expressions for x and y
184     int64_t basetime;               ///< base pts time in the real world for display
185     double var_values[VAR_VARS_NB];
186     char   *a_expr;
187     AVExpr *a_pexpr;
188     int alpha;
189     AVLFG  prng;                    ///< random
190     char       *tc_opt_string;      ///< specified timecode option string
191     AVRational  tc_rate;            ///< frame rate for timecode
192     AVTimecode  tc;                 ///< timecode context
193     int tc24hmax;                   ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
194     int reload;                     ///< reload text file for each frame
195     int start_number;               ///< starting frame number for n/frame_num var
196 #if CONFIG_LIBFRIBIDI
197     int text_shaping;               ///< 1 to shape the text before drawing it
198 #endif
199     AVDictionary *metadata;
200 } DrawTextContext;
201
202 #define OFFSET(x) offsetof(DrawTextContext, x)
203 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
204
205 static const AVOption drawtext_options[]= {
206     {"fontfile",    "set font file",        OFFSET(fontfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
207     {"text",        "set text",             OFFSET(text),               AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
208     {"textfile",    "set text file",        OFFSET(textfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
209     {"fontcolor",   "set foreground color", OFFSET(fontcolor.rgba),     AV_OPT_TYPE_COLOR,  {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
210     {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, CHAR_MIN, CHAR_MAX, FLAGS},
211     {"boxcolor",    "set box color",        OFFSET(boxcolor.rgba),      AV_OPT_TYPE_COLOR,  {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
212     {"bordercolor", "set border color",     OFFSET(bordercolor.rgba),   AV_OPT_TYPE_COLOR,  {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
213     {"shadowcolor", "set shadow color",     OFFSET(shadowcolor.rgba),   AV_OPT_TYPE_COLOR,  {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
214     {"box",         "set box",              OFFSET(draw_box),           AV_OPT_TYPE_BOOL,   {.i64=0},     0,        1       , FLAGS},
215     {"boxborderw",  "set box border width", OFFSET(boxborderw),         AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
216     {"line_spacing",  "set line spacing in pixels", OFFSET(line_spacing),   AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX,FLAGS},
217     {"fontsize",    "set font size",        OFFSET(fontsize_expr),      AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX , FLAGS},
218     {"x",           "set x expression",     OFFSET(x_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX, FLAGS},
219     {"y",           "set y expression",     OFFSET(y_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX, FLAGS},
220     {"shadowx",     "set shadow x offset",  OFFSET(shadowx),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
221     {"shadowy",     "set shadow y offset",  OFFSET(shadowy),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
222     {"borderw",     "set border width",     OFFSET(borderw),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
223     {"tabsize",     "set tab size",         OFFSET(tabsize),            AV_OPT_TYPE_INT,    {.i64=4},     0,        INT_MAX , FLAGS},
224     {"basetime",    "set base time",        OFFSET(basetime),           AV_OPT_TYPE_INT64,  {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
225 #if CONFIG_LIBFONTCONFIG
226     { "font",        "Font name",            OFFSET(font),               AV_OPT_TYPE_STRING, { .str = "Sans" },           .flags = FLAGS },
227 #endif
228
229     {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
230         {"none",     "set no expansion",                    OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE},     0, 0, FLAGS, "expansion"},
231         {"normal",   "set normal expansion",                OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL},   0, 0, FLAGS, "expansion"},
232         {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
233
234     {"timecode",        "set initial timecode",             OFFSET(tc_opt_string), AV_OPT_TYPE_STRING,   {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
235     {"tc24hmax",        "set 24 hours max (timecode only)", OFFSET(tc24hmax),      AV_OPT_TYPE_BOOL,     {.i64=0},           0,        1, FLAGS},
236     {"timecode_rate",   "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
237     {"r",               "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
238     {"rate",            "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
239     {"reload",     "reload text file for each frame",                       OFFSET(reload),     AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
240     { "alpha",       "apply alpha while rendering", OFFSET(a_expr),      AV_OPT_TYPE_STRING, { .str = "1"     },          .flags = FLAGS },
241     {"fix_bounds", "check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
242     {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
243
244 #if CONFIG_LIBFRIBIDI
245     {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
246 #endif
247
248     /* FT_LOAD_* flags */
249     { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, "ft_load_flags" },
250         { "default",                     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT },                     .flags = FLAGS, .unit = "ft_load_flags" },
251         { "no_scale",                    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE },                    .flags = FLAGS, .unit = "ft_load_flags" },
252         { "no_hinting",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING },                  .flags = FLAGS, .unit = "ft_load_flags" },
253         { "render",                      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER },                      .flags = FLAGS, .unit = "ft_load_flags" },
254         { "no_bitmap",                   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP },                   .flags = FLAGS, .unit = "ft_load_flags" },
255         { "vertical_layout",             NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT },             .flags = FLAGS, .unit = "ft_load_flags" },
256         { "force_autohint",              NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT },              .flags = FLAGS, .unit = "ft_load_flags" },
257         { "crop_bitmap",                 NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP },                 .flags = FLAGS, .unit = "ft_load_flags" },
258         { "pedantic",                    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC },                    .flags = FLAGS, .unit = "ft_load_flags" },
259         { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
260         { "no_recurse",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE },                  .flags = FLAGS, .unit = "ft_load_flags" },
261         { "ignore_transform",            NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM },            .flags = FLAGS, .unit = "ft_load_flags" },
262         { "monochrome",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME },                  .flags = FLAGS, .unit = "ft_load_flags" },
263         { "linear_design",               NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN },               .flags = FLAGS, .unit = "ft_load_flags" },
264         { "no_autohint",                 NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT },                 .flags = FLAGS, .unit = "ft_load_flags" },
265     { NULL }
266 };
267
268 AVFILTER_DEFINE_CLASS(drawtext);
269
270 #undef __FTERRORS_H__
271 #define FT_ERROR_START_LIST {
272 #define FT_ERRORDEF(e, v, s) { (e), (s) },
273 #define FT_ERROR_END_LIST { 0, NULL } };
274
275 static const struct ft_error {
276     int err;
277     const char *err_msg;
278 } ft_errors[] =
279 #include FT_ERRORS_H
280
281 #define FT_ERRMSG(e) ft_errors[e].err_msg
282
283 typedef struct Glyph {
284     FT_Glyph glyph;
285     FT_Glyph border_glyph;
286     uint32_t code;
287     unsigned int fontsize;
288     FT_Bitmap bitmap; ///< array holding bitmaps of font
289     FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
290     FT_BBox bbox;
291     int advance;
292     int bitmap_left;
293     int bitmap_top;
294 } Glyph;
295
296 static int glyph_cmp(const void *key, const void *b)
297 {
298     const Glyph *a = key, *bb = b;
299     int64_t diff = (int64_t)a->code - (int64_t)bb->code;
300
301     if (diff != 0)
302          return diff > 0 ? 1 : -1;
303     else
304          return FFDIFFSIGN((int64_t)a->fontsize, (int64_t)bb->fontsize);
305 }
306
307 /**
308  * Load glyphs corresponding to the UTF-32 codepoint code.
309  */
310 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
311 {
312     DrawTextContext *s = ctx->priv;
313     FT_BitmapGlyph bitmapglyph;
314     Glyph *glyph;
315     struct AVTreeNode *node = NULL;
316     int ret;
317
318     /* load glyph into s->face->glyph */
319     if (FT_Load_Char(s->face, code, s->ft_load_flags))
320         return AVERROR(EINVAL);
321
322     glyph = av_mallocz(sizeof(*glyph));
323     if (!glyph) {
324         ret = AVERROR(ENOMEM);
325         goto error;
326     }
327     glyph->code  = code;
328     glyph->fontsize = s->fontsize;
329
330     if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
331         ret = AVERROR(EINVAL);
332         goto error;
333     }
334     if (s->borderw) {
335         glyph->border_glyph = glyph->glyph;
336         if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
337             FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
338             ret = AVERROR_EXTERNAL;
339             goto error;
340         }
341         bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
342         glyph->border_bitmap = bitmapglyph->bitmap;
343     }
344     if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
345         ret = AVERROR_EXTERNAL;
346         goto error;
347     }
348     bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
349
350     glyph->bitmap      = bitmapglyph->bitmap;
351     glyph->bitmap_left = bitmapglyph->left;
352     glyph->bitmap_top  = bitmapglyph->top;
353     glyph->advance     = s->face->glyph->advance.x >> 6;
354
355     /* measure text height to calculate text_height (or the maximum text height) */
356     FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
357
358     /* cache the newly created glyph */
359     if (!(node = av_tree_node_alloc())) {
360         ret = AVERROR(ENOMEM);
361         goto error;
362     }
363     av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
364
365     if (glyph_ptr)
366         *glyph_ptr = glyph;
367     return 0;
368
369 error:
370     if (glyph)
371         av_freep(&glyph->glyph);
372
373     av_freep(&glyph);
374     av_freep(&node);
375     return ret;
376 }
377
378 static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
379 {
380     int err;
381     DrawTextContext *s = ctx->priv;
382
383     if ((err = FT_Set_Pixel_Sizes(s->face, 0, fontsize))) {
384         av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
385                fontsize, FT_ERRMSG(err));
386         return AVERROR(EINVAL);
387     }
388
389     s->fontsize = fontsize;
390
391     return 0;
392 }
393
394 static av_cold int parse_fontsize(AVFilterContext *ctx)
395 {
396     DrawTextContext *s = ctx->priv;
397     int err;
398
399     if (s->fontsize_pexpr)
400         return 0;
401
402     if (s->fontsize_expr == NULL)
403         return AVERROR(EINVAL);
404
405     if ((err = av_expr_parse(&s->fontsize_pexpr, s->fontsize_expr, var_names,
406                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
407         return err;
408
409     return 0;
410 }
411
412 static av_cold int update_fontsize(AVFilterContext *ctx)
413 {
414     DrawTextContext *s = ctx->priv;
415     unsigned int fontsize = s->default_fontsize;
416     int err;
417     double size, roundedsize;
418
419     // if no fontsize specified use the default
420     if (s->fontsize_expr != NULL) {
421         if ((err = parse_fontsize(ctx)) < 0)
422            return err;
423
424         size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
425
426         if (!isnan(size)) {
427             roundedsize = round(size);
428             // test for overflow before cast
429             if (!(roundedsize > INT_MIN && roundedsize < INT_MAX)) {
430                 av_log(ctx, AV_LOG_ERROR, "fontsize overflow\n");
431                 return AVERROR(EINVAL);
432             }
433
434             fontsize = roundedsize;
435         }
436     }
437
438     if (fontsize == 0)
439         fontsize = 1;
440
441     // no change
442     if (fontsize == s->fontsize)
443         return 0;
444
445     return set_fontsize(ctx, fontsize);
446 }
447
448 static int load_font_file(AVFilterContext *ctx, const char *path, int index)
449 {
450     DrawTextContext *s = ctx->priv;
451     int err;
452
453     err = FT_New_Face(s->library, path, index, &s->face);
454     if (err) {
455 #if !CONFIG_LIBFONTCONFIG
456         av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
457                s->fontfile, FT_ERRMSG(err));
458 #endif
459         return AVERROR(EINVAL);
460     }
461     return 0;
462 }
463
464 #if CONFIG_LIBFONTCONFIG
465 static int load_font_fontconfig(AVFilterContext *ctx)
466 {
467     DrawTextContext *s = ctx->priv;
468     FcConfig *fontconfig;
469     FcPattern *pat, *best;
470     FcResult result = FcResultMatch;
471     FcChar8 *filename;
472     int index;
473     double size;
474     int err = AVERROR(ENOENT);
475     int parse_err;
476
477     fontconfig = FcInitLoadConfigAndFonts();
478     if (!fontconfig) {
479         av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
480         return AVERROR_UNKNOWN;
481     }
482     pat = FcNameParse(s->fontfile ? s->fontfile :
483                           (uint8_t *)(intptr_t)"default");
484     if (!pat) {
485         av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
486         return AVERROR(EINVAL);
487     }
488
489     FcPatternAddString(pat, FC_FAMILY, s->font);
490
491     parse_err = parse_fontsize(ctx);
492     if (!parse_err) {
493         double size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
494
495         if (isnan(size)) {
496             av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
497             return AVERROR(EINVAL);
498         }
499
500         FcPatternAddDouble(pat, FC_SIZE, size);
501     }
502
503     FcDefaultSubstitute(pat);
504
505     if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
506         av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
507         FcPatternDestroy(pat);
508         return AVERROR(ENOMEM);
509     }
510
511     best = FcFontMatch(fontconfig, pat, &result);
512     FcPatternDestroy(pat);
513
514     if (!best || result != FcResultMatch) {
515         av_log(ctx, AV_LOG_ERROR,
516                "Cannot find a valid font for the family %s\n",
517                s->font);
518         goto fail;
519     }
520
521     if (
522         FcPatternGetInteger(best, FC_INDEX, 0, &index   ) != FcResultMatch ||
523         FcPatternGetDouble (best, FC_SIZE,  0, &size    ) != FcResultMatch) {
524         av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
525         return AVERROR(EINVAL);
526     }
527
528     if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
529         av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
530                s->font);
531         goto fail;
532     }
533
534     av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
535     if (parse_err)
536         s->default_fontsize = size + 0.5;
537
538     err = load_font_file(ctx, filename, index);
539     if (err)
540         return err;
541     FcConfigDestroy(fontconfig);
542 fail:
543     FcPatternDestroy(best);
544     return err;
545 }
546 #endif
547
548 static int load_font(AVFilterContext *ctx)
549 {
550     DrawTextContext *s = ctx->priv;
551     int err;
552
553     /* load the face, and set up the encoding, which is by default UTF-8 */
554     err = load_font_file(ctx, s->fontfile, 0);
555     if (!err)
556         return 0;
557 #if CONFIG_LIBFONTCONFIG
558     err = load_font_fontconfig(ctx);
559     if (!err)
560         return 0;
561 #endif
562     return err;
563 }
564
565 static int load_textfile(AVFilterContext *ctx)
566 {
567     DrawTextContext *s = ctx->priv;
568     int err;
569     uint8_t *textbuf;
570     uint8_t *tmp;
571     size_t textbuf_size;
572
573     if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
574         av_log(ctx, AV_LOG_ERROR,
575                "The text file '%s' could not be read or is empty\n",
576                s->textfile);
577         return err;
578     }
579
580     if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
581         av_file_unmap(textbuf, textbuf_size);
582         return AVERROR(ENOMEM);
583     }
584     s->text = tmp;
585     memcpy(s->text, textbuf, textbuf_size);
586     s->text[textbuf_size] = 0;
587     av_file_unmap(textbuf, textbuf_size);
588
589     return 0;
590 }
591
592 static inline int is_newline(uint32_t c)
593 {
594     return c == '\n' || c == '\r' || c == '\f' || c == '\v';
595 }
596
597 #if CONFIG_LIBFRIBIDI
598 static int shape_text(AVFilterContext *ctx)
599 {
600     DrawTextContext *s = ctx->priv;
601     uint8_t *tmp;
602     int ret = AVERROR(ENOMEM);
603     static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
604                                       FRIBIDI_FLAGS_ARABIC;
605     FriBidiChar *unicodestr = NULL;
606     FriBidiStrIndex len;
607     FriBidiParType direction = FRIBIDI_PAR_LTR;
608     FriBidiStrIndex line_start = 0;
609     FriBidiStrIndex line_end = 0;
610     FriBidiLevel *embedding_levels = NULL;
611     FriBidiArabicProp *ar_props = NULL;
612     FriBidiCharType *bidi_types = NULL;
613     FriBidiStrIndex i,j;
614
615     len = strlen(s->text);
616     if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
617         goto out;
618     }
619     len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
620                                      s->text, len, unicodestr);
621
622     bidi_types = av_malloc_array(len, sizeof(*bidi_types));
623     if (!bidi_types) {
624         goto out;
625     }
626
627     fribidi_get_bidi_types(unicodestr, len, bidi_types);
628
629     embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
630     if (!embedding_levels) {
631         goto out;
632     }
633
634     if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
635                                           embedding_levels)) {
636         goto out;
637     }
638
639     ar_props = av_malloc_array(len, sizeof(*ar_props));
640     if (!ar_props) {
641         goto out;
642     }
643
644     fribidi_get_joining_types(unicodestr, len, ar_props);
645     fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
646     fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
647
648     for (line_end = 0, line_start = 0; line_end < len; line_end++) {
649         if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
650             if (!fribidi_reorder_line(flags, bidi_types,
651                                       line_end - line_start + 1, line_start,
652                                       direction, embedding_levels, unicodestr,
653                                       NULL)) {
654                 goto out;
655             }
656             line_start = line_end + 1;
657         }
658     }
659
660     /* Remove zero-width fill chars put in by libfribidi */
661     for (i = 0, j = 0; i < len; i++)
662         if (unicodestr[i] != FRIBIDI_CHAR_FILL)
663             unicodestr[j++] = unicodestr[i];
664     len = j;
665
666     if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
667         /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
668         goto out;
669     }
670
671     s->text = tmp;
672     len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
673                                      unicodestr, len, s->text);
674     ret = 0;
675
676 out:
677     av_free(unicodestr);
678     av_free(embedding_levels);
679     av_free(ar_props);
680     av_free(bidi_types);
681     return ret;
682 }
683 #endif
684
685 static av_cold int init(AVFilterContext *ctx)
686 {
687     int err;
688     DrawTextContext *s = ctx->priv;
689     Glyph *glyph;
690
691     av_expr_free(s->fontsize_pexpr);
692     s->fontsize_pexpr = NULL;
693
694     s->fontsize = 0;
695     s->default_fontsize = 16;
696
697     if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
698         av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
699         return AVERROR(EINVAL);
700     }
701
702     if (s->textfile) {
703         if (s->text) {
704             av_log(ctx, AV_LOG_ERROR,
705                    "Both text and text file provided. Please provide only one\n");
706             return AVERROR(EINVAL);
707         }
708         if ((err = load_textfile(ctx)) < 0)
709             return err;
710     }
711
712     if (s->reload && !s->textfile)
713         av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
714
715     if (s->tc_opt_string) {
716         int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
717                                                s->tc_opt_string, ctx);
718         if (ret < 0)
719             return ret;
720         if (s->tc24hmax)
721             s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
722         if (!s->text)
723             s->text = av_strdup("");
724     }
725
726     if (!s->text) {
727         av_log(ctx, AV_LOG_ERROR,
728                "Either text, a valid file or a timecode must be provided\n");
729         return AVERROR(EINVAL);
730     }
731
732 #if CONFIG_LIBFRIBIDI
733     if (s->text_shaping)
734         if ((err = shape_text(ctx)) < 0)
735             return err;
736 #endif
737
738     if ((err = FT_Init_FreeType(&(s->library)))) {
739         av_log(ctx, AV_LOG_ERROR,
740                "Could not load FreeType: %s\n", FT_ERRMSG(err));
741         return AVERROR(EINVAL);
742     }
743
744     if ((err = load_font(ctx)) < 0)
745         return err;
746
747     if ((err = update_fontsize(ctx)) < 0)
748         return err;
749
750     if (s->borderw) {
751         if (FT_Stroker_New(s->library, &s->stroker)) {
752             av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
753             return AVERROR_EXTERNAL;
754         }
755         FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
756                        FT_STROKER_LINEJOIN_ROUND, 0);
757     }
758
759     s->use_kerning = FT_HAS_KERNING(s->face);
760
761     /* load the fallback glyph with code 0 */
762     load_glyph(ctx, NULL, 0);
763
764     /* set the tabsize in pixels */
765     if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
766         av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
767         return err;
768     }
769     s->tabsize *= glyph->advance;
770
771     if (s->exp_mode == EXP_STRFTIME &&
772         (strchr(s->text, '%') || strchr(s->text, '\\')))
773         av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
774
775     av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
776     av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
777
778     return 0;
779 }
780
781 static int query_formats(AVFilterContext *ctx)
782 {
783     return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
784 }
785
786 static int glyph_enu_free(void *opaque, void *elem)
787 {
788     Glyph *glyph = elem;
789
790     FT_Done_Glyph(glyph->glyph);
791     FT_Done_Glyph(glyph->border_glyph);
792     av_free(elem);
793     return 0;
794 }
795
796 static av_cold void uninit(AVFilterContext *ctx)
797 {
798     DrawTextContext *s = ctx->priv;
799
800     av_expr_free(s->x_pexpr);
801     av_expr_free(s->y_pexpr);
802     av_expr_free(s->a_pexpr);
803     av_expr_free(s->fontsize_pexpr);
804
805     s->x_pexpr = s->y_pexpr = s->a_pexpr = s->fontsize_pexpr = NULL;
806
807     av_freep(&s->positions);
808     s->nb_positions = 0;
809
810     av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
811     av_tree_destroy(s->glyphs);
812     s->glyphs = NULL;
813
814     FT_Done_Face(s->face);
815     FT_Stroker_Done(s->stroker);
816     FT_Done_FreeType(s->library);
817
818     av_bprint_finalize(&s->expanded_text, NULL);
819     av_bprint_finalize(&s->expanded_fontcolor, NULL);
820 }
821
822 static int config_input(AVFilterLink *inlink)
823 {
824     AVFilterContext *ctx = inlink->dst;
825     DrawTextContext *s = ctx->priv;
826     int ret;
827
828     ff_draw_init(&s->dc, inlink->format, FF_DRAW_PROCESS_ALPHA);
829     ff_draw_color(&s->dc, &s->fontcolor,   s->fontcolor.rgba);
830     ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
831     ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
832     ff_draw_color(&s->dc, &s->boxcolor,    s->boxcolor.rgba);
833
834     s->var_values[VAR_w]     = s->var_values[VAR_W]     = s->var_values[VAR_MAIN_W] = inlink->w;
835     s->var_values[VAR_h]     = s->var_values[VAR_H]     = s->var_values[VAR_MAIN_H] = inlink->h;
836     s->var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
837     s->var_values[VAR_DAR]   = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
838     s->var_values[VAR_HSUB]  = 1 << s->dc.hsub_max;
839     s->var_values[VAR_VSUB]  = 1 << s->dc.vsub_max;
840     s->var_values[VAR_X]     = NAN;
841     s->var_values[VAR_Y]     = NAN;
842     s->var_values[VAR_T]     = NAN;
843
844     av_lfg_init(&s->prng, av_get_random_seed());
845
846     av_expr_free(s->x_pexpr);
847     av_expr_free(s->y_pexpr);
848     av_expr_free(s->a_pexpr);
849     s->x_pexpr = s->y_pexpr = s->a_pexpr = NULL;
850
851     if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
852                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
853         (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
854                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
855         (ret = av_expr_parse(&s->a_pexpr, s->a_expr, var_names,
856                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
857
858         return AVERROR(EINVAL);
859
860     return 0;
861 }
862
863 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
864 {
865     DrawTextContext *s = ctx->priv;
866
867     if (!strcmp(cmd, "reinit")) {
868         int ret;
869         uninit(ctx);
870         s->reinit = 1;
871         if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
872             return ret;
873         if ((ret = init(ctx)) < 0)
874             return ret;
875         return config_input(ctx->inputs[0]);
876     }
877
878     return AVERROR(ENOSYS);
879 }
880
881 static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
882                           char *fct, unsigned argc, char **argv, int tag)
883 {
884     DrawTextContext *s = ctx->priv;
885
886     av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
887     return 0;
888 }
889
890 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
891                     char *fct, unsigned argc, char **argv, int tag)
892 {
893     DrawTextContext *s = ctx->priv;
894     const char *fmt;
895     double pts = s->var_values[VAR_T];
896     int ret;
897
898     fmt = argc >= 1 ? argv[0] : "flt";
899     if (argc >= 2) {
900         int64_t delta;
901         if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
902             av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
903             return ret;
904         }
905         pts += (double)delta / AV_TIME_BASE;
906     }
907     if (!strcmp(fmt, "flt")) {
908         av_bprintf(bp, "%.6f", pts);
909     } else if (!strcmp(fmt, "hms")) {
910         if (isnan(pts)) {
911             av_bprintf(bp, " ??:??:??.???");
912         } else {
913             int64_t ms = llrint(pts * 1000);
914             char sign = ' ';
915             if (ms < 0) {
916                 sign = '-';
917                 ms = -ms;
918             }
919             if (argc >= 3) {
920                 if (!strcmp(argv[2], "24HH")) {
921                     ms %= 24 * 60 * 60 * 1000;
922                 } else {
923                     av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s'\n", argv[2]);
924                     return AVERROR(EINVAL);
925                 }
926             }
927             av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
928                        (int)(ms / (60 * 60 * 1000)),
929                        (int)(ms / (60 * 1000)) % 60,
930                        (int)(ms / 1000) % 60,
931                        (int)(ms % 1000));
932         }
933     } else if (!strcmp(fmt, "localtime") ||
934                !strcmp(fmt, "gmtime")) {
935         struct tm tm;
936         time_t ms = (time_t)pts;
937         const char *timefmt = argc >= 3 ? argv[2] : "%Y-%m-%d %H:%M:%S";
938         if (!strcmp(fmt, "localtime"))
939             localtime_r(&ms, &tm);
940         else
941             gmtime_r(&ms, &tm);
942         av_bprint_strftime(bp, timefmt, &tm);
943     } else {
944         av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
945         return AVERROR(EINVAL);
946     }
947     return 0;
948 }
949
950 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
951                           char *fct, unsigned argc, char **argv, int tag)
952 {
953     DrawTextContext *s = ctx->priv;
954
955     av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
956     return 0;
957 }
958
959 static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
960                          char *fct, unsigned argc, char **argv, int tag)
961 {
962     DrawTextContext *s = ctx->priv;
963     AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
964
965     if (e && e->value)
966         av_bprintf(bp, "%s", e->value);
967     else if (argc >= 2)
968         av_bprintf(bp, "%s", argv[1]);
969     return 0;
970 }
971
972 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
973                          char *fct, unsigned argc, char **argv, int tag)
974 {
975     const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
976     time_t now;
977     struct tm tm;
978
979     time(&now);
980     if (tag == 'L')
981         localtime_r(&now, &tm);
982     else
983         tm = *gmtime_r(&now, &tm);
984     av_bprint_strftime(bp, fmt, &tm);
985     return 0;
986 }
987
988 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
989                           char *fct, unsigned argc, char **argv, int tag)
990 {
991     DrawTextContext *s = ctx->priv;
992     double res;
993     int ret;
994
995     ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
996                                  NULL, NULL, fun2_names, fun2,
997                                  &s->prng, 0, ctx);
998     if (ret < 0)
999         av_log(ctx, AV_LOG_ERROR,
1000                "Expression '%s' for the expr text expansion function is not valid\n",
1001                argv[0]);
1002     else
1003         av_bprintf(bp, "%f", res);
1004
1005     return ret;
1006 }
1007
1008 static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
1009                           char *fct, unsigned argc, char **argv, int tag)
1010 {
1011     DrawTextContext *s = ctx->priv;
1012     double res;
1013     int intval;
1014     int ret;
1015     unsigned int positions = 0;
1016     char fmt_str[30] = "%";
1017
1018     /*
1019      * argv[0] expression to be converted to `int`
1020      * argv[1] format: 'x', 'X', 'd' or 'u'
1021      * argv[2] positions printed (optional)
1022      */
1023
1024     ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
1025                                  NULL, NULL, fun2_names, fun2,
1026                                  &s->prng, 0, ctx);
1027     if (ret < 0) {
1028         av_log(ctx, AV_LOG_ERROR,
1029                "Expression '%s' for the expr text expansion function is not valid\n",
1030                argv[0]);
1031         return ret;
1032     }
1033
1034     if (!strchr("xXdu", argv[1][0])) {
1035         av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
1036                 " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
1037         return AVERROR(EINVAL);
1038     }
1039
1040     if (argc == 3) {
1041         ret = sscanf(argv[2], "%u", &positions);
1042         if (ret != 1) {
1043             av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
1044                     " to print: '%s'\n", argv[2]);
1045             return AVERROR(EINVAL);
1046         }
1047     }
1048
1049     feclearexcept(FE_ALL_EXCEPT);
1050     intval = res;
1051     if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
1052         av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
1053         return AVERROR(EINVAL);
1054     }
1055
1056     if (argc == 3)
1057         av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
1058     av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
1059
1060     av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
1061             res, argv[0], fmt_str);
1062
1063     av_bprintf(bp, fmt_str, intval);
1064
1065     return 0;
1066 }
1067
1068 static const struct drawtext_function {
1069     const char *name;
1070     unsigned argc_min, argc_max;
1071     int tag;                            /**< opaque argument to func */
1072     int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
1073 } functions[] = {
1074     { "expr",      1, 1, 0,   func_eval_expr },
1075     { "e",         1, 1, 0,   func_eval_expr },
1076     { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
1077     { "eif",       2, 3, 0,   func_eval_expr_int_format },
1078     { "pict_type", 0, 0, 0,   func_pict_type },
1079     { "pts",       0, 3, 0,   func_pts      },
1080     { "gmtime",    0, 1, 'G', func_strftime },
1081     { "localtime", 0, 1, 'L', func_strftime },
1082     { "frame_num", 0, 0, 0,   func_frame_num },
1083     { "n",         0, 0, 0,   func_frame_num },
1084     { "metadata",  1, 2, 0,   func_metadata },
1085 };
1086
1087 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
1088                          unsigned argc, char **argv)
1089 {
1090     unsigned i;
1091
1092     for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
1093         if (strcmp(fct, functions[i].name))
1094             continue;
1095         if (argc < functions[i].argc_min) {
1096             av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
1097                    fct, functions[i].argc_min);
1098             return AVERROR(EINVAL);
1099         }
1100         if (argc > functions[i].argc_max) {
1101             av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
1102                    fct, functions[i].argc_max);
1103             return AVERROR(EINVAL);
1104         }
1105         break;
1106     }
1107     if (i >= FF_ARRAY_ELEMS(functions)) {
1108         av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
1109         return AVERROR(EINVAL);
1110     }
1111     return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
1112 }
1113
1114 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
1115 {
1116     const char *text = *rtext;
1117     char *argv[16] = { NULL };
1118     unsigned argc = 0, i;
1119     int ret;
1120
1121     if (*text != '{') {
1122         av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
1123         return AVERROR(EINVAL);
1124     }
1125     text++;
1126     while (1) {
1127         if (!(argv[argc++] = av_get_token(&text, ":}"))) {
1128             ret = AVERROR(ENOMEM);
1129             goto end;
1130         }
1131         if (!*text) {
1132             av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
1133             ret = AVERROR(EINVAL);
1134             goto end;
1135         }
1136         if (argc == FF_ARRAY_ELEMS(argv))
1137             av_freep(&argv[--argc]); /* error will be caught later */
1138         if (*text == '}')
1139             break;
1140         text++;
1141     }
1142
1143     if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
1144         goto end;
1145     ret = 0;
1146     *rtext = (char *)text + 1;
1147
1148 end:
1149     for (i = 0; i < argc; i++)
1150         av_freep(&argv[i]);
1151     return ret;
1152 }
1153
1154 static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
1155 {
1156     int ret;
1157
1158     av_bprint_clear(bp);
1159     while (*text) {
1160         if (*text == '\\' && text[1]) {
1161             av_bprint_chars(bp, text[1], 1);
1162             text += 2;
1163         } else if (*text == '%') {
1164             text++;
1165             if ((ret = expand_function(ctx, bp, &text)) < 0)
1166                 return ret;
1167         } else {
1168             av_bprint_chars(bp, *text, 1);
1169             text++;
1170         }
1171     }
1172     if (!av_bprint_is_complete(bp))
1173         return AVERROR(ENOMEM);
1174     return 0;
1175 }
1176
1177 static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
1178                        int width, int height,
1179                        FFDrawColor *color,
1180                        int x, int y, int borderw)
1181 {
1182     char *text = s->expanded_text.str;
1183     uint32_t code = 0;
1184     int i, x1, y1;
1185     uint8_t *p;
1186     Glyph *glyph = NULL;
1187
1188     for (i = 0, p = text; *p; i++) {
1189         FT_Bitmap bitmap;
1190         Glyph dummy = { 0 };
1191         GET_UTF8(code, *p++, continue;);
1192
1193         /* skip new line chars, just go to new line */
1194         if (code == '\n' || code == '\r' || code == '\t')
1195             continue;
1196
1197         dummy.code = code;
1198         dummy.fontsize = s->fontsize;
1199         glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1200
1201         bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
1202
1203         if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
1204             glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
1205             return AVERROR(EINVAL);
1206
1207         x1 = s->positions[i].x+s->x+x - borderw;
1208         y1 = s->positions[i].y+s->y+y - borderw;
1209
1210         ff_blend_mask(&s->dc, color,
1211                       frame->data, frame->linesize, width, height,
1212                       bitmap.buffer, bitmap.pitch,
1213                       bitmap.width, bitmap.rows,
1214                       bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
1215                       0, x1, y1);
1216     }
1217
1218     return 0;
1219 }
1220
1221
1222 static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
1223 {
1224     *color = incolor;
1225     color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
1226     ff_draw_color(&s->dc, color, color->rgba);
1227 }
1228
1229 static void update_alpha(DrawTextContext *s)
1230 {
1231     double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
1232
1233     if (isnan(alpha))
1234         return;
1235
1236     if (alpha >= 1.0)
1237         s->alpha = 255;
1238     else if (alpha <= 0)
1239         s->alpha = 0;
1240     else
1241         s->alpha = 256 * alpha;
1242 }
1243
1244 static int draw_text(AVFilterContext *ctx, AVFrame *frame,
1245                      int width, int height)
1246 {
1247     DrawTextContext *s = ctx->priv;
1248     AVFilterLink *inlink = ctx->inputs[0];
1249
1250     uint32_t code = 0, prev_code = 0;
1251     int x = 0, y = 0, i = 0, ret;
1252     int max_text_line_w = 0, len;
1253     int box_w, box_h;
1254     char *text;
1255     uint8_t *p;
1256     int y_min = 32000, y_max = -32000;
1257     int x_min = 32000, x_max = -32000;
1258     FT_Vector delta;
1259     Glyph *glyph = NULL, *prev_glyph = NULL;
1260     Glyph dummy = { 0 };
1261
1262     time_t now = time(0);
1263     struct tm ltime;
1264     AVBPrint *bp = &s->expanded_text;
1265
1266     FFDrawColor fontcolor;
1267     FFDrawColor shadowcolor;
1268     FFDrawColor bordercolor;
1269     FFDrawColor boxcolor;
1270
1271     av_bprint_clear(bp);
1272
1273     if(s->basetime != AV_NOPTS_VALUE)
1274         now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
1275
1276     switch (s->exp_mode) {
1277     case EXP_NONE:
1278         av_bprintf(bp, "%s", s->text);
1279         break;
1280     case EXP_NORMAL:
1281         if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
1282             return ret;
1283         break;
1284     case EXP_STRFTIME:
1285         localtime_r(&now, &ltime);
1286         av_bprint_strftime(bp, s->text, &ltime);
1287         break;
1288     }
1289
1290     if (s->tc_opt_string) {
1291         char tcbuf[AV_TIMECODE_STR_SIZE];
1292         av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count_out);
1293         av_bprint_clear(bp);
1294         av_bprintf(bp, "%s%s", s->text, tcbuf);
1295     }
1296
1297     if (!av_bprint_is_complete(bp))
1298         return AVERROR(ENOMEM);
1299     text = s->expanded_text.str;
1300     if ((len = s->expanded_text.len) > s->nb_positions) {
1301         if (!(s->positions =
1302               av_realloc(s->positions, len*sizeof(*s->positions))))
1303             return AVERROR(ENOMEM);
1304         s->nb_positions = len;
1305     }
1306
1307     if (s->fontcolor_expr[0]) {
1308         /* If expression is set, evaluate and replace the static value */
1309         av_bprint_clear(&s->expanded_fontcolor);
1310         if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
1311             return ret;
1312         if (!av_bprint_is_complete(&s->expanded_fontcolor))
1313             return AVERROR(ENOMEM);
1314         av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
1315         ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
1316         if (ret)
1317             return ret;
1318         ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
1319     }
1320
1321     x = 0;
1322     y = 0;
1323
1324     if ((ret = update_fontsize(ctx)) < 0)
1325         return ret;
1326
1327     /* load and cache glyphs */
1328     for (i = 0, p = text; *p; i++) {
1329         GET_UTF8(code, *p++, continue;);
1330
1331         /* get glyph */
1332         dummy.code = code;
1333         dummy.fontsize = s->fontsize;
1334         glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1335         if (!glyph) {
1336             ret = load_glyph(ctx, &glyph, code);
1337             if (ret < 0)
1338                 return ret;
1339         }
1340
1341         y_min = FFMIN(glyph->bbox.yMin, y_min);
1342         y_max = FFMAX(glyph->bbox.yMax, y_max);
1343         x_min = FFMIN(glyph->bbox.xMin, x_min);
1344         x_max = FFMAX(glyph->bbox.xMax, x_max);
1345     }
1346     s->max_glyph_h = y_max - y_min;
1347     s->max_glyph_w = x_max - x_min;
1348
1349     /* compute and save position for each glyph */
1350     glyph = NULL;
1351     for (i = 0, p = text; *p; i++) {
1352         GET_UTF8(code, *p++, continue;);
1353
1354         /* skip the \n in the sequence \r\n */
1355         if (prev_code == '\r' && code == '\n')
1356             continue;
1357
1358         prev_code = code;
1359         if (is_newline(code)) {
1360
1361             max_text_line_w = FFMAX(max_text_line_w, x);
1362             y += s->max_glyph_h + s->line_spacing;
1363             x = 0;
1364             continue;
1365         }
1366
1367         /* get glyph */
1368         prev_glyph = glyph;
1369         dummy.code = code;
1370         dummy.fontsize = s->fontsize;
1371         glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1372
1373         /* kerning */
1374         if (s->use_kerning && prev_glyph && glyph->code) {
1375             FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
1376                            ft_kerning_default, &delta);
1377             x += delta.x >> 6;
1378         }
1379
1380         /* save position */
1381         s->positions[i].x = x + glyph->bitmap_left;
1382         s->positions[i].y = y - glyph->bitmap_top + y_max;
1383         if (code == '\t') x  = (x / s->tabsize + 1)*s->tabsize;
1384         else              x += glyph->advance;
1385     }
1386
1387     max_text_line_w = FFMAX(x, max_text_line_w);
1388
1389     s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
1390     s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
1391
1392     s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
1393     s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
1394     s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
1395     s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
1396
1397     s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
1398
1399     s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1400     s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
1401     /* It is necessary if x is expressed from y  */
1402     s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1403
1404     update_alpha(s);
1405     update_color_with_alpha(s, &fontcolor  , s->fontcolor  );
1406     update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
1407     update_color_with_alpha(s, &bordercolor, s->bordercolor);
1408     update_color_with_alpha(s, &boxcolor   , s->boxcolor   );
1409
1410     box_w = max_text_line_w;
1411     box_h = y + s->max_glyph_h;
1412
1413     if (s->fix_bounds) {
1414
1415         /* calculate footprint of text effects */
1416         int boxoffset     = s->draw_box ? FFMAX(s->boxborderw, 0) : 0;
1417         int borderoffset  = s->borderw  ? FFMAX(s->borderw, 0) : 0;
1418
1419         int offsetleft = FFMAX3(boxoffset, borderoffset,
1420                                 (s->shadowx < 0 ? FFABS(s->shadowx) : 0));
1421         int offsettop = FFMAX3(boxoffset, borderoffset,
1422                                 (s->shadowy < 0 ? FFABS(s->shadowy) : 0));
1423
1424         int offsetright = FFMAX3(boxoffset, borderoffset,
1425                                  (s->shadowx > 0 ? s->shadowx : 0));
1426         int offsetbottom = FFMAX3(boxoffset, borderoffset,
1427                                   (s->shadowy > 0 ? s->shadowy : 0));
1428
1429
1430         if (s->x - offsetleft < 0) s->x = offsetleft;
1431         if (s->y - offsettop < 0)  s->y = offsettop;
1432
1433         if (s->x + box_w + offsetright > width)
1434             s->x = FFMAX(width - box_w - offsetright, 0);
1435         if (s->y + box_h + offsetbottom > height)
1436             s->y = FFMAX(height - box_h - offsetbottom, 0);
1437     }
1438
1439     /* draw box */
1440     if (s->draw_box)
1441         ff_blend_rectangle(&s->dc, &boxcolor,
1442                            frame->data, frame->linesize, width, height,
1443                            s->x - s->boxborderw, s->y - s->boxborderw,
1444                            box_w + s->boxborderw * 2, box_h + s->boxborderw * 2);
1445
1446     if (s->shadowx || s->shadowy) {
1447         if ((ret = draw_glyphs(s, frame, width, height,
1448                                &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
1449             return ret;
1450     }
1451
1452     if (s->borderw) {
1453         if ((ret = draw_glyphs(s, frame, width, height,
1454                                &bordercolor, 0, 0, s->borderw)) < 0)
1455             return ret;
1456     }
1457     if ((ret = draw_glyphs(s, frame, width, height,
1458                            &fontcolor, 0, 0, 0)) < 0)
1459         return ret;
1460
1461     return 0;
1462 }
1463
1464 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
1465 {
1466     AVFilterContext *ctx = inlink->dst;
1467     AVFilterLink *outlink = ctx->outputs[0];
1468     DrawTextContext *s = ctx->priv;
1469     int ret;
1470
1471     if (s->reload) {
1472         if ((ret = load_textfile(ctx)) < 0) {
1473             av_frame_free(&frame);
1474             return ret;
1475         }
1476 #if CONFIG_LIBFRIBIDI
1477         if (s->text_shaping)
1478             if ((ret = shape_text(ctx)) < 0) {
1479                 av_frame_free(&frame);
1480                 return ret;
1481             }
1482 #endif
1483     }
1484
1485     s->var_values[VAR_N] = inlink->frame_count_out + s->start_number;
1486     s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
1487         NAN : frame->pts * av_q2d(inlink->time_base);
1488
1489     s->var_values[VAR_PICT_TYPE] = frame->pict_type;
1490     s->metadata = frame->metadata;
1491
1492     draw_text(ctx, frame, frame->width, frame->height);
1493
1494     av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
1495            (int)s->var_values[VAR_N], s->var_values[VAR_T],
1496            (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
1497            s->x, s->y);
1498
1499     return ff_filter_frame(outlink, frame);
1500 }
1501
1502 static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
1503     {
1504         .name           = "default",
1505         .type           = AVMEDIA_TYPE_VIDEO,
1506         .filter_frame   = filter_frame,
1507         .config_props   = config_input,
1508         .needs_writable = 1,
1509     },
1510     { NULL }
1511 };
1512
1513 static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
1514     {
1515         .name = "default",
1516         .type = AVMEDIA_TYPE_VIDEO,
1517     },
1518     { NULL }
1519 };
1520
1521 AVFilter ff_vf_drawtext = {
1522     .name          = "drawtext",
1523     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1524     .priv_size     = sizeof(DrawTextContext),
1525     .priv_class    = &drawtext_class,
1526     .init          = init,
1527     .uninit        = uninit,
1528     .query_formats = query_formats,
1529     .inputs        = avfilter_vf_drawtext_inputs,
1530     .outputs       = avfilter_vf_drawtext_outputs,
1531     .process_command = command,
1532     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
1533 };