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