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