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