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