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