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