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