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