]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_drawtext.c
lavu/mem: fix potential int overflow and crash in av_dynarray_add()
[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 <sys/time.h>
30 #include <time.h>
31
32 #include "config.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/bprint.h"
35 #include "libavutil/common.h"
36 #include "libavutil/file.h"
37 #include "libavutil/eval.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/random_seed.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/timecode.h"
42 #include "libavutil/tree.h"
43 #include "libavutil/lfg.h"
44 #include "avfilter.h"
45 #include "drawutils.h"
46 #include "formats.h"
47 #include "internal.h"
48 #include "video.h"
49
50 #include <ft2build.h>
51 #include <freetype/config/ftheader.h>
52 #include FT_FREETYPE_H
53 #include FT_GLYPH_H
54 #if CONFIG_FONTCONFIG
55 #include <fontconfig/fontconfig.h>
56 #endif
57
58 static const char *const var_names[] = {
59     "dar",
60     "hsub", "vsub",
61     "line_h", "lh",           ///< line height, same as max_glyph_h
62     "main_h", "h", "H",       ///< height of the input video
63     "main_w", "w", "W",       ///< width  of the input video
64     "max_glyph_a", "ascent",  ///< max glyph ascent
65     "max_glyph_d", "descent", ///< min glyph descent
66     "max_glyph_h",            ///< max glyph height
67     "max_glyph_w",            ///< max glyph width
68     "n",                      ///< number of frame
69     "sar",
70     "t",                      ///< timestamp expressed in seconds
71     "text_h", "th",           ///< height of the rendered text
72     "text_w", "tw",           ///< width  of the rendered text
73     "x",
74     "y",
75     "pict_type",
76     NULL
77 };
78
79 static const char *const fun2_names[] = {
80     "rand"
81 };
82
83 static double drand(void *opaque, double min, double max)
84 {
85     return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
86 }
87
88 typedef double (*eval_func2)(void *, double a, double b);
89
90 static const eval_func2 fun2[] = {
91     drand,
92     NULL
93 };
94
95 enum var_name {
96     VAR_DAR,
97     VAR_HSUB, VAR_VSUB,
98     VAR_LINE_H, VAR_LH,
99     VAR_MAIN_H, VAR_h, VAR_H,
100     VAR_MAIN_W, VAR_w, VAR_W,
101     VAR_MAX_GLYPH_A, VAR_ASCENT,
102     VAR_MAX_GLYPH_D, VAR_DESCENT,
103     VAR_MAX_GLYPH_H,
104     VAR_MAX_GLYPH_W,
105     VAR_N,
106     VAR_SAR,
107     VAR_T,
108     VAR_TEXT_H, VAR_TH,
109     VAR_TEXT_W, VAR_TW,
110     VAR_X,
111     VAR_Y,
112     VAR_PICT_TYPE,
113     VAR_VARS_NB
114 };
115
116 enum expansion_mode {
117     EXP_NONE,
118     EXP_NORMAL,
119     EXP_STRFTIME,
120 };
121
122 typedef struct {
123     const AVClass *class;
124     enum expansion_mode exp_mode;   ///< expansion mode to use for the text
125     int reinit;                     ///< tells if the filter is being reinited
126     uint8_t *fontfile;              ///< font to be used
127     uint8_t *text;                  ///< text to be drawn
128     AVBPrint expanded_text;         ///< used to contain the expanded text
129     int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
130     FT_Vector *positions;           ///< positions for each element in the text
131     size_t nb_positions;            ///< number of elements of positions array
132     char *textfile;                 ///< file with text to be drawn
133     int x;                          ///< x position to start drawing text
134     int y;                          ///< y position to start drawing text
135     int max_glyph_w;                ///< max glyph width
136     int max_glyph_h;                ///< max glyph height
137     int shadowx, shadowy;
138     unsigned int fontsize;          ///< font size to use
139     char *fontcolor_string;         ///< font color as string
140     char *boxcolor_string;          ///< box color as string
141     char *shadowcolor_string;       ///< shadow color as string
142
143     short int draw_box;             ///< draw box around text - true or false
144     int use_kerning;                ///< font kerning is used - true/false
145     int tabsize;                    ///< tab size
146     int fix_bounds;                 ///< do we let it go out of frame bounds - t/f
147
148     FFDrawContext dc;
149     FFDrawColor fontcolor;          ///< foreground color
150     FFDrawColor shadowcolor;        ///< shadow color
151     FFDrawColor boxcolor;           ///< background color
152
153     FT_Library library;             ///< freetype font library handle
154     FT_Face face;                   ///< freetype font face handle
155     struct AVTreeNode *glyphs;      ///< rendered glyphs, stored using the UTF-32 char code
156     char *x_expr;                   ///< expression for x position
157     char *y_expr;                   ///< expression for y position
158     AVExpr *x_pexpr, *y_pexpr;      ///< parsed expressions for x and y
159     int64_t basetime;               ///< base pts time in the real world for display
160     double var_values[VAR_VARS_NB];
161     char   *draw_expr;              ///< expression for draw
162     AVExpr *draw_pexpr;             ///< parsed expression for draw
163     int draw;                       ///< set to zero to prevent drawing
164     AVLFG  prng;                    ///< random
165     char       *tc_opt_string;      ///< specified timecode option string
166     AVRational  tc_rate;            ///< frame rate for timecode
167     AVTimecode  tc;                 ///< timecode context
168     int tc24hmax;                   ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
169     int reload;                     ///< reload text file for each frame
170 } DrawTextContext;
171
172 #define OFFSET(x) offsetof(DrawTextContext, x)
173 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
174
175 static const AVOption drawtext_options[]= {
176     {"fontfile",    "set font file",        OFFSET(fontfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
177     {"text",        "set text",             OFFSET(text),               AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
178     {"textfile",    "set text file",        OFFSET(textfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
179     {"fontcolor",   "set foreground color", OFFSET(fontcolor_string),   AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
180     {"boxcolor",    "set box color",        OFFSET(boxcolor_string),    AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
181     {"shadowcolor", "set shadow color",     OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
182     {"box",         "set box",              OFFSET(draw_box),           AV_OPT_TYPE_INT,    {.i64=0},     0,        1       , FLAGS},
183     {"fontsize",    "set font size",        OFFSET(fontsize),           AV_OPT_TYPE_INT,    {.i64=0},     0,        INT_MAX , FLAGS},
184     {"x",           "set x expression",     OFFSET(x_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX, FLAGS},
185     {"y",           "set y expression",     OFFSET(y_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX, FLAGS},
186     {"shadowx",     "set x",                OFFSET(shadowx),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
187     {"shadowy",     "set y",                OFFSET(shadowy),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
188     {"tabsize",     "set tab size",         OFFSET(tabsize),            AV_OPT_TYPE_INT,    {.i64=4},     0,        INT_MAX , FLAGS},
189     {"basetime",    "set base time",        OFFSET(basetime),           AV_OPT_TYPE_INT64,  {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
190     {"draw",        "if false do not draw", OFFSET(draw_expr),          AV_OPT_TYPE_STRING, {.str="1"},   CHAR_MIN, CHAR_MAX, FLAGS},
191
192     {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
193         {"none",     "set no expansion",                    OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE},     0, 0, FLAGS, "expansion"},
194         {"normal",   "set normal expansion",                OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL},   0, 0, FLAGS, "expansion"},
195         {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
196
197     {"timecode",        "set initial timecode",             OFFSET(tc_opt_string), AV_OPT_TYPE_STRING,   {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
198     {"tc24hmax",        "set 24 hours max (timecode only)", OFFSET(tc24hmax),      AV_OPT_TYPE_INT,      {.i64=0},           0,        1, FLAGS},
199     {"timecode_rate",   "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
200     {"r",               "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
201     {"rate",            "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
202     {"reload",     "reload text file for each frame",                       OFFSET(reload),     AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
203     {"fix_bounds", "if true, check and fix text coords to avoid clipping",  OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
204
205     /* FT_LOAD_* flags */
206     { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT | FT_LOAD_RENDER}, 0, INT_MAX, FLAGS, "ft_load_flags" },
207         { "default",                     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT },                     .flags = FLAGS, .unit = "ft_load_flags" },
208         { "no_scale",                    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE },                    .flags = FLAGS, .unit = "ft_load_flags" },
209         { "no_hinting",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING },                  .flags = FLAGS, .unit = "ft_load_flags" },
210         { "render",                      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER },                      .flags = FLAGS, .unit = "ft_load_flags" },
211         { "no_bitmap",                   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP },                   .flags = FLAGS, .unit = "ft_load_flags" },
212         { "vertical_layout",             NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT },             .flags = FLAGS, .unit = "ft_load_flags" },
213         { "force_autohint",              NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT },              .flags = FLAGS, .unit = "ft_load_flags" },
214         { "crop_bitmap",                 NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP },                 .flags = FLAGS, .unit = "ft_load_flags" },
215         { "pedantic",                    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC },                    .flags = FLAGS, .unit = "ft_load_flags" },
216         { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
217         { "no_recurse",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE },                  .flags = FLAGS, .unit = "ft_load_flags" },
218         { "ignore_transform",            NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM },            .flags = FLAGS, .unit = "ft_load_flags" },
219         { "monochrome",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME },                  .flags = FLAGS, .unit = "ft_load_flags" },
220         { "linear_design",               NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN },               .flags = FLAGS, .unit = "ft_load_flags" },
221         { "no_autohint",                 NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT },                 .flags = FLAGS, .unit = "ft_load_flags" },
222     { NULL},
223 };
224
225 AVFILTER_DEFINE_CLASS(drawtext);
226
227 #undef __FTERRORS_H__
228 #define FT_ERROR_START_LIST {
229 #define FT_ERRORDEF(e, v, s) { (e), (s) },
230 #define FT_ERROR_END_LIST { 0, NULL } };
231
232 struct ft_error
233 {
234     int err;
235     const char *err_msg;
236 } static ft_errors[] =
237 #include FT_ERRORS_H
238
239 #define FT_ERRMSG(e) ft_errors[e].err_msg
240
241 typedef struct {
242     FT_Glyph *glyph;
243     uint32_t code;
244     FT_Bitmap bitmap; ///< array holding bitmaps of font
245     FT_BBox bbox;
246     int advance;
247     int bitmap_left;
248     int bitmap_top;
249 } Glyph;
250
251 static int glyph_cmp(void *key, const void *b)
252 {
253     const Glyph *a = key, *bb = b;
254     int64_t diff = (int64_t)a->code - (int64_t)bb->code;
255     return diff > 0 ? 1 : diff < 0 ? -1 : 0;
256 }
257
258 /**
259  * Load glyphs corresponding to the UTF-32 codepoint code.
260  */
261 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
262 {
263     DrawTextContext *dtext = ctx->priv;
264     Glyph *glyph;
265     struct AVTreeNode *node = NULL;
266     int ret;
267
268     /* load glyph into dtext->face->glyph */
269     if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
270         return AVERROR(EINVAL);
271
272     /* save glyph */
273     if (!(glyph = av_mallocz(sizeof(*glyph))) ||
274         !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
275         ret = AVERROR(ENOMEM);
276         goto error;
277     }
278     glyph->code  = code;
279
280     if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
281         ret = AVERROR(EINVAL);
282         goto error;
283     }
284
285     glyph->bitmap      = dtext->face->glyph->bitmap;
286     glyph->bitmap_left = dtext->face->glyph->bitmap_left;
287     glyph->bitmap_top  = dtext->face->glyph->bitmap_top;
288     glyph->advance     = dtext->face->glyph->advance.x >> 6;
289
290     /* measure text height to calculate text_height (or the maximum text height) */
291     FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
292
293     /* cache the newly created glyph */
294     if (!(node = av_tree_node_alloc())) {
295         ret = AVERROR(ENOMEM);
296         goto error;
297     }
298     av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
299
300     if (glyph_ptr)
301         *glyph_ptr = glyph;
302     return 0;
303
304 error:
305     if (glyph)
306         av_freep(&glyph->glyph);
307     av_freep(&glyph);
308     av_freep(&node);
309     return ret;
310 }
311
312 static int load_font_file(AVFilterContext *ctx, const char *path, int index,
313                           const char **error)
314 {
315     DrawTextContext *dtext = ctx->priv;
316     int err;
317
318     err = FT_New_Face(dtext->library, path, index, &dtext->face);
319     if (err) {
320         *error = FT_ERRMSG(err);
321         return AVERROR(EINVAL);
322     }
323     return 0;
324 }
325
326 #if CONFIG_FONTCONFIG
327 static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
328 {
329     DrawTextContext *dtext = ctx->priv;
330     FcConfig *fontconfig;
331     FcPattern *pattern, *fpat;
332     FcResult result = FcResultMatch;
333     FcChar8 *filename;
334     int err, index;
335     double size;
336
337     fontconfig = FcInitLoadConfigAndFonts();
338     if (!fontconfig) {
339         *error = "impossible to init fontconfig\n";
340         return AVERROR(EINVAL);
341     }
342     pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
343                           (uint8_t *)(intptr_t)"default");
344     if (!pattern) {
345         *error = "could not parse fontconfig pattern";
346         return AVERROR(EINVAL);
347     }
348     if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
349         *error = "could not substitue fontconfig options"; /* very unlikely */
350         return AVERROR(EINVAL);
351     }
352     FcDefaultSubstitute(pattern);
353     fpat = FcFontMatch(fontconfig, pattern, &result);
354     if (!fpat || result != FcResultMatch) {
355         *error = "impossible to find a matching font";
356         return AVERROR(EINVAL);
357     }
358     if (FcPatternGetString (fpat, FC_FILE,  0, &filename) != FcResultMatch ||
359         FcPatternGetInteger(fpat, FC_INDEX, 0, &index   ) != FcResultMatch ||
360         FcPatternGetDouble (fpat, FC_SIZE,  0, &size    ) != FcResultMatch) {
361         *error = "impossible to find font information";
362         return AVERROR(EINVAL);
363     }
364     av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
365     if (!dtext->fontsize)
366         dtext->fontsize = size + 0.5;
367     err = load_font_file(ctx, filename, index, error);
368     if (err)
369         return err;
370     FcPatternDestroy(fpat);
371     FcPatternDestroy(pattern);
372     FcConfigDestroy(fontconfig);
373     return 0;
374 }
375 #endif
376
377 static int load_font(AVFilterContext *ctx)
378 {
379     DrawTextContext *dtext = ctx->priv;
380     int err;
381     const char *error = "unknown error\n";
382
383     /* load the face, and set up the encoding, which is by default UTF-8 */
384     err = load_font_file(ctx, dtext->fontfile, 0, &error);
385     if (!err)
386         return 0;
387 #if CONFIG_FONTCONFIG
388     err = load_font_fontconfig(ctx, &error);
389     if (!err)
390         return 0;
391 #endif
392     av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
393            dtext->fontfile, error);
394     return err;
395 }
396
397 static int load_textfile(AVFilterContext *ctx)
398 {
399     DrawTextContext *dtext = ctx->priv;
400     int err;
401     uint8_t *textbuf;
402     size_t textbuf_size;
403
404     if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
405         av_log(ctx, AV_LOG_ERROR,
406                "The text file '%s' could not be read or is empty\n",
407                dtext->textfile);
408         return err;
409     }
410
411     if (!(dtext->text = av_realloc(dtext->text, textbuf_size + 1)))
412         return AVERROR(ENOMEM);
413     memcpy(dtext->text, textbuf, textbuf_size);
414     dtext->text[textbuf_size] = 0;
415     av_file_unmap(textbuf, textbuf_size);
416
417     return 0;
418 }
419
420 static av_cold int init(AVFilterContext *ctx)
421 {
422     int err;
423     DrawTextContext *dtext = ctx->priv;
424     Glyph *glyph;
425
426     if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
427         av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
428         return AVERROR(EINVAL);
429     }
430
431     if (dtext->textfile) {
432         if (dtext->text) {
433             av_log(ctx, AV_LOG_ERROR,
434                    "Both text and text file provided. Please provide only one\n");
435             return AVERROR(EINVAL);
436         }
437         if ((err = load_textfile(ctx)) < 0)
438             return err;
439     }
440
441     if (dtext->reload && !dtext->textfile)
442         av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
443
444     if (dtext->tc_opt_string) {
445         int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
446                                                dtext->tc_opt_string, ctx);
447         if (ret < 0)
448             return ret;
449         if (dtext->tc24hmax)
450             dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
451         if (!dtext->text)
452             dtext->text = av_strdup("");
453     }
454
455     if (!dtext->text) {
456         av_log(ctx, AV_LOG_ERROR,
457                "Either text, a valid file or a timecode must be provided\n");
458         return AVERROR(EINVAL);
459     }
460
461     if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
462         av_log(ctx, AV_LOG_ERROR,
463                "Invalid font color '%s'\n", dtext->fontcolor_string);
464         return err;
465     }
466
467     if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
468         av_log(ctx, AV_LOG_ERROR,
469                "Invalid box color '%s'\n", dtext->boxcolor_string);
470         return err;
471     }
472
473     if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
474         av_log(ctx, AV_LOG_ERROR,
475                "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
476         return err;
477     }
478
479     if ((err = FT_Init_FreeType(&(dtext->library)))) {
480         av_log(ctx, AV_LOG_ERROR,
481                "Could not load FreeType: %s\n", FT_ERRMSG(err));
482         return AVERROR(EINVAL);
483     }
484
485     err = load_font(ctx);
486     if (err)
487         return err;
488     if (!dtext->fontsize)
489         dtext->fontsize = 16;
490     if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
491         av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
492                dtext->fontsize, FT_ERRMSG(err));
493         return AVERROR(EINVAL);
494     }
495
496     dtext->use_kerning = FT_HAS_KERNING(dtext->face);
497
498     /* load the fallback glyph with code 0 */
499     load_glyph(ctx, NULL, 0);
500
501     /* set the tabsize in pixels */
502     if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
503         av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
504         return err;
505     }
506     dtext->tabsize *= glyph->advance;
507
508     if (dtext->exp_mode == EXP_STRFTIME &&
509         (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
510         av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
511
512     av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
513
514     return 0;
515 }
516
517 static int query_formats(AVFilterContext *ctx)
518 {
519     ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
520     return 0;
521 }
522
523 static int glyph_enu_free(void *opaque, void *elem)
524 {
525     Glyph *glyph = elem;
526
527     FT_Done_Glyph(*glyph->glyph);
528     av_freep(&glyph->glyph);
529     av_free(elem);
530     return 0;
531 }
532
533 static av_cold void uninit(AVFilterContext *ctx)
534 {
535     DrawTextContext *dtext = ctx->priv;
536
537     av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
538     av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
539     av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
540
541     av_freep(&dtext->positions);
542     dtext->nb_positions = 0;
543
544
545     av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
546     av_tree_destroy(dtext->glyphs);
547     dtext->glyphs = NULL;
548
549     FT_Done_Face(dtext->face);
550     FT_Done_FreeType(dtext->library);
551
552     av_bprint_finalize(&dtext->expanded_text, NULL);
553 }
554
555 static inline int is_newline(uint32_t c)
556 {
557     return c == '\n' || c == '\r' || c == '\f' || c == '\v';
558 }
559
560 static int config_input(AVFilterLink *inlink)
561 {
562     AVFilterContext *ctx = inlink->dst;
563     DrawTextContext *dtext = ctx->priv;
564     int ret;
565
566     ff_draw_init(&dtext->dc, inlink->format, 0);
567     ff_draw_color(&dtext->dc, &dtext->fontcolor,   dtext->fontcolor.rgba);
568     ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
569     ff_draw_color(&dtext->dc, &dtext->boxcolor,    dtext->boxcolor.rgba);
570
571     dtext->var_values[VAR_w]     = dtext->var_values[VAR_W]     = dtext->var_values[VAR_MAIN_W] = inlink->w;
572     dtext->var_values[VAR_h]     = dtext->var_values[VAR_H]     = dtext->var_values[VAR_MAIN_H] = inlink->h;
573     dtext->var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
574     dtext->var_values[VAR_DAR]   = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
575     dtext->var_values[VAR_HSUB]  = 1 << dtext->dc.hsub_max;
576     dtext->var_values[VAR_VSUB]  = 1 << dtext->dc.vsub_max;
577     dtext->var_values[VAR_X]     = NAN;
578     dtext->var_values[VAR_Y]     = NAN;
579     if (!dtext->reinit)
580         dtext->var_values[VAR_N] = 0;
581     dtext->var_values[VAR_T]     = NAN;
582
583     av_lfg_init(&dtext->prng, av_get_random_seed());
584
585     if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
586                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
587         (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
588                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
589         (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
590                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
591
592         return AVERROR(EINVAL);
593
594     return 0;
595 }
596
597 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
598 {
599     DrawTextContext *dtext = ctx->priv;
600
601     if (!strcmp(cmd, "reinit")) {
602         int ret;
603         uninit(ctx);
604         dtext->reinit = 1;
605         if ((ret = init(ctx)) < 0)
606             return ret;
607         return config_input(ctx->inputs[0]);
608     }
609
610     return AVERROR(ENOSYS);
611 }
612
613 static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
614                           char *fct, unsigned argc, char **argv, int tag)
615 {
616     DrawTextContext *dtext = ctx->priv;
617
618     av_bprintf(bp, "%c", av_get_picture_type_char(dtext->var_values[VAR_PICT_TYPE]));
619     return 0;
620 }
621
622 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
623                     char *fct, unsigned argc, char **argv, int tag)
624 {
625     DrawTextContext *dtext = ctx->priv;
626
627     av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
628     return 0;
629 }
630
631 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
632                           char *fct, unsigned argc, char **argv, int tag)
633 {
634     DrawTextContext *dtext = ctx->priv;
635
636     av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
637     return 0;
638 }
639
640 #if !HAVE_LOCALTIME_R
641 static void localtime_r(const time_t *t, struct tm *tm)
642 {
643     *tm = *localtime(t);
644 }
645 #endif
646
647 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
648                          char *fct, unsigned argc, char **argv, int tag)
649 {
650     const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
651     time_t now;
652     struct tm tm;
653
654     time(&now);
655     if (tag == 'L')
656         localtime_r(&now, &tm);
657     else
658         tm = *gmtime(&now);
659     av_bprint_strftime(bp, fmt, &tm);
660     return 0;
661 }
662
663 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
664                           char *fct, unsigned argc, char **argv, int tag)
665 {
666     DrawTextContext *dtext = ctx->priv;
667     double res;
668     int ret;
669
670     ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
671                                  NULL, NULL, fun2_names, fun2,
672                                  &dtext->prng, 0, ctx);
673     if (ret < 0)
674         av_log(ctx, AV_LOG_ERROR,
675                "Expression '%s' for the expr text expansion function is not valid\n",
676                argv[0]);
677     else
678         av_bprintf(bp, "%f", res);
679
680     return ret;
681 }
682
683 static const struct drawtext_function {
684     const char *name;
685     unsigned argc_min, argc_max;
686     int tag; /** opaque argument to func */
687     int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
688 } functions[] = {
689     { "expr",      1, 1, 0,   func_eval_expr },
690     { "e",         1, 1, 0,   func_eval_expr },
691     { "pict_type", 0, 0, 0,   func_pict_type },
692     { "pts",       0, 0, 0,   func_pts      },
693     { "gmtime",    0, 1, 'G', func_strftime },
694     { "localtime", 0, 1, 'L', func_strftime },
695     { "frame_num", 0, 0, 0,   func_frame_num },
696     { "n",         0, 0, 0,   func_frame_num },
697 };
698
699 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
700                          unsigned argc, char **argv)
701 {
702     unsigned i;
703
704     for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
705         if (strcmp(fct, functions[i].name))
706             continue;
707         if (argc < functions[i].argc_min) {
708             av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
709                    fct, functions[i].argc_min);
710             return AVERROR(EINVAL);
711         }
712         if (argc > functions[i].argc_max) {
713             av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
714                    fct, functions[i].argc_max);
715             return AVERROR(EINVAL);
716         }
717         break;
718     }
719     if (i >= FF_ARRAY_ELEMS(functions)) {
720         av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
721         return AVERROR(EINVAL);
722     }
723     return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
724 }
725
726 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
727 {
728     const char *text = *rtext;
729     char *argv[16] = { NULL };
730     unsigned argc = 0, i;
731     int ret;
732
733     if (*text != '{') {
734         av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
735         return AVERROR(EINVAL);
736     }
737     text++;
738     while (1) {
739         if (!(argv[argc++] = av_get_token(&text, ":}"))) {
740             ret = AVERROR(ENOMEM);
741             goto end;
742         }
743         if (!*text) {
744             av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
745             ret = AVERROR(EINVAL);
746             goto end;
747         }
748         if (argc == FF_ARRAY_ELEMS(argv))
749             av_freep(&argv[--argc]); /* error will be caught later */
750         if (*text == '}')
751             break;
752         text++;
753     }
754
755     if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
756         goto end;
757     ret = 0;
758     *rtext = (char *)text + 1;
759
760 end:
761     for (i = 0; i < argc; i++)
762         av_freep(&argv[i]);
763     return ret;
764 }
765
766 static int expand_text(AVFilterContext *ctx)
767 {
768     DrawTextContext *dtext = ctx->priv;
769     char *text = dtext->text;
770     AVBPrint *bp = &dtext->expanded_text;
771     int ret;
772
773     av_bprint_clear(bp);
774     while (*text) {
775         if (*text == '\\' && text[1]) {
776             av_bprint_chars(bp, text[1], 1);
777             text += 2;
778         } else if (*text == '%') {
779             text++;
780             if ((ret = expand_function(ctx, bp, &text)) < 0)
781                 return ret;
782         } else {
783             av_bprint_chars(bp, *text, 1);
784             text++;
785         }
786     }
787     if (!av_bprint_is_complete(bp))
788         return AVERROR(ENOMEM);
789     return 0;
790 }
791
792 static int draw_glyphs(DrawTextContext *dtext, AVFrame *frame,
793                        int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
794 {
795     char *text = dtext->expanded_text.str;
796     uint32_t code = 0;
797     int i, x1, y1;
798     uint8_t *p;
799     Glyph *glyph = NULL;
800
801     for (i = 0, p = text; *p; i++) {
802         Glyph dummy = { 0 };
803         GET_UTF8(code, *p++, continue;);
804
805         /* skip new line chars, just go to new line */
806         if (code == '\n' || code == '\r' || code == '\t')
807             continue;
808
809         dummy.code = code;
810         glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
811
812         if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
813             glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
814             return AVERROR(EINVAL);
815
816         x1 = dtext->positions[i].x+dtext->x+x;
817         y1 = dtext->positions[i].y+dtext->y+y;
818
819         ff_blend_mask(&dtext->dc, color,
820                       frame->data, frame->linesize, width, height,
821                       glyph->bitmap.buffer, glyph->bitmap.pitch,
822                       glyph->bitmap.width, glyph->bitmap.rows,
823                       glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
824                       0, x1, y1);
825     }
826
827     return 0;
828 }
829
830 static int draw_text(AVFilterContext *ctx, AVFrame *frame,
831                      int width, int height)
832 {
833     DrawTextContext *dtext = ctx->priv;
834     AVFilterLink *inlink = ctx->inputs[0];
835     uint32_t code = 0, prev_code = 0;
836     int x = 0, y = 0, i = 0, ret;
837     int max_text_line_w = 0, len;
838     int box_w, box_h;
839     char *text = dtext->text;
840     uint8_t *p;
841     int y_min = 32000, y_max = -32000;
842     int x_min = 32000, x_max = -32000;
843     FT_Vector delta;
844     Glyph *glyph = NULL, *prev_glyph = NULL;
845     Glyph dummy = { 0 };
846
847     time_t now = time(0);
848     struct tm ltime;
849     AVBPrint *bp = &dtext->expanded_text;
850
851     av_bprint_clear(bp);
852
853     if(dtext->basetime != AV_NOPTS_VALUE)
854         now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
855
856     switch (dtext->exp_mode) {
857     case EXP_NONE:
858         av_bprintf(bp, "%s", dtext->text);
859         break;
860     case EXP_NORMAL:
861         if ((ret = expand_text(ctx)) < 0)
862             return ret;
863         break;
864     case EXP_STRFTIME:
865         localtime_r(&now, &ltime);
866         av_bprint_strftime(bp, dtext->text, &ltime);
867         break;
868     }
869
870     if (dtext->tc_opt_string) {
871         char tcbuf[AV_TIMECODE_STR_SIZE];
872         av_timecode_make_string(&dtext->tc, tcbuf, inlink->frame_count);
873         av_bprint_clear(bp);
874         av_bprintf(bp, "%s%s", dtext->text, tcbuf);
875     }
876
877     if (!av_bprint_is_complete(bp))
878         return AVERROR(ENOMEM);
879     text = dtext->expanded_text.str;
880     if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
881         if (!(dtext->positions =
882               av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
883             return AVERROR(ENOMEM);
884         dtext->nb_positions = len;
885     }
886
887     x = 0;
888     y = 0;
889
890     /* load and cache glyphs */
891     for (i = 0, p = text; *p; i++) {
892         GET_UTF8(code, *p++, continue;);
893
894         /* get glyph */
895         dummy.code = code;
896         glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
897         if (!glyph) {
898             load_glyph(ctx, &glyph, code);
899         }
900
901         y_min = FFMIN(glyph->bbox.yMin, y_min);
902         y_max = FFMAX(glyph->bbox.yMax, y_max);
903         x_min = FFMIN(glyph->bbox.xMin, x_min);
904         x_max = FFMAX(glyph->bbox.xMax, x_max);
905     }
906     dtext->max_glyph_h = y_max - y_min;
907     dtext->max_glyph_w = x_max - x_min;
908
909     /* compute and save position for each glyph */
910     glyph = NULL;
911     for (i = 0, p = text; *p; i++) {
912         GET_UTF8(code, *p++, continue;);
913
914         /* skip the \n in the sequence \r\n */
915         if (prev_code == '\r' && code == '\n')
916             continue;
917
918         prev_code = code;
919         if (is_newline(code)) {
920             max_text_line_w = FFMAX(max_text_line_w, x);
921             y += dtext->max_glyph_h;
922             x = 0;
923             continue;
924         }
925
926         /* get glyph */
927         prev_glyph = glyph;
928         dummy.code = code;
929         glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
930
931         /* kerning */
932         if (dtext->use_kerning && prev_glyph && glyph->code) {
933             FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
934                            ft_kerning_default, &delta);
935             x += delta.x >> 6;
936         }
937
938         /* save position */
939         dtext->positions[i].x = x + glyph->bitmap_left;
940         dtext->positions[i].y = y - glyph->bitmap_top + y_max;
941         if (code == '\t') x  = (x / dtext->tabsize + 1)*dtext->tabsize;
942         else              x += glyph->advance;
943     }
944
945     max_text_line_w = FFMAX(x, max_text_line_w);
946
947     dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
948     dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
949
950     dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
951     dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
952     dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
953     dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
954
955     dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
956
957     dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
958     dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
959     dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
960     dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
961
962     if(!dtext->draw)
963         return 0;
964
965     box_w = FFMIN(width - 1 , max_text_line_w);
966     box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
967
968     /* draw box */
969     if (dtext->draw_box)
970         ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
971                            frame->data, frame->linesize, width, height,
972                            dtext->x, dtext->y, box_w, box_h);
973
974     if (dtext->shadowx || dtext->shadowy) {
975         if ((ret = draw_glyphs(dtext, frame, width, height, dtext->shadowcolor.rgba,
976                                &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
977             return ret;
978     }
979
980     if ((ret = draw_glyphs(dtext, frame, width, height, dtext->fontcolor.rgba,
981                            &dtext->fontcolor, 0, 0)) < 0)
982         return ret;
983
984     return 0;
985 }
986
987 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
988 {
989     AVFilterContext *ctx = inlink->dst;
990     AVFilterLink *outlink = ctx->outputs[0];
991     DrawTextContext *dtext = ctx->priv;
992     int ret;
993
994     if (dtext->reload)
995         if ((ret = load_textfile(ctx)) < 0)
996             return ret;
997
998     dtext->var_values[VAR_N] = inlink->frame_count;
999     dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
1000         NAN : frame->pts * av_q2d(inlink->time_base);
1001
1002     dtext->var_values[VAR_PICT_TYPE] = frame->pict_type;
1003
1004     draw_text(ctx, frame, frame->width, frame->height);
1005
1006     av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
1007            (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
1008            (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
1009            dtext->x, dtext->y);
1010
1011     return ff_filter_frame(outlink, frame);
1012 }
1013
1014 static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
1015     {
1016         .name             = "default",
1017         .type             = AVMEDIA_TYPE_VIDEO,
1018         .get_video_buffer = ff_null_get_video_buffer,
1019         .filter_frame     = filter_frame,
1020         .config_props     = config_input,
1021         .needs_writable   = 1,
1022     },
1023     { NULL }
1024 };
1025
1026 static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
1027     {
1028         .name = "default",
1029         .type = AVMEDIA_TYPE_VIDEO,
1030     },
1031     { NULL }
1032 };
1033
1034 AVFilter avfilter_vf_drawtext = {
1035     .name          = "drawtext",
1036     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1037     .priv_size     = sizeof(DrawTextContext),
1038     .priv_class    = &drawtext_class,
1039     .init          = init,
1040     .uninit        = uninit,
1041     .query_formats = query_formats,
1042
1043     .inputs    = avfilter_vf_drawtext_inputs,
1044     .outputs   = avfilter_vf_drawtext_outputs,
1045     .process_command = command,
1046 };