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