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