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