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