]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_drawtext.c
vp9: copy bug in libvpx for 4:2:2 chroma bs=8x4/4x4 prediction.
[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 "config.h"
30
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <time.h>
37 #if HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #include <fenv.h>
41
42 #if CONFIG_LIBFONTCONFIG
43 #include <fontconfig/fontconfig.h>
44 #endif
45
46 #include "libavutil/avstring.h"
47 #include "libavutil/bprint.h"
48 #include "libavutil/common.h"
49 #include "libavutil/file.h"
50 #include "libavutil/eval.h"
51 #include "libavutil/opt.h"
52 #include "libavutil/random_seed.h"
53 #include "libavutil/parseutils.h"
54 #include "libavutil/timecode.h"
55 #include "libavutil/time_internal.h"
56 #include "libavutil/tree.h"
57 #include "libavutil/lfg.h"
58 #include "avfilter.h"
59 #include "drawutils.h"
60 #include "formats.h"
61 #include "internal.h"
62 #include "video.h"
63
64 #if CONFIG_LIBFRIBIDI
65 #include <fribidi.h>
66 #endif
67
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #include FT_GLYPH_H
71 #include FT_STROKER_H
72
73 static const char *const var_names[] = {
74     "dar",
75     "hsub", "vsub",
76     "line_h", "lh",           ///< line height, same as max_glyph_h
77     "main_h", "h", "H",       ///< height of the input video
78     "main_w", "w", "W",       ///< width  of the input video
79     "max_glyph_a", "ascent",  ///< max glyph ascent
80     "max_glyph_d", "descent", ///< min glyph descent
81     "max_glyph_h",            ///< max glyph height
82     "max_glyph_w",            ///< max glyph width
83     "n",                      ///< number of frame
84     "sar",
85     "t",                      ///< timestamp expressed in seconds
86     "text_h", "th",           ///< height of the rendered text
87     "text_w", "tw",           ///< width  of the rendered text
88     "x",
89     "y",
90     "pict_type",
91     NULL
92 };
93
94 static const char *const fun2_names[] = {
95     "rand"
96 };
97
98 static double drand(void *opaque, double min, double max)
99 {
100     return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
101 }
102
103 typedef double (*eval_func2)(void *, double a, double b);
104
105 static const eval_func2 fun2[] = {
106     drand,
107     NULL
108 };
109
110 enum var_name {
111     VAR_DAR,
112     VAR_HSUB, VAR_VSUB,
113     VAR_LINE_H, VAR_LH,
114     VAR_MAIN_H, VAR_h, VAR_H,
115     VAR_MAIN_W, VAR_w, VAR_W,
116     VAR_MAX_GLYPH_A, VAR_ASCENT,
117     VAR_MAX_GLYPH_D, VAR_DESCENT,
118     VAR_MAX_GLYPH_H,
119     VAR_MAX_GLYPH_W,
120     VAR_N,
121     VAR_SAR,
122     VAR_T,
123     VAR_TEXT_H, VAR_TH,
124     VAR_TEXT_W, VAR_TW,
125     VAR_X,
126     VAR_Y,
127     VAR_PICT_TYPE,
128     VAR_VARS_NB
129 };
130
131 enum expansion_mode {
132     EXP_NONE,
133     EXP_NORMAL,
134     EXP_STRFTIME,
135 };
136
137 typedef struct DrawTextContext {
138     const AVClass *class;
139     int exp_mode;                   ///< expansion mode to use for the text
140     int reinit;                     ///< tells if the filter is being reinited
141 #if CONFIG_LIBFONTCONFIG
142     uint8_t *font;              ///< font to be used
143 #endif
144     uint8_t *fontfile;              ///< font to be used
145     uint8_t *text;                  ///< text to be drawn
146     AVBPrint expanded_text;         ///< used to contain the expanded text
147     uint8_t *fontcolor_expr;        ///< fontcolor expression to evaluate
148     AVBPrint expanded_fontcolor;    ///< used to contain the expanded fontcolor spec
149     int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
150     FT_Vector *positions;           ///< positions for each element in the text
151     size_t nb_positions;            ///< number of elements of positions array
152     char *textfile;                 ///< file with text to be drawn
153     int x;                          ///< x position to start drawing text
154     int y;                          ///< y position to start drawing text
155     int max_glyph_w;                ///< max glyph width
156     int max_glyph_h;                ///< max glyph height
157     int shadowx, shadowy;
158     int borderw;                    ///< border width
159     unsigned int fontsize;          ///< font size to use
160
161     short int draw_box;             ///< draw box around text - true or false
162     int boxborderw;                 ///< box border width
163     int use_kerning;                ///< font kerning is used - true/false
164     int tabsize;                    ///< tab size
165     int fix_bounds;                 ///< do we let it go out of frame bounds - t/f
166
167     FFDrawContext dc;
168     FFDrawColor fontcolor;          ///< foreground color
169     FFDrawColor shadowcolor;        ///< shadow color
170     FFDrawColor bordercolor;        ///< border color
171     FFDrawColor boxcolor;           ///< background color
172
173     FT_Library library;             ///< freetype font library handle
174     FT_Face face;                   ///< freetype font face handle
175     FT_Stroker stroker;             ///< freetype stroker handle
176     struct AVTreeNode *glyphs;      ///< rendered glyphs, stored using the UTF-32 char code
177     char *x_expr;                   ///< expression for x position
178     char *y_expr;                   ///< expression for y position
179     AVExpr *x_pexpr, *y_pexpr;      ///< parsed expressions for x and y
180     int64_t basetime;               ///< base pts time in the real world for display
181     double var_values[VAR_VARS_NB];
182     char   *a_expr;
183     AVExpr *a_pexpr;
184     int alpha;
185     AVLFG  prng;                    ///< random
186     char       *tc_opt_string;      ///< specified timecode option string
187     AVRational  tc_rate;            ///< frame rate for timecode
188     AVTimecode  tc;                 ///< timecode context
189     int tc24hmax;                   ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
190     int reload;                     ///< reload text file for each frame
191     int start_number;               ///< starting frame number for n/frame_num var
192 #if CONFIG_LIBFRIBIDI
193     int text_shaping;               ///< 1 to shape the text before drawing it
194 #endif
195     AVDictionary *metadata;
196 } DrawTextContext;
197
198 #define OFFSET(x) offsetof(DrawTextContext, x)
199 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
200
201 static const AVOption drawtext_options[]= {
202     {"fontfile",    "set font file",        OFFSET(fontfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
203     {"text",        "set text",             OFFSET(text),               AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
204     {"textfile",    "set text file",        OFFSET(textfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX, FLAGS},
205     {"fontcolor",   "set foreground color", OFFSET(fontcolor.rgba),     AV_OPT_TYPE_COLOR,  {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
206     {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, CHAR_MIN, CHAR_MAX, FLAGS},
207     {"boxcolor",    "set box color",        OFFSET(boxcolor.rgba),      AV_OPT_TYPE_COLOR,  {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
208     {"bordercolor", "set border color",     OFFSET(bordercolor.rgba),   AV_OPT_TYPE_COLOR,  {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
209     {"shadowcolor", "set shadow color",     OFFSET(shadowcolor.rgba),   AV_OPT_TYPE_COLOR,  {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
210     {"box",         "set box",              OFFSET(draw_box),           AV_OPT_TYPE_INT,    {.i64=0},     0,        1       , FLAGS},
211     {"boxborderw",  "set box border width", OFFSET(boxborderw),         AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
212     {"fontsize",    "set font size",        OFFSET(fontsize),           AV_OPT_TYPE_INT,    {.i64=0},     0,        INT_MAX , FLAGS},
213     {"x",           "set x expression",     OFFSET(x_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX, FLAGS},
214     {"y",           "set y expression",     OFFSET(y_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX, FLAGS},
215     {"shadowx",     "set x",                OFFSET(shadowx),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
216     {"shadowy",     "set y",                OFFSET(shadowy),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
217     {"borderw",     "set border width",     OFFSET(borderw),            AV_OPT_TYPE_INT,    {.i64=0},     INT_MIN,  INT_MAX , FLAGS},
218     {"tabsize",     "set tab size",         OFFSET(tabsize),            AV_OPT_TYPE_INT,    {.i64=4},     0,        INT_MAX , FLAGS},
219     {"basetime",    "set base time",        OFFSET(basetime),           AV_OPT_TYPE_INT64,  {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
220 #if CONFIG_LIBFONTCONFIG
221     { "font",        "Font name",            OFFSET(font),               AV_OPT_TYPE_STRING, { .str = "Sans" },           .flags = FLAGS },
222 #endif
223
224     {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
225         {"none",     "set no expansion",                    OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE},     0, 0, FLAGS, "expansion"},
226         {"normal",   "set normal expansion",                OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL},   0, 0, FLAGS, "expansion"},
227         {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
228
229     {"timecode",        "set initial timecode",             OFFSET(tc_opt_string), AV_OPT_TYPE_STRING,   {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
230     {"tc24hmax",        "set 24 hours max (timecode only)", OFFSET(tc24hmax),      AV_OPT_TYPE_INT,      {.i64=0},           0,        1, FLAGS},
231     {"timecode_rate",   "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
232     {"r",               "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
233     {"rate",            "set rate (timecode only)",         OFFSET(tc_rate),       AV_OPT_TYPE_RATIONAL, {.dbl=0},           0,  INT_MAX, FLAGS},
234     {"reload",     "reload text file for each frame",                       OFFSET(reload),     AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
235     { "alpha",       "apply alpha while rendering", OFFSET(a_expr),      AV_OPT_TYPE_STRING, { .str = "1"     },          .flags = FLAGS },
236     {"fix_bounds", "if true, check and fix text coords to avoid clipping",  OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
237     {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
238
239 #if CONFIG_LIBFRIBIDI
240     {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
241 #endif
242
243     /* FT_LOAD_* flags */
244     { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, "ft_load_flags" },
245         { "default",                     NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT },                     .flags = FLAGS, .unit = "ft_load_flags" },
246         { "no_scale",                    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE },                    .flags = FLAGS, .unit = "ft_load_flags" },
247         { "no_hinting",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING },                  .flags = FLAGS, .unit = "ft_load_flags" },
248         { "render",                      NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER },                      .flags = FLAGS, .unit = "ft_load_flags" },
249         { "no_bitmap",                   NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP },                   .flags = FLAGS, .unit = "ft_load_flags" },
250         { "vertical_layout",             NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT },             .flags = FLAGS, .unit = "ft_load_flags" },
251         { "force_autohint",              NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT },              .flags = FLAGS, .unit = "ft_load_flags" },
252         { "crop_bitmap",                 NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP },                 .flags = FLAGS, .unit = "ft_load_flags" },
253         { "pedantic",                    NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC },                    .flags = FLAGS, .unit = "ft_load_flags" },
254         { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
255         { "no_recurse",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE },                  .flags = FLAGS, .unit = "ft_load_flags" },
256         { "ignore_transform",            NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM },            .flags = FLAGS, .unit = "ft_load_flags" },
257         { "monochrome",                  NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME },                  .flags = FLAGS, .unit = "ft_load_flags" },
258         { "linear_design",               NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN },               .flags = FLAGS, .unit = "ft_load_flags" },
259         { "no_autohint",                 NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT },                 .flags = FLAGS, .unit = "ft_load_flags" },
260     { NULL }
261 };
262
263 AVFILTER_DEFINE_CLASS(drawtext);
264
265 #undef __FTERRORS_H__
266 #define FT_ERROR_START_LIST {
267 #define FT_ERRORDEF(e, v, s) { (e), (s) },
268 #define FT_ERROR_END_LIST { 0, NULL } };
269
270 static const struct ft_error
271 {
272     int err;
273     const char *err_msg;
274 } ft_errors[] =
275 #include FT_ERRORS_H
276
277 #define FT_ERRMSG(e) ft_errors[e].err_msg
278
279 typedef struct Glyph {
280     FT_Glyph glyph;
281     FT_Glyph border_glyph;
282     uint32_t code;
283     FT_Bitmap bitmap; ///< array holding bitmaps of font
284     FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
285     FT_BBox bbox;
286     int advance;
287     int bitmap_left;
288     int bitmap_top;
289 } Glyph;
290
291 static int glyph_cmp(void *key, const void *b)
292 {
293     const Glyph *a = key, *bb = b;
294     int64_t diff = (int64_t)a->code - (int64_t)bb->code;
295     return diff > 0 ? 1 : diff < 0 ? -1 : 0;
296 }
297
298 /**
299  * Load glyphs corresponding to the UTF-32 codepoint code.
300  */
301 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
302 {
303     DrawTextContext *s = ctx->priv;
304     FT_BitmapGlyph bitmapglyph;
305     Glyph *glyph;
306     struct AVTreeNode *node = NULL;
307     int ret;
308
309     /* load glyph into s->face->glyph */
310     if (FT_Load_Char(s->face, code, s->ft_load_flags))
311         return AVERROR(EINVAL);
312
313     glyph = av_mallocz(sizeof(*glyph));
314     if (!glyph) {
315         ret = AVERROR(ENOMEM);
316         goto error;
317     }
318     glyph->code  = code;
319
320     if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
321         ret = AVERROR(EINVAL);
322         goto error;
323     }
324     if (s->borderw) {
325         glyph->border_glyph = glyph->glyph;
326         if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
327             FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
328             ret = AVERROR_EXTERNAL;
329             goto error;
330         }
331         bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
332         glyph->border_bitmap = bitmapglyph->bitmap;
333     }
334     if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
335         ret = AVERROR_EXTERNAL;
336         goto error;
337     }
338     bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
339
340     glyph->bitmap      = bitmapglyph->bitmap;
341     glyph->bitmap_left = bitmapglyph->left;
342     glyph->bitmap_top  = bitmapglyph->top;
343     glyph->advance     = s->face->glyph->advance.x >> 6;
344
345     /* measure text height to calculate text_height (or the maximum text height) */
346     FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
347
348     /* cache the newly created glyph */
349     if (!(node = av_tree_node_alloc())) {
350         ret = AVERROR(ENOMEM);
351         goto error;
352     }
353     av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
354
355     if (glyph_ptr)
356         *glyph_ptr = glyph;
357     return 0;
358
359 error:
360     if (glyph)
361         av_freep(&glyph->glyph);
362
363     av_freep(&glyph);
364     av_freep(&node);
365     return ret;
366 }
367
368 static int load_font_file(AVFilterContext *ctx, const char *path, int index)
369 {
370     DrawTextContext *s = ctx->priv;
371     int err;
372
373     err = FT_New_Face(s->library, path, index, &s->face);
374     if (err) {
375         av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
376                s->fontfile, FT_ERRMSG(err));
377         return AVERROR(EINVAL);
378     }
379     return 0;
380 }
381
382 #if CONFIG_LIBFONTCONFIG
383 static int load_font_fontconfig(AVFilterContext *ctx)
384 {
385     DrawTextContext *s = ctx->priv;
386     FcConfig *fontconfig;
387     FcPattern *pat, *best;
388     FcResult result = FcResultMatch;
389     FcChar8 *filename;
390     int index;
391     double size;
392     int err = AVERROR(ENOENT);
393
394     fontconfig = FcInitLoadConfigAndFonts();
395     if (!fontconfig) {
396         av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
397         return AVERROR_UNKNOWN;
398     }
399     pat = FcNameParse(s->fontfile ? s->fontfile :
400                           (uint8_t *)(intptr_t)"default");
401     if (!pat) {
402         av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
403         return AVERROR(EINVAL);
404     }
405
406     FcPatternAddString(pat, FC_FAMILY, s->font);
407     if (s->fontsize)
408         FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
409
410     FcDefaultSubstitute(pat);
411
412     if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
413         av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
414         FcPatternDestroy(pat);
415         return AVERROR(ENOMEM);
416     }
417
418     best = FcFontMatch(fontconfig, pat, &result);
419     FcPatternDestroy(pat);
420
421     if (!best || result != FcResultMatch) {
422         av_log(ctx, AV_LOG_ERROR,
423                "Cannot find a valid font for the family %s\n",
424                s->font);
425         goto fail;
426     }
427
428     if (
429         FcPatternGetInteger(best, FC_INDEX, 0, &index   ) != FcResultMatch ||
430         FcPatternGetDouble (best, FC_SIZE,  0, &size    ) != FcResultMatch) {
431         av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
432         return AVERROR(EINVAL);
433     }
434
435     if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
436         av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
437                s->font);
438         goto fail;
439     }
440
441     av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
442     if (!s->fontsize)
443         s->fontsize = size + 0.5;
444
445     err = load_font_file(ctx, filename, index);
446     if (err)
447         return err;
448     FcConfigDestroy(fontconfig);
449 fail:
450     FcPatternDestroy(best);
451     return err;
452 }
453 #endif
454
455 static int load_font(AVFilterContext *ctx)
456 {
457     DrawTextContext *s = ctx->priv;
458     int err;
459
460     /* load the face, and set up the encoding, which is by default UTF-8 */
461     err = load_font_file(ctx, s->fontfile, 0);
462     if (!err)
463         return 0;
464 #if CONFIG_LIBFONTCONFIG
465     err = load_font_fontconfig(ctx);
466     if (!err)
467         return 0;
468 #endif
469     return err;
470 }
471
472 static int load_textfile(AVFilterContext *ctx)
473 {
474     DrawTextContext *s = ctx->priv;
475     int err;
476     uint8_t *textbuf;
477     uint8_t *tmp;
478     size_t textbuf_size;
479
480     if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
481         av_log(ctx, AV_LOG_ERROR,
482                "The text file '%s' could not be read or is empty\n",
483                s->textfile);
484         return err;
485     }
486
487     if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
488         av_file_unmap(textbuf, textbuf_size);
489         return AVERROR(ENOMEM);
490     }
491     s->text = tmp;
492     memcpy(s->text, textbuf, textbuf_size);
493     s->text[textbuf_size] = 0;
494     av_file_unmap(textbuf, textbuf_size);
495
496     return 0;
497 }
498
499 static inline int is_newline(uint32_t c)
500 {
501     return c == '\n' || c == '\r' || c == '\f' || c == '\v';
502 }
503
504 #if CONFIG_LIBFRIBIDI
505 static int shape_text(AVFilterContext *ctx)
506 {
507     DrawTextContext *s = ctx->priv;
508     uint8_t *tmp;
509     int ret = AVERROR(ENOMEM);
510     static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
511                                       FRIBIDI_FLAGS_ARABIC;
512     FriBidiChar *unicodestr = NULL;
513     FriBidiStrIndex len;
514     FriBidiParType direction = FRIBIDI_PAR_LTR;
515     FriBidiStrIndex line_start = 0;
516     FriBidiStrIndex line_end = 0;
517     FriBidiLevel *embedding_levels = NULL;
518     FriBidiArabicProp *ar_props = NULL;
519     FriBidiCharType *bidi_types = NULL;
520     FriBidiStrIndex i,j;
521
522     len = strlen(s->text);
523     if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
524         goto out;
525     }
526     len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
527                                      s->text, len, unicodestr);
528
529     bidi_types = av_malloc_array(len, sizeof(*bidi_types));
530     if (!bidi_types) {
531         goto out;
532     }
533
534     fribidi_get_bidi_types(unicodestr, len, bidi_types);
535
536     embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
537     if (!embedding_levels) {
538         goto out;
539     }
540
541     if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
542                                           embedding_levels)) {
543         goto out;
544     }
545
546     ar_props = av_malloc_array(len, sizeof(*ar_props));
547     if (!ar_props) {
548         goto out;
549     }
550
551     fribidi_get_joining_types(unicodestr, len, ar_props);
552     fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
553     fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
554
555     for (line_end = 0, line_start = 0; line_end < len; line_end++) {
556         if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
557             if (!fribidi_reorder_line(flags, bidi_types,
558                                       line_end - line_start + 1, line_start,
559                                       direction, embedding_levels, unicodestr,
560                                       NULL)) {
561                 goto out;
562             }
563             line_start = line_end + 1;
564         }
565     }
566
567     /* Remove zero-width fill chars put in by libfribidi */
568     for (i = 0, j = 0; i < len; i++)
569         if (unicodestr[i] != FRIBIDI_CHAR_FILL)
570             unicodestr[j++] = unicodestr[i];
571     len = j;
572
573     if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
574         /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
575         goto out;
576     }
577
578     s->text = tmp;
579     len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
580                                      unicodestr, len, s->text);
581     ret = 0;
582
583 out:
584     av_free(unicodestr);
585     av_free(embedding_levels);
586     av_free(ar_props);
587     av_free(bidi_types);
588     return ret;
589 }
590 #endif
591
592 static av_cold int init(AVFilterContext *ctx)
593 {
594     int err;
595     DrawTextContext *s = ctx->priv;
596     Glyph *glyph;
597
598     if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
599         av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
600         return AVERROR(EINVAL);
601     }
602
603     if (s->textfile) {
604         if (s->text) {
605             av_log(ctx, AV_LOG_ERROR,
606                    "Both text and text file provided. Please provide only one\n");
607             return AVERROR(EINVAL);
608         }
609         if ((err = load_textfile(ctx)) < 0)
610             return err;
611     }
612
613 #if CONFIG_LIBFRIBIDI
614     if (s->text_shaping)
615         if ((err = shape_text(ctx)) < 0)
616             return err;
617 #endif
618
619     if (s->reload && !s->textfile)
620         av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
621
622     if (s->tc_opt_string) {
623         int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
624                                                s->tc_opt_string, ctx);
625         if (ret < 0)
626             return ret;
627         if (s->tc24hmax)
628             s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
629         if (!s->text)
630             s->text = av_strdup("");
631     }
632
633     if (!s->text) {
634         av_log(ctx, AV_LOG_ERROR,
635                "Either text, a valid file or a timecode must be provided\n");
636         return AVERROR(EINVAL);
637     }
638
639     if ((err = FT_Init_FreeType(&(s->library)))) {
640         av_log(ctx, AV_LOG_ERROR,
641                "Could not load FreeType: %s\n", FT_ERRMSG(err));
642         return AVERROR(EINVAL);
643     }
644
645     err = load_font(ctx);
646     if (err)
647         return err;
648     if (!s->fontsize)
649         s->fontsize = 16;
650     if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
651         av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
652                s->fontsize, FT_ERRMSG(err));
653         return AVERROR(EINVAL);
654     }
655
656     if (s->borderw) {
657         if (FT_Stroker_New(s->library, &s->stroker)) {
658             av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
659             return AVERROR_EXTERNAL;
660         }
661         FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
662                        FT_STROKER_LINEJOIN_ROUND, 0);
663     }
664
665     s->use_kerning = FT_HAS_KERNING(s->face);
666
667     /* load the fallback glyph with code 0 */
668     load_glyph(ctx, NULL, 0);
669
670     /* set the tabsize in pixels */
671     if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
672         av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
673         return err;
674     }
675     s->tabsize *= glyph->advance;
676
677     if (s->exp_mode == EXP_STRFTIME &&
678         (strchr(s->text, '%') || strchr(s->text, '\\')))
679         av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
680
681     av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
682     av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
683
684     return 0;
685 }
686
687 static int query_formats(AVFilterContext *ctx)
688 {
689     return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
690 }
691
692 static int glyph_enu_free(void *opaque, void *elem)
693 {
694     Glyph *glyph = elem;
695
696     FT_Done_Glyph(glyph->glyph);
697     FT_Done_Glyph(glyph->border_glyph);
698     av_free(elem);
699     return 0;
700 }
701
702 static av_cold void uninit(AVFilterContext *ctx)
703 {
704     DrawTextContext *s = ctx->priv;
705
706     av_expr_free(s->x_pexpr);
707     av_expr_free(s->y_pexpr);
708     s->x_pexpr = s->y_pexpr = NULL;
709     av_freep(&s->positions);
710     s->nb_positions = 0;
711
712
713     av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
714     av_tree_destroy(s->glyphs);
715     s->glyphs = NULL;
716
717     FT_Done_Face(s->face);
718     FT_Stroker_Done(s->stroker);
719     FT_Done_FreeType(s->library);
720
721     av_bprint_finalize(&s->expanded_text, NULL);
722     av_bprint_finalize(&s->expanded_fontcolor, NULL);
723 }
724
725 static int config_input(AVFilterLink *inlink)
726 {
727     AVFilterContext *ctx = inlink->dst;
728     DrawTextContext *s = ctx->priv;
729     int ret;
730
731     ff_draw_init(&s->dc, inlink->format, 0);
732     ff_draw_color(&s->dc, &s->fontcolor,   s->fontcolor.rgba);
733     ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
734     ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
735     ff_draw_color(&s->dc, &s->boxcolor,    s->boxcolor.rgba);
736
737     s->var_values[VAR_w]     = s->var_values[VAR_W]     = s->var_values[VAR_MAIN_W] = inlink->w;
738     s->var_values[VAR_h]     = s->var_values[VAR_H]     = s->var_values[VAR_MAIN_H] = inlink->h;
739     s->var_values[VAR_SAR]   = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
740     s->var_values[VAR_DAR]   = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
741     s->var_values[VAR_HSUB]  = 1 << s->dc.hsub_max;
742     s->var_values[VAR_VSUB]  = 1 << s->dc.vsub_max;
743     s->var_values[VAR_X]     = NAN;
744     s->var_values[VAR_Y]     = NAN;
745     s->var_values[VAR_T]     = NAN;
746
747     av_lfg_init(&s->prng, av_get_random_seed());
748
749     av_expr_free(s->x_pexpr);
750     av_expr_free(s->y_pexpr);
751     s->x_pexpr = s->y_pexpr = NULL;
752
753     if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
754                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
755         (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
756                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
757         (ret = av_expr_parse(&s->a_pexpr, s->a_expr, var_names,
758                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
759
760         return AVERROR(EINVAL);
761
762     return 0;
763 }
764
765 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
766 {
767     DrawTextContext *s = ctx->priv;
768
769     if (!strcmp(cmd, "reinit")) {
770         int ret;
771         uninit(ctx);
772         s->reinit = 1;
773         if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
774             return ret;
775         if ((ret = init(ctx)) < 0)
776             return ret;
777         return config_input(ctx->inputs[0]);
778     }
779
780     return AVERROR(ENOSYS);
781 }
782
783 static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
784                           char *fct, unsigned argc, char **argv, int tag)
785 {
786     DrawTextContext *s = ctx->priv;
787
788     av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
789     return 0;
790 }
791
792 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
793                     char *fct, unsigned argc, char **argv, int tag)
794 {
795     DrawTextContext *s = ctx->priv;
796     const char *fmt;
797     double pts = s->var_values[VAR_T];
798     int ret;
799
800     fmt = argc >= 1 ? argv[0] : "flt";
801     if (argc >= 2) {
802         int64_t delta;
803         if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
804             av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
805             return ret;
806         }
807         pts += (double)delta / AV_TIME_BASE;
808     }
809     if (!strcmp(fmt, "flt")) {
810         av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
811     } else if (!strcmp(fmt, "hms")) {
812         if (isnan(pts)) {
813             av_bprintf(bp, " ??:??:??.???");
814         } else {
815             int64_t ms = round(pts * 1000);
816             char sign = ' ';
817             if (ms < 0) {
818                 sign = '-';
819                 ms = -ms;
820             }
821             av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
822                        (int)(ms / (60 * 60 * 1000)),
823                        (int)(ms / (60 * 1000)) % 60,
824                        (int)(ms / 1000) % 60,
825                        (int)ms % 1000);
826         }
827     } else {
828         av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
829         return AVERROR(EINVAL);
830     }
831     return 0;
832 }
833
834 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
835                           char *fct, unsigned argc, char **argv, int tag)
836 {
837     DrawTextContext *s = ctx->priv;
838
839     av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
840     return 0;
841 }
842
843 static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
844                          char *fct, unsigned argc, char **argv, int tag)
845 {
846     DrawTextContext *s = ctx->priv;
847     AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
848
849     if (e && e->value)
850         av_bprintf(bp, "%s", e->value);
851     return 0;
852 }
853
854 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
855                          char *fct, unsigned argc, char **argv, int tag)
856 {
857     const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
858     time_t now;
859     struct tm tm;
860
861     time(&now);
862     if (tag == 'L')
863         localtime_r(&now, &tm);
864     else
865         tm = *gmtime_r(&now, &tm);
866     av_bprint_strftime(bp, fmt, &tm);
867     return 0;
868 }
869
870 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
871                           char *fct, unsigned argc, char **argv, int tag)
872 {
873     DrawTextContext *s = ctx->priv;
874     double res;
875     int ret;
876
877     ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
878                                  NULL, NULL, fun2_names, fun2,
879                                  &s->prng, 0, ctx);
880     if (ret < 0)
881         av_log(ctx, AV_LOG_ERROR,
882                "Expression '%s' for the expr text expansion function is not valid\n",
883                argv[0]);
884     else
885         av_bprintf(bp, "%f", res);
886
887     return ret;
888 }
889
890 static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
891                           char *fct, unsigned argc, char **argv, int tag)
892 {
893     DrawTextContext *s = ctx->priv;
894     double res;
895     int intval;
896     int ret;
897     unsigned int positions = 0;
898     char fmt_str[30] = "%";
899
900     /*
901      * argv[0] expression to be converted to `int`
902      * argv[1] format: 'x', 'X', 'd' or 'u'
903      * argv[2] positions printed (optional)
904      */
905
906     ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
907                                  NULL, NULL, fun2_names, fun2,
908                                  &s->prng, 0, ctx);
909     if (ret < 0) {
910         av_log(ctx, AV_LOG_ERROR,
911                "Expression '%s' for the expr text expansion function is not valid\n",
912                argv[0]);
913         return ret;
914     }
915
916     if (!strchr("xXdu", argv[1][0])) {
917         av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
918                 " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
919         return AVERROR(EINVAL);
920     }
921
922     if (argc == 3) {
923         ret = sscanf(argv[2], "%u", &positions);
924         if (ret != 1) {
925             av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
926                     " to print: '%s'\n", argv[2]);
927             return AVERROR(EINVAL);
928         }
929     }
930
931     feclearexcept(FE_ALL_EXCEPT);
932     intval = res;
933     if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
934         av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
935         return AVERROR(EINVAL);
936     }
937
938     if (argc == 3)
939         av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
940     av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
941
942     av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
943             res, argv[0], fmt_str);
944
945     av_bprintf(bp, fmt_str, intval);
946
947     return 0;
948 }
949
950 static const struct drawtext_function {
951     const char *name;
952     unsigned argc_min, argc_max;
953     int tag;                            /**< opaque argument to func */
954     int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
955 } functions[] = {
956     { "expr",      1, 1, 0,   func_eval_expr },
957     { "e",         1, 1, 0,   func_eval_expr },
958     { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
959     { "eif",       2, 3, 0,   func_eval_expr_int_format },
960     { "pict_type", 0, 0, 0,   func_pict_type },
961     { "pts",       0, 2, 0,   func_pts      },
962     { "gmtime",    0, 1, 'G', func_strftime },
963     { "localtime", 0, 1, 'L', func_strftime },
964     { "frame_num", 0, 0, 0,   func_frame_num },
965     { "n",         0, 0, 0,   func_frame_num },
966     { "metadata",  1, 1, 0,   func_metadata },
967 };
968
969 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
970                          unsigned argc, char **argv)
971 {
972     unsigned i;
973
974     for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
975         if (strcmp(fct, functions[i].name))
976             continue;
977         if (argc < functions[i].argc_min) {
978             av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
979                    fct, functions[i].argc_min);
980             return AVERROR(EINVAL);
981         }
982         if (argc > functions[i].argc_max) {
983             av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
984                    fct, functions[i].argc_max);
985             return AVERROR(EINVAL);
986         }
987         break;
988     }
989     if (i >= FF_ARRAY_ELEMS(functions)) {
990         av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
991         return AVERROR(EINVAL);
992     }
993     return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
994 }
995
996 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
997 {
998     const char *text = *rtext;
999     char *argv[16] = { NULL };
1000     unsigned argc = 0, i;
1001     int ret;
1002
1003     if (*text != '{') {
1004         av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
1005         return AVERROR(EINVAL);
1006     }
1007     text++;
1008     while (1) {
1009         if (!(argv[argc++] = av_get_token(&text, ":}"))) {
1010             ret = AVERROR(ENOMEM);
1011             goto end;
1012         }
1013         if (!*text) {
1014             av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
1015             ret = AVERROR(EINVAL);
1016             goto end;
1017         }
1018         if (argc == FF_ARRAY_ELEMS(argv))
1019             av_freep(&argv[--argc]); /* error will be caught later */
1020         if (*text == '}')
1021             break;
1022         text++;
1023     }
1024
1025     if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
1026         goto end;
1027     ret = 0;
1028     *rtext = (char *)text + 1;
1029
1030 end:
1031     for (i = 0; i < argc; i++)
1032         av_freep(&argv[i]);
1033     return ret;
1034 }
1035
1036 static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
1037 {
1038     int ret;
1039
1040     av_bprint_clear(bp);
1041     while (*text) {
1042         if (*text == '\\' && text[1]) {
1043             av_bprint_chars(bp, text[1], 1);
1044             text += 2;
1045         } else if (*text == '%') {
1046             text++;
1047             if ((ret = expand_function(ctx, bp, &text)) < 0)
1048                 return ret;
1049         } else {
1050             av_bprint_chars(bp, *text, 1);
1051             text++;
1052         }
1053     }
1054     if (!av_bprint_is_complete(bp))
1055         return AVERROR(ENOMEM);
1056     return 0;
1057 }
1058
1059 static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
1060                        int width, int height,
1061                        FFDrawColor *color,
1062                        int x, int y, int borderw)
1063 {
1064     char *text = s->expanded_text.str;
1065     uint32_t code = 0;
1066     int i, x1, y1;
1067     uint8_t *p;
1068     Glyph *glyph = NULL;
1069
1070     for (i = 0, p = text; *p; i++) {
1071         FT_Bitmap bitmap;
1072         Glyph dummy = { 0 };
1073         GET_UTF8(code, *p++, continue;);
1074
1075         /* skip new line chars, just go to new line */
1076         if (code == '\n' || code == '\r' || code == '\t')
1077             continue;
1078
1079         dummy.code = code;
1080         glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
1081
1082         bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
1083
1084         if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
1085             glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
1086             return AVERROR(EINVAL);
1087
1088         x1 = s->positions[i].x+s->x+x - borderw;
1089         y1 = s->positions[i].y+s->y+y - borderw;
1090
1091         ff_blend_mask(&s->dc, color,
1092                       frame->data, frame->linesize, width, height,
1093                       bitmap.buffer, bitmap.pitch,
1094                       bitmap.width, bitmap.rows,
1095                       bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
1096                       0, x1, y1);
1097     }
1098
1099     return 0;
1100 }
1101
1102
1103 static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
1104 {
1105     *color = incolor;
1106     color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
1107     ff_draw_color(&s->dc, color, color->rgba);
1108 }
1109
1110 static void update_alpha(DrawTextContext *s)
1111 {
1112     double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
1113
1114     if (isnan(alpha))
1115         return;
1116
1117     if (alpha >= 1.0)
1118         s->alpha = 255;
1119     else if (alpha <= 0)
1120         s->alpha = 0;
1121     else
1122         s->alpha = 256 * alpha;
1123 }
1124
1125 static int draw_text(AVFilterContext *ctx, AVFrame *frame,
1126                      int width, int height)
1127 {
1128     DrawTextContext *s = ctx->priv;
1129     AVFilterLink *inlink = ctx->inputs[0];
1130
1131     uint32_t code = 0, prev_code = 0;
1132     int x = 0, y = 0, i = 0, ret;
1133     int max_text_line_w = 0, len;
1134     int box_w, box_h;
1135     char *text;
1136     uint8_t *p;
1137     int y_min = 32000, y_max = -32000;
1138     int x_min = 32000, x_max = -32000;
1139     FT_Vector delta;
1140     Glyph *glyph = NULL, *prev_glyph = NULL;
1141     Glyph dummy = { 0 };
1142
1143     time_t now = time(0);
1144     struct tm ltime;
1145     AVBPrint *bp = &s->expanded_text;
1146
1147     FFDrawColor fontcolor;
1148     FFDrawColor shadowcolor;
1149     FFDrawColor bordercolor;
1150     FFDrawColor boxcolor;
1151
1152     av_bprint_clear(bp);
1153
1154     if(s->basetime != AV_NOPTS_VALUE)
1155         now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
1156
1157     switch (s->exp_mode) {
1158     case EXP_NONE:
1159         av_bprintf(bp, "%s", s->text);
1160         break;
1161     case EXP_NORMAL:
1162         if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
1163             return ret;
1164         break;
1165     case EXP_STRFTIME:
1166         localtime_r(&now, &ltime);
1167         av_bprint_strftime(bp, s->text, &ltime);
1168         break;
1169     }
1170
1171     if (s->tc_opt_string) {
1172         char tcbuf[AV_TIMECODE_STR_SIZE];
1173         av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
1174         av_bprint_clear(bp);
1175         av_bprintf(bp, "%s%s", s->text, tcbuf);
1176     }
1177
1178     if (!av_bprint_is_complete(bp))
1179         return AVERROR(ENOMEM);
1180     text = s->expanded_text.str;
1181     if ((len = s->expanded_text.len) > s->nb_positions) {
1182         if (!(s->positions =
1183               av_realloc(s->positions, len*sizeof(*s->positions))))
1184             return AVERROR(ENOMEM);
1185         s->nb_positions = len;
1186     }
1187
1188     if (s->fontcolor_expr[0]) {
1189         /* If expression is set, evaluate and replace the static value */
1190         av_bprint_clear(&s->expanded_fontcolor);
1191         if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
1192             return ret;
1193         if (!av_bprint_is_complete(&s->expanded_fontcolor))
1194             return AVERROR(ENOMEM);
1195         av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
1196         ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
1197         if (ret)
1198             return ret;
1199         ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
1200     }
1201
1202     x = 0;
1203     y = 0;
1204
1205     /* load and cache glyphs */
1206     for (i = 0, p = text; *p; i++) {
1207         GET_UTF8(code, *p++, continue;);
1208
1209         /* get glyph */
1210         dummy.code = code;
1211         glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1212         if (!glyph) {
1213             load_glyph(ctx, &glyph, code);
1214         }
1215
1216         y_min = FFMIN(glyph->bbox.yMin, y_min);
1217         y_max = FFMAX(glyph->bbox.yMax, y_max);
1218         x_min = FFMIN(glyph->bbox.xMin, x_min);
1219         x_max = FFMAX(glyph->bbox.xMax, x_max);
1220     }
1221     s->max_glyph_h = y_max - y_min;
1222     s->max_glyph_w = x_max - x_min;
1223
1224     /* compute and save position for each glyph */
1225     glyph = NULL;
1226     for (i = 0, p = text; *p; i++) {
1227         GET_UTF8(code, *p++, continue;);
1228
1229         /* skip the \n in the sequence \r\n */
1230         if (prev_code == '\r' && code == '\n')
1231             continue;
1232
1233         prev_code = code;
1234         if (is_newline(code)) {
1235
1236             max_text_line_w = FFMAX(max_text_line_w, x);
1237             y += s->max_glyph_h;
1238             x = 0;
1239             continue;
1240         }
1241
1242         /* get glyph */
1243         prev_glyph = glyph;
1244         dummy.code = code;
1245         glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1246
1247         /* kerning */
1248         if (s->use_kerning && prev_glyph && glyph->code) {
1249             FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
1250                            ft_kerning_default, &delta);
1251             x += delta.x >> 6;
1252         }
1253
1254         /* save position */
1255         s->positions[i].x = x + glyph->bitmap_left;
1256         s->positions[i].y = y - glyph->bitmap_top + y_max;
1257         if (code == '\t') x  = (x / s->tabsize + 1)*s->tabsize;
1258         else              x += glyph->advance;
1259     }
1260
1261     max_text_line_w = FFMAX(x, max_text_line_w);
1262
1263     s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
1264     s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
1265
1266     s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
1267     s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
1268     s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
1269     s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
1270
1271     s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
1272
1273     s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1274     s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
1275     s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1276
1277     update_alpha(s);
1278     update_color_with_alpha(s, &fontcolor  , s->fontcolor  );
1279     update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
1280     update_color_with_alpha(s, &bordercolor, s->bordercolor);
1281     update_color_with_alpha(s, &boxcolor   , s->boxcolor   );
1282
1283     box_w = FFMIN(width - 1 , max_text_line_w);
1284     box_h = FFMIN(height - 1, y + s->max_glyph_h);
1285
1286     /* draw box */
1287     if (s->draw_box)
1288         ff_blend_rectangle(&s->dc, &boxcolor,
1289                            frame->data, frame->linesize, width, height,
1290                            s->x - s->boxborderw, s->y - s->boxborderw,
1291                            box_w + s->boxborderw * 2, box_h + s->boxborderw * 2);
1292
1293     if (s->shadowx || s->shadowy) {
1294         if ((ret = draw_glyphs(s, frame, width, height,
1295                                &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
1296             return ret;
1297     }
1298
1299     if (s->borderw) {
1300         if ((ret = draw_glyphs(s, frame, width, height,
1301                                &bordercolor, 0, 0, s->borderw)) < 0)
1302             return ret;
1303     }
1304     if ((ret = draw_glyphs(s, frame, width, height,
1305                            &fontcolor, 0, 0, 0)) < 0)
1306         return ret;
1307
1308     return 0;
1309 }
1310
1311 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
1312 {
1313     AVFilterContext *ctx = inlink->dst;
1314     AVFilterLink *outlink = ctx->outputs[0];
1315     DrawTextContext *s = ctx->priv;
1316     int ret;
1317
1318     if (s->reload) {
1319         if ((ret = load_textfile(ctx)) < 0) {
1320             av_frame_free(&frame);
1321             return ret;
1322         }
1323 #if CONFIG_LIBFRIBIDI
1324         if (s->text_shaping)
1325             if ((ret = shape_text(ctx)) < 0) {
1326                 av_frame_free(&frame);
1327                 return ret;
1328             }
1329 #endif
1330     }
1331
1332     s->var_values[VAR_N] = inlink->frame_count+s->start_number;
1333     s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
1334         NAN : frame->pts * av_q2d(inlink->time_base);
1335
1336     s->var_values[VAR_PICT_TYPE] = frame->pict_type;
1337     s->metadata = av_frame_get_metadata(frame);
1338
1339     draw_text(ctx, frame, frame->width, frame->height);
1340
1341     av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
1342            (int)s->var_values[VAR_N], s->var_values[VAR_T],
1343            (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
1344            s->x, s->y);
1345
1346     return ff_filter_frame(outlink, frame);
1347 }
1348
1349 static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
1350     {
1351         .name           = "default",
1352         .type           = AVMEDIA_TYPE_VIDEO,
1353         .filter_frame   = filter_frame,
1354         .config_props   = config_input,
1355         .needs_writable = 1,
1356     },
1357     { NULL }
1358 };
1359
1360 static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
1361     {
1362         .name = "default",
1363         .type = AVMEDIA_TYPE_VIDEO,
1364     },
1365     { NULL }
1366 };
1367
1368 AVFilter ff_vf_drawtext = {
1369     .name          = "drawtext",
1370     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1371     .priv_size     = sizeof(DrawTextContext),
1372     .priv_class    = &drawtext_class,
1373     .init          = init,
1374     .uninit        = uninit,
1375     .query_formats = query_formats,
1376     .inputs        = avfilter_vf_drawtext_inputs,
1377     .outputs       = avfilter_vf_drawtext_outputs,
1378     .process_command = command,
1379     .flags         = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
1380 };