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