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