]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_drawtext.c
lavfi: make formats API private on next bump.
[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 Libav.
7  *
8  * Libav 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  * Libav 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 Libav; 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 "libavutil/colorspace.h"
33 #include "libavutil/file.h"
34 #include "libavutil/eval.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/random_seed.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/tree.h"
41 #include "libavutil/lfg.h"
42 #include "avfilter.h"
43 #include "drawutils.h"
44 #include "formats.h"
45 #include "video.h"
46
47 #undef time
48
49 #include <ft2build.h>
50 #include <freetype/config/ftheader.h>
51 #include FT_FREETYPE_H
52 #include FT_GLYPH_H
53
54 static const char *const var_names[] = {
55     "E",
56     "PHI",
57     "PI",
58     "main_w",    "W", ///< width  of the main    video
59     "main_h",    "H", ///< height of the main    video
60     "text_w",    "w", ///< width  of the overlay text
61     "text_h",    "h", ///< height of the overlay text
62     "x",
63     "y",
64     "n",              ///< number of processed frames
65     "t",              ///< timestamp expressed in seconds
66     NULL
67 };
68
69 static const char *const fun2_names[] = {
70     "rand"
71 };
72
73 static double drand(void *opaque, double min, double max)
74 {
75     return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
76 }
77
78 typedef double (*eval_func2)(void *, double a, double b);
79
80 static const eval_func2 fun2[] = {
81     drand,
82     NULL
83 };
84
85 enum var_name {
86     VAR_E,
87     VAR_PHI,
88     VAR_PI,
89     VAR_MAIN_W, VAR_MW,
90     VAR_MAIN_H, VAR_MH,
91     VAR_TEXT_W, VAR_TW,
92     VAR_TEXT_H, VAR_TH,
93     VAR_X,
94     VAR_Y,
95     VAR_N,
96     VAR_T,
97     VAR_VARS_NB
98 };
99
100 typedef struct {
101     const AVClass *class;
102     uint8_t *fontfile;              ///< font to be used
103     uint8_t *text;                  ///< text to be drawn
104     uint8_t *expanded_text;         ///< used to contain the strftime()-expanded text
105     size_t   expanded_text_size;    ///< size in bytes of the expanded_text buffer
106     int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
107     FT_Vector *positions;           ///< positions for each element in the text
108     size_t nb_positions;            ///< number of elements of positions array
109     char *textfile;                 ///< file with text to be drawn
110     int x, y;                       ///< position to start drawing text
111     int w, h;                       ///< dimension of the text block
112     int shadowx, shadowy;
113     unsigned int fontsize;          ///< font size to use
114     char *fontcolor_string;         ///< font color as string
115     char *boxcolor_string;          ///< box color as string
116     char *shadowcolor_string;       ///< shadow color as string
117     uint8_t fontcolor[4];           ///< foreground color
118     uint8_t boxcolor[4];            ///< background color
119     uint8_t shadowcolor[4];         ///< shadow color
120     uint8_t fontcolor_rgba[4];      ///< foreground color in RGBA
121     uint8_t boxcolor_rgba[4];       ///< background color in RGBA
122     uint8_t shadowcolor_rgba[4];    ///< shadow color in RGBA
123
124     short int draw_box;             ///< draw box around text - true or false
125     int use_kerning;                ///< font kerning is used - true/false
126     int tabsize;                    ///< tab size
127     int fix_bounds;                 ///< do we let it go out of frame bounds - t/f
128
129     FT_Library library;             ///< freetype font library handle
130     FT_Face face;                   ///< freetype font face handle
131     struct AVTreeNode *glyphs;      ///< rendered glyphs, stored using the UTF-32 char code
132     int hsub, vsub;                 ///< chroma subsampling values
133     int is_packed_rgb;
134     int pixel_step[4];              ///< distance in bytes between the component of each pixel
135     uint8_t rgba_map[4];            ///< map RGBA offsets to the positions in the packed RGBA format
136     uint8_t *box_line[4];           ///< line used for filling the box background
137     char   *x_expr, *y_expr;
138     AVExpr *x_pexpr, *y_pexpr;      ///< parsed expressions for x and y
139     double var_values[VAR_VARS_NB];
140     char   *d_expr;
141     AVExpr *d_pexpr;
142     int draw;                       ///< set to zero to prevent drawing
143     AVLFG  prng;                    ///< random
144 } DrawTextContext;
145
146 #define OFFSET(x) offsetof(DrawTextContext, x)
147
148 static const AVOption drawtext_options[]= {
149 {"fontfile", "set font file",        OFFSET(fontfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX },
150 {"text",     "set text",             OFFSET(text),               AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX },
151 {"textfile", "set text file",        OFFSET(textfile),           AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX },
152 {"fontcolor","set foreground color", OFFSET(fontcolor_string),   AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX },
153 {"boxcolor", "set box color",        OFFSET(boxcolor_string),    AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX },
154 {"shadowcolor", "set shadow color",  OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str=NULL},  CHAR_MIN, CHAR_MAX },
155 {"box",      "set box",              OFFSET(draw_box),           AV_OPT_TYPE_INT,    {.dbl=0},     0,        1        },
156 {"fontsize", "set font size",        OFFSET(fontsize),           AV_OPT_TYPE_INT,    {.dbl=16},    1,        72       },
157 {"x",        "set x",                OFFSET(x_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX },
158 {"y",        "set y",                OFFSET(y_expr),             AV_OPT_TYPE_STRING, {.str="0"},   CHAR_MIN, CHAR_MAX },
159 {"shadowx",  "set x",                OFFSET(shadowx),            AV_OPT_TYPE_INT,    {.dbl=0},     INT_MIN,  INT_MAX  },
160 {"shadowy",  "set y",                OFFSET(shadowy),            AV_OPT_TYPE_INT,    {.dbl=0},     INT_MIN,  INT_MAX  },
161 {"tabsize",  "set tab size",         OFFSET(tabsize),            AV_OPT_TYPE_INT,    {.dbl=4},     0,        INT_MAX  },
162 {"draw",     "if false do not draw", OFFSET(d_expr),             AV_OPT_TYPE_STRING, {.str="1"},   CHAR_MIN, CHAR_MAX },
163 {"fix_bounds", "if true, check and fix text coords to avoid clipping",
164                                      OFFSET(fix_bounds),         AV_OPT_TYPE_INT,    {.dbl=1},     0,        1        },
165
166 /* FT_LOAD_* flags */
167 {"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" },
168 {"default",                     "set default",                     0, AV_OPT_TYPE_CONST, {FT_LOAD_DEFAULT},                     INT_MIN, INT_MAX, 0, "ft_load_flags" },
169 {"no_scale",                    "set no_scale",                    0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_SCALE},                    INT_MIN, INT_MAX, 0, "ft_load_flags" },
170 {"no_hinting",                  "set no_hinting",                  0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_HINTING},                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
171 {"render",                      "set render",                      0, AV_OPT_TYPE_CONST, {FT_LOAD_RENDER},                      INT_MIN, INT_MAX, 0, "ft_load_flags" },
172 {"no_bitmap",                   "set no_bitmap",                   0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_BITMAP},                   INT_MIN, INT_MAX, 0, "ft_load_flags" },
173 {"vertical_layout",             "set vertical_layout",             0, AV_OPT_TYPE_CONST, {FT_LOAD_VERTICAL_LAYOUT},             INT_MIN, INT_MAX, 0, "ft_load_flags" },
174 {"force_autohint",              "set force_autohint",              0, AV_OPT_TYPE_CONST, {FT_LOAD_FORCE_AUTOHINT},              INT_MIN, INT_MAX, 0, "ft_load_flags" },
175 {"crop_bitmap",                 "set crop_bitmap",                 0, AV_OPT_TYPE_CONST, {FT_LOAD_CROP_BITMAP},                 INT_MIN, INT_MAX, 0, "ft_load_flags" },
176 {"pedantic",                    "set pedantic",                    0, AV_OPT_TYPE_CONST, {FT_LOAD_PEDANTIC},                    INT_MIN, INT_MAX, 0, "ft_load_flags" },
177 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
178 {"no_recurse",                  "set no_recurse",                  0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_RECURSE},                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
179 {"ignore_transform",            "set ignore_transform",            0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_TRANSFORM},            INT_MIN, INT_MAX, 0, "ft_load_flags" },
180 {"monochrome",                  "set monochrome",                  0, AV_OPT_TYPE_CONST, {FT_LOAD_MONOCHROME},                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
181 {"linear_design",               "set linear_design",               0, AV_OPT_TYPE_CONST, {FT_LOAD_LINEAR_DESIGN},               INT_MIN, INT_MAX, 0, "ft_load_flags" },
182 {"no_autohint",                 "set no_autohint",                 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_AUTOHINT},                 INT_MIN, INT_MAX, 0, "ft_load_flags" },
183 {NULL},
184 };
185
186 static const char *drawtext_get_name(void *ctx)
187 {
188     return "drawtext";
189 }
190
191 static const AVClass drawtext_class = {
192     "DrawTextContext",
193     drawtext_get_name,
194     drawtext_options
195 };
196
197 #undef __FTERRORS_H__
198 #define FT_ERROR_START_LIST {
199 #define FT_ERRORDEF(e, v, s) { (e), (s) },
200 #define FT_ERROR_END_LIST { 0, NULL } };
201
202 struct ft_error
203 {
204     int err;
205     const char *err_msg;
206 } static ft_errors[] =
207 #include FT_ERRORS_H
208
209 #define FT_ERRMSG(e) ft_errors[e].err_msg
210
211 typedef struct {
212     FT_Glyph *glyph;
213     uint32_t code;
214     FT_Bitmap bitmap; ///< array holding bitmaps of font
215     FT_BBox bbox;
216     int advance;
217     int bitmap_left;
218     int bitmap_top;
219 } Glyph;
220
221 static int glyph_cmp(void *key, const void *b)
222 {
223     const Glyph *a = key, *bb = b;
224     int64_t diff = (int64_t)a->code - (int64_t)bb->code;
225     return diff > 0 ? 1 : diff < 0 ? -1 : 0;
226 }
227
228 /**
229  * Load glyphs corresponding to the UTF-32 codepoint code.
230  */
231 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
232 {
233     DrawTextContext *dtext = ctx->priv;
234     Glyph *glyph;
235     struct AVTreeNode *node = NULL;
236     int ret;
237
238     /* load glyph into dtext->face->glyph */
239     if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
240         return AVERROR(EINVAL);
241
242     /* save glyph */
243     if (!(glyph = av_mallocz(sizeof(*glyph))) ||
244         !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
245         ret = AVERROR(ENOMEM);
246         goto error;
247     }
248     glyph->code  = code;
249
250     if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
251         ret = AVERROR(EINVAL);
252         goto error;
253     }
254
255     glyph->bitmap      = dtext->face->glyph->bitmap;
256     glyph->bitmap_left = dtext->face->glyph->bitmap_left;
257     glyph->bitmap_top  = dtext->face->glyph->bitmap_top;
258     glyph->advance     = dtext->face->glyph->advance.x >> 6;
259
260     /* measure text height to calculate text_height (or the maximum text height) */
261     FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
262
263     /* cache the newly created glyph */
264     if (!(node = av_mallocz(av_tree_node_size))) {
265         ret = AVERROR(ENOMEM);
266         goto error;
267     }
268     av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
269
270     if (glyph_ptr)
271         *glyph_ptr = glyph;
272     return 0;
273
274 error:
275     if (glyph)
276         av_freep(&glyph->glyph);
277     av_freep(&glyph);
278     av_freep(&node);
279     return ret;
280 }
281
282 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
283 {
284     int err;
285     DrawTextContext *dtext = ctx->priv;
286     Glyph *glyph;
287
288     dtext->class = &drawtext_class;
289     av_opt_set_defaults(dtext);
290     dtext->fontcolor_string = av_strdup("black");
291     dtext->boxcolor_string = av_strdup("white");
292     dtext->shadowcolor_string = av_strdup("black");
293
294     if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
295         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
296         return err;
297     }
298
299     if (!dtext->fontfile) {
300         av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
301         return AVERROR(EINVAL);
302     }
303
304     if (dtext->textfile) {
305         uint8_t *textbuf;
306         size_t textbuf_size;
307
308         if (dtext->text) {
309             av_log(ctx, AV_LOG_ERROR,
310                    "Both text and text file provided. Please provide only one\n");
311             return AVERROR(EINVAL);
312         }
313         if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
314             av_log(ctx, AV_LOG_ERROR,
315                    "The text file '%s' could not be read or is empty\n",
316                    dtext->textfile);
317             return err;
318         }
319
320         if (!(dtext->text = av_malloc(textbuf_size+1)))
321             return AVERROR(ENOMEM);
322         memcpy(dtext->text, textbuf, textbuf_size);
323         dtext->text[textbuf_size] = 0;
324         av_file_unmap(textbuf, textbuf_size);
325     }
326
327     if (!dtext->text) {
328         av_log(ctx, AV_LOG_ERROR,
329                "Either text or a valid file must be provided\n");
330         return AVERROR(EINVAL);
331     }
332
333     if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
334         av_log(ctx, AV_LOG_ERROR,
335                "Invalid font color '%s'\n", dtext->fontcolor_string);
336         return err;
337     }
338
339     if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
340         av_log(ctx, AV_LOG_ERROR,
341                "Invalid box color '%s'\n", dtext->boxcolor_string);
342         return err;
343     }
344
345     if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
346         av_log(ctx, AV_LOG_ERROR,
347                "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
348         return err;
349     }
350
351     if ((err = FT_Init_FreeType(&(dtext->library)))) {
352         av_log(ctx, AV_LOG_ERROR,
353                "Could not load FreeType: %s\n", FT_ERRMSG(err));
354         return AVERROR(EINVAL);
355     }
356
357     /* load the face, and set up the encoding, which is by default UTF-8 */
358     if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
359         av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
360                dtext->fontfile, FT_ERRMSG(err));
361         return AVERROR(EINVAL);
362     }
363     if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
364         av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
365                dtext->fontsize, FT_ERRMSG(err));
366         return AVERROR(EINVAL);
367     }
368
369     dtext->use_kerning = FT_HAS_KERNING(dtext->face);
370
371     /* load the fallback glyph with code 0 */
372     load_glyph(ctx, NULL, 0);
373
374     /* set the tabsize in pixels */
375     if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
376         av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
377         return err;
378     }
379     dtext->tabsize *= glyph->advance;
380
381 #if !HAVE_LOCALTIME_R
382     av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
383 #endif
384
385     return 0;
386 }
387
388 static int query_formats(AVFilterContext *ctx)
389 {
390     static const enum PixelFormat pix_fmts[] = {
391         PIX_FMT_ARGB,    PIX_FMT_RGBA,
392         PIX_FMT_ABGR,    PIX_FMT_BGRA,
393         PIX_FMT_RGB24,   PIX_FMT_BGR24,
394         PIX_FMT_YUV420P, PIX_FMT_YUV444P,
395         PIX_FMT_YUV422P, PIX_FMT_YUV411P,
396         PIX_FMT_YUV410P, PIX_FMT_YUV440P,
397         PIX_FMT_NONE
398     };
399
400     ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
401     return 0;
402 }
403
404 static int glyph_enu_free(void *opaque, void *elem)
405 {
406     av_free(elem);
407     return 0;
408 }
409
410 static av_cold void uninit(AVFilterContext *ctx)
411 {
412     DrawTextContext *dtext = ctx->priv;
413     int i;
414
415     av_freep(&dtext->fontfile);
416     av_freep(&dtext->text);
417     av_freep(&dtext->expanded_text);
418     av_freep(&dtext->fontcolor_string);
419     av_freep(&dtext->boxcolor_string);
420     av_freep(&dtext->positions);
421     av_freep(&dtext->shadowcolor_string);
422     av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
423     av_tree_destroy(dtext->glyphs);
424     dtext->glyphs = 0;
425     FT_Done_Face(dtext->face);
426     FT_Done_FreeType(dtext->library);
427
428     for (i = 0; i < 4; i++) {
429         av_freep(&dtext->box_line[i]);
430         dtext->pixel_step[i] = 0;
431     }
432
433 }
434
435 static inline int is_newline(uint32_t c)
436 {
437     return c == '\n' || c == '\r' || c == '\f' || c == '\v';
438 }
439
440 static int dtext_prepare_text(AVFilterContext *ctx)
441 {
442     DrawTextContext *dtext = ctx->priv;
443     uint32_t code = 0, prev_code = 0;
444     int x = 0, y = 0, i = 0, ret;
445     int text_height, baseline;
446     char *text = dtext->text;
447     uint8_t *p;
448     int str_w = 0, len;
449     int y_min = 32000, y_max = -32000;
450     FT_Vector delta;
451     Glyph *glyph = NULL, *prev_glyph = NULL;
452     Glyph dummy = { 0 };
453     int width  = ctx->inputs[0]->w;
454     int height = ctx->inputs[0]->h;
455
456 #if HAVE_LOCALTIME_R
457     time_t now = time(0);
458     struct tm ltime;
459     uint8_t *buf = dtext->expanded_text;
460     int buf_size = dtext->expanded_text_size;
461
462     if (!buf)
463         buf_size = 2*strlen(dtext->text)+1;
464
465     localtime_r(&now, &ltime);
466
467     while ((buf = av_realloc(buf, buf_size))) {
468         *buf = 1;
469         if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
470             break;
471         buf_size *= 2;
472     }
473
474     if (!buf)
475         return AVERROR(ENOMEM);
476     text = dtext->expanded_text = buf;
477     dtext->expanded_text_size = buf_size;
478 #endif
479
480     if ((len = strlen(text)) > dtext->nb_positions) {
481         FT_Vector *p = av_realloc(dtext->positions,
482                                   len * sizeof(*dtext->positions));
483         if (!p) {
484             av_freep(dtext->positions);
485             dtext->nb_positions = 0;
486             return AVERROR(ENOMEM);
487         } else {
488             dtext->positions = p;
489             dtext->nb_positions = len;
490         }
491     }
492
493     /* load and cache glyphs */
494     for (i = 0, p = text; *p; i++) {
495         GET_UTF8(code, *p++, continue;);
496
497         /* get glyph */
498         dummy.code = code;
499         glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
500         if (!glyph) {
501             ret = load_glyph(ctx, &glyph, code);
502             if (ret)
503                 return ret;
504         }
505
506         y_min = FFMIN(glyph->bbox.yMin, y_min);
507         y_max = FFMAX(glyph->bbox.yMax, y_max);
508     }
509     text_height = y_max - y_min;
510     baseline    = y_max;
511
512     /* compute and save position for each glyph */
513     glyph = NULL;
514     for (i = 0, p = text; *p; i++) {
515         GET_UTF8(code, *p++, continue;);
516
517         /* skip the \n in the sequence \r\n */
518         if (prev_code == '\r' && code == '\n')
519             continue;
520
521         prev_code = code;
522         if (is_newline(code)) {
523             str_w = FFMAX(str_w, x - dtext->x);
524             y += text_height;
525             x = 0;
526             continue;
527         }
528
529         /* get glyph */
530         prev_glyph = glyph;
531         dummy.code = code;
532         glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
533
534         /* kerning */
535         if (dtext->use_kerning && prev_glyph && glyph->code) {
536             FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
537                            ft_kerning_default, &delta);
538             x += delta.x >> 6;
539         }
540
541         if (x + glyph->bbox.xMax >= width) {
542             str_w = FFMAX(str_w, x);
543             y += text_height;
544             x = 0;
545         }
546
547         /* save position */
548         dtext->positions[i].x = x + glyph->bitmap_left;
549         dtext->positions[i].y = y - glyph->bitmap_top + baseline;
550         if (code == '\t') x  = (x / dtext->tabsize + 1)*dtext->tabsize;
551         else              x += glyph->advance;
552     }
553
554     str_w = FFMIN(width - 1, FFMAX(str_w, x));
555     y     = FFMIN(y + text_height, height - 1);
556
557     dtext->w = str_w;
558     dtext->var_values[VAR_TEXT_W] = dtext->var_values[VAR_TW] = dtext->w;
559     dtext->h = y;
560     dtext->var_values[VAR_TEXT_H] = dtext->var_values[VAR_TH] = dtext->h;
561
562     return 0;
563 }
564
565
566 static int config_input(AVFilterLink *inlink)
567 {
568     AVFilterContext *ctx  = inlink->dst;
569     DrawTextContext *dtext = ctx->priv;
570     const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
571     int ret;
572
573     dtext->hsub = pix_desc->log2_chroma_w;
574     dtext->vsub = pix_desc->log2_chroma_h;
575
576     dtext->var_values[VAR_E  ] = M_E;
577     dtext->var_values[VAR_PHI] = M_PHI;
578     dtext->var_values[VAR_PI ] = M_PI;
579
580     dtext->var_values[VAR_MAIN_W] =
581         dtext->var_values[VAR_MW] = ctx->inputs[0]->w;
582     dtext->var_values[VAR_MAIN_H] =
583         dtext->var_values[VAR_MH] = ctx->inputs[0]->h;
584
585     dtext->var_values[VAR_X] = 0;
586     dtext->var_values[VAR_Y] = 0;
587     dtext->var_values[VAR_N] = 0;
588     dtext->var_values[VAR_T] = NAN;
589
590     av_lfg_init(&dtext->prng, av_get_random_seed());
591
592     if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
593                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
594         (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
595                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
596         (ret = av_expr_parse(&dtext->d_pexpr, dtext->d_expr, var_names,
597                              NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
598         return AVERROR(EINVAL);
599
600     if ((ret =
601          ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
602                                  inlink->w, dtext->boxcolor,
603                                  inlink->format, dtext->boxcolor_rgba,
604                                  &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
605         return ret;
606
607     if (!dtext->is_packed_rgb) {
608         uint8_t *rgba = dtext->fontcolor_rgba;
609         dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
610         dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
611         dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
612         dtext->fontcolor[3] = rgba[3];
613         rgba = dtext->shadowcolor_rgba;
614         dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
615         dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
616         dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
617         dtext->shadowcolor[3] = rgba[3];
618     }
619
620     dtext->draw = 1;
621
622     return dtext_prepare_text(ctx);
623 }
624
625 #define GET_BITMAP_VAL(r, c)                                            \
626     bitmap->pixel_mode == FT_PIXEL_MODE_MONO ?                          \
627         (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
628          bitmap->buffer[(r) * bitmap->pitch +  (c)]
629
630 #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) {           \
631     luma_pos    = ((x)          ) + ((y)          ) * picref->linesize[0]; \
632     alpha = yuva_color[3] * (val) * 129;                               \
633     picref->data[0][luma_pos]    = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos]   ) >> 23; \
634     if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
635         chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
636         chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
637         picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
638         picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
639     }\
640 }
641
642 static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
643                                  unsigned int y, unsigned int width, unsigned int height,
644                                  const uint8_t yuva_color[4], int hsub, int vsub)
645 {
646     int r, c, alpha;
647     unsigned int luma_pos, chroma_pos1, chroma_pos2;
648     uint8_t src_val;
649
650     for (r = 0; r < bitmap->rows && r+y < height; r++) {
651         for (c = 0; c < bitmap->width && c+x < width; c++) {
652             /* get intensity value in the glyph bitmap (source) */
653             src_val = GET_BITMAP_VAL(r, c);
654             if (!src_val)
655                 continue;
656
657             SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
658         }
659     }
660
661     return 0;
662 }
663
664 #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
665     p   = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
666     alpha = rgba_color[3] * (val) * 129;                              \
667     *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
668     *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
669     *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
670 }
671
672 static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
673                                  unsigned int x, unsigned int y,
674                                  unsigned int width, unsigned int height, int pixel_step,
675                                  const uint8_t rgba_color[4], const uint8_t rgba_map[4])
676 {
677     int r, c, alpha;
678     uint8_t *p;
679     uint8_t src_val;
680
681     for (r = 0; r < bitmap->rows && r+y < height; r++) {
682         for (c = 0; c < bitmap->width && c+x < width; c++) {
683             /* get intensity value in the glyph bitmap (source) */
684             src_val = GET_BITMAP_VAL(r, c);
685             if (!src_val)
686                 continue;
687
688             SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
689                           rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
690         }
691     }
692
693     return 0;
694 }
695
696 static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
697                            unsigned int width, unsigned int height,
698                            uint8_t *line[4], int pixel_step[4], uint8_t color[4],
699                            int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
700 {
701     int i, j, alpha;
702
703     if (color[3] != 0xFF) {
704         if (is_rgba_packed) {
705             uint8_t *p;
706             for (j = 0; j < height; j++)
707                 for (i = 0; i < width; i++)
708                     SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
709                                   rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
710         } else {
711             unsigned int luma_pos, chroma_pos1, chroma_pos2;
712             for (j = 0; j < height; j++)
713                 for (i = 0; i < width; i++)
714                     SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
715         }
716     } else {
717         ff_draw_rectangle(picref->data, picref->linesize,
718                           line, pixel_step, hsub, vsub,
719                           x, y, width, height);
720     }
721 }
722
723 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
724                        int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
725 {
726     char *text = HAVE_LOCALTIME_R ? dtext->expanded_text : dtext->text;
727     uint32_t code = 0;
728     int i;
729     uint8_t *p;
730     Glyph *glyph = NULL;
731
732     for (i = 0, p = text; *p; i++) {
733         Glyph dummy = { 0 };
734         GET_UTF8(code, *p++, continue;);
735
736         /* skip new line chars, just go to new line */
737         if (code == '\n' || code == '\r' || code == '\t')
738             continue;
739
740         dummy.code = code;
741         glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
742
743         if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
744             glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
745             return AVERROR(EINVAL);
746
747         if (dtext->is_packed_rgb) {
748             draw_glyph_rgb(picref, &glyph->bitmap,
749                            dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
750                            dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
751         } else {
752             draw_glyph_yuv(picref, &glyph->bitmap,
753                            dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
754                            yuvcolor, dtext->hsub, dtext->vsub);
755         }
756     }
757
758     return 0;
759 }
760
761 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
762                      int width, int height)
763 {
764     DrawTextContext *dtext = ctx->priv;
765     int ret;
766
767     /* draw box */
768     if (dtext->draw_box)
769         drawbox(picref, dtext->x, dtext->y, dtext->w, dtext->h,
770                 dtext->box_line, dtext->pixel_step, dtext->boxcolor,
771                 dtext->hsub, dtext->vsub, dtext->is_packed_rgb,
772                 dtext->rgba_map);
773
774     if (dtext->shadowx || dtext->shadowy) {
775         if ((ret = draw_glyphs(dtext, picref, width, height,
776                                dtext->shadowcolor_rgba,
777                                dtext->shadowcolor,
778                                dtext->x + dtext->shadowx,
779                                dtext->y + dtext->shadowy)) < 0)
780             return ret;
781     }
782
783     if ((ret = draw_glyphs(dtext, picref, width, height,
784                            dtext->fontcolor_rgba,
785                            dtext->fontcolor,
786                            dtext->x,
787                            dtext->y)) < 0)
788         return ret;
789
790     return 0;
791 }
792
793 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
794
795 static inline int normalize_double(int *n, double d)
796 {
797     int ret = 0;
798
799     if (isnan(d)) {
800         ret = AVERROR(EINVAL);
801     } else if (d > INT_MAX || d < INT_MIN) {
802         *n = d > INT_MAX ? INT_MAX : INT_MIN;
803         ret = AVERROR(EINVAL);
804     } else
805         *n = round(d);
806
807     return ret;
808 }
809
810 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
811 {
812     AVFilterContext *ctx = inlink->dst;
813     DrawTextContext *dtext = ctx->priv;
814     int fail = 0;
815
816     if (dtext_prepare_text(ctx) < 0) {
817         av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
818         fail = 1;
819     }
820
821     dtext->var_values[VAR_T] = inpicref->pts == AV_NOPTS_VALUE ?
822         NAN : inpicref->pts * av_q2d(inlink->time_base);
823     dtext->var_values[VAR_X] =
824         av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
825     dtext->var_values[VAR_Y] =
826         av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
827     dtext->var_values[VAR_X] =
828         av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
829
830     dtext->draw = fail ? 0 :
831         av_expr_eval(dtext->d_pexpr, dtext->var_values, &dtext->prng);
832
833     normalize_double(&dtext->x, dtext->var_values[VAR_X]);
834     normalize_double(&dtext->y, dtext->var_values[VAR_Y]);
835
836     if (dtext->fix_bounds) {
837         if (dtext->x < 0) dtext->x = 0;
838         if (dtext->y < 0) dtext->y = 0;
839         if ((unsigned)dtext->x + (unsigned)dtext->w > inlink->w)
840             dtext->x = inlink->w - dtext->w;
841         if ((unsigned)dtext->y + (unsigned)dtext->h > inlink->h)
842             dtext->y = inlink->h - dtext->h;
843     }
844
845     dtext->x &= ~((1 << dtext->hsub) - 1);
846     dtext->y &= ~((1 << dtext->vsub) - 1);
847
848     av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
849             (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
850             dtext->x, dtext->y, dtext->x+dtext->w, dtext->y+dtext->h);
851
852     avfilter_start_frame(inlink->dst->outputs[0], inpicref);
853 }
854
855 static void end_frame(AVFilterLink *inlink)
856 {
857     AVFilterLink *outlink = inlink->dst->outputs[0];
858     AVFilterBufferRef *picref = inlink->cur_buf;
859     DrawTextContext *dtext = inlink->dst->priv;
860
861     if (dtext->draw)
862         draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
863
864     dtext->var_values[VAR_N] += 1.0;
865
866     avfilter_draw_slice(outlink, 0, picref->video->h, 1);
867     avfilter_end_frame(outlink);
868 }
869
870 AVFilter avfilter_vf_drawtext = {
871     .name          = "drawtext",
872     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
873     .priv_size     = sizeof(DrawTextContext),
874     .init          = init,
875     .uninit        = uninit,
876     .query_formats = query_formats,
877
878     .inputs    = (AVFilterPad[]) {{ .name             = "default",
879                                     .type             = AVMEDIA_TYPE_VIDEO,
880                                     .get_video_buffer = ff_null_get_video_buffer,
881                                     .start_frame      = start_frame,
882                                     .draw_slice       = null_draw_slice,
883                                     .end_frame        = end_frame,
884                                     .config_props     = config_input,
885                                     .min_perms        = AV_PERM_WRITE |
886                                                         AV_PERM_READ,
887                                     .rej_perms        = AV_PERM_PRESERVE },
888                                   { .name = NULL}},
889     .outputs   = (AVFilterPad[]) {{ .name             = "default",
890                                     .type             = AVMEDIA_TYPE_VIDEO, },
891                                   { .name = NULL}},
892 };