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