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