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