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