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