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