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