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