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