]> git.sesse.net Git - ffmpeg/blob - libavfilter/vf_drawtext.c
mpegvideo: make FF_DEBUG_DCT_COEFF output coeffs via av_log() instead of just via...
[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 FFmpeg 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/opt.h"
35 #include "libavutil/parseutils.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavutil/tree.h"
38 #include "avfilter.h"
39 #include "drawutils.h"
40
41 #undef time
42
43 #include <ft2build.h>
44 #include <freetype/config/ftheader.h>
45 #include FT_FREETYPE_H
46 #include FT_GLYPH_H
47
48 typedef struct {
49     const AVClass *class;
50     uint8_t *fontfile;              ///< font to be used
51     uint8_t *text;                  ///< text to be drawn
52     uint8_t *text_priv;             ///< used to detect whether text changed
53     int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
54     FT_Vector *positions;           ///< positions for each element in the text
55     char *textfile;                 ///< file with text to be drawn
56     unsigned int x;                 ///< x position to start drawing text
57     unsigned int y;                 ///< y position to start drawing text
58     int shadowx, shadowy;
59     unsigned int fontsize;          ///< font size to use
60     char *fontcolor_string;         ///< font color as string
61     char *boxcolor_string;          ///< box color as string
62     char *shadowcolor_string;       ///< shadow color as string
63     uint8_t fontcolor[4];           ///< foreground color
64     uint8_t boxcolor[4];            ///< background color
65     uint8_t shadowcolor[4];         ///< shadow color
66     uint8_t fontcolor_rgba[4];      ///< foreground color in RGBA
67     uint8_t boxcolor_rgba[4];       ///< background color in RGBA
68     uint8_t shadowcolor_rgba[4];    ///< shadow color in RGBA
69
70     short int draw_box;             ///< draw box around text - true or false
71     int use_kerning;                ///< font kerning is used - true/false
72     int tabsize;                    ///< tab size
73
74     FT_Library library;             ///< freetype font library handle
75     FT_Face face;                   ///< freetype font face handle
76     struct AVTreeNode *glyphs;      ///< rendered glyphs, stored using the UTF-32 char code
77     int hsub, vsub;                 ///< chroma subsampling values
78     int is_packed_rgb;
79     int pixel_step[4];              ///< distance in bytes between the component of each pixel
80     uint8_t rgba_map[4];            ///< map RGBA offsets to the positions in the packed RGBA format
81     uint8_t *box_line[4];           ///< line used for filling the box background
82 } DrawTextContext;
83
84 #define OFFSET(x) offsetof(DrawTextContext, x)
85
86 static const AVOption drawtext_options[]= {
87 {"fontfile", "set font file",        OFFSET(fontfile),         FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
88 {"text",     "set text",             OFFSET(text),             FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
89 {"textfile", "set text file",        OFFSET(textfile),         FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
90 {"fontcolor","set foreground color", OFFSET(fontcolor_string), FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
91 {"boxcolor", "set box color",        OFFSET(boxcolor_string),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
92 {"shadowcolor", "set shadow color",  OFFSET(shadowcolor_string),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
93 {"box",      "set box",              OFFSET(draw_box),         FF_OPT_TYPE_INT,    0,         0,        1 },
94 {"fontsize", "set font size",        OFFSET(fontsize),         FF_OPT_TYPE_INT,   16,         1,       72 },
95 {"x",        "set x",                OFFSET(x),                FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
96 {"y",        "set y",                OFFSET(y),                FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
97 {"shadowx",  "set x",                OFFSET(shadowx),          FF_OPT_TYPE_INT,    0,   INT_MIN,  INT_MAX },
98 {"shadowy",  "set y",                OFFSET(shadowy),          FF_OPT_TYPE_INT,    0,   INT_MIN,  INT_MAX },
99 {"tabsize",  "set tab size",         OFFSET(tabsize),          FF_OPT_TYPE_INT,    4,         0,  INT_MAX },
100
101 /* FT_LOAD_* flags */
102 {"ft_load_flags", "set font loading flags for libfreetype",   OFFSET(ft_load_flags),  FF_OPT_TYPE_FLAGS,  FT_LOAD_DEFAULT|FT_LOAD_RENDER, 0, INT_MAX, 0, "ft_load_flags" },
103 {"default",                     "set default",                     0, FF_OPT_TYPE_CONST, FT_LOAD_DEFAULT,                     INT_MIN, INT_MAX, 0, "ft_load_flags" },
104 {"no_scale",                    "set no_scale",                    0, FF_OPT_TYPE_CONST, FT_LOAD_NO_SCALE,                    INT_MIN, INT_MAX, 0, "ft_load_flags" },
105 {"no_hinting",                  "set no_hinting",                  0, FF_OPT_TYPE_CONST, FT_LOAD_NO_HINTING,                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
106 {"render",                      "set render",                      0, FF_OPT_TYPE_CONST, FT_LOAD_RENDER,                      INT_MIN, INT_MAX, 0, "ft_load_flags" },
107 {"no_bitmap",                   "set no_bitmap",                   0, FF_OPT_TYPE_CONST, FT_LOAD_NO_BITMAP,                   INT_MIN, INT_MAX, 0, "ft_load_flags" },
108 {"vertical_layout",             "set vertical_layout",             0, FF_OPT_TYPE_CONST, FT_LOAD_VERTICAL_LAYOUT,             INT_MIN, INT_MAX, 0, "ft_load_flags" },
109 {"force_autohint",              "set force_autohint",              0, FF_OPT_TYPE_CONST, FT_LOAD_FORCE_AUTOHINT,              INT_MIN, INT_MAX, 0, "ft_load_flags" },
110 {"crop_bitmap",                 "set crop_bitmap",                 0, FF_OPT_TYPE_CONST, FT_LOAD_CROP_BITMAP,                 INT_MIN, INT_MAX, 0, "ft_load_flags" },
111 {"pedantic",                    "set pedantic",                    0, FF_OPT_TYPE_CONST, FT_LOAD_PEDANTIC,                    INT_MIN, INT_MAX, 0, "ft_load_flags" },
112 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH, INT_MIN, INT_MAX, 0, "ft_load_flags" },
113 {"no_recurse",                  "set no_recurse",                  0, FF_OPT_TYPE_CONST, FT_LOAD_NO_RECURSE,                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
114 {"ignore_transform",            "set ignore_transform",            0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_TRANSFORM,            INT_MIN, INT_MAX, 0, "ft_load_flags" },
115 {"monochrome",                  "set monochrome",                  0, FF_OPT_TYPE_CONST, FT_LOAD_MONOCHROME,                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
116 {"linear_design",               "set linear_design",               0, FF_OPT_TYPE_CONST, FT_LOAD_LINEAR_DESIGN,               INT_MIN, INT_MAX, 0, "ft_load_flags" },
117 {"no_autohint",                 "set no_autohint",                 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_AUTOHINT,                 INT_MIN, INT_MAX, 0, "ft_load_flags" },
118 {NULL},
119 };
120
121 static const char *drawtext_get_name(void *ctx)
122 {
123     return "drawtext";
124 }
125
126 static const AVClass drawtext_class = {
127     "DrawTextContext",
128     drawtext_get_name,
129     drawtext_options
130 };
131
132 #undef __FTERRORS_H__
133 #define FT_ERROR_START_LIST {
134 #define FT_ERRORDEF(e, v, s) { (e), (s) },
135 #define FT_ERROR_END_LIST { 0, NULL } };
136
137 struct ft_error
138 {
139     int err;
140     const char *err_msg;
141 } static ft_errors[] =
142 #include FT_ERRORS_H
143
144 #define FT_ERRMSG(e) ft_errors[e].err_msg
145
146 typedef struct {
147     FT_Glyph *glyph;
148     uint32_t code;
149     FT_Bitmap bitmap; ///< array holding bitmaps of font
150     FT_BBox bbox;
151     int advance;
152     int bitmap_left;
153     int bitmap_top;
154 } Glyph;
155
156 static int glyph_cmp(void *key, const void *b)
157 {
158     const Glyph *a = key, *bb = b;
159     int64_t diff = (int64_t)a->code - (int64_t)bb->code;
160     return diff > 0 ? 1 : diff < 0 ? -1 : 0;
161 }
162
163 /**
164  * Load glyphs corresponding to the UTF-32 codepoint code.
165  */
166 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
167 {
168     DrawTextContext *dtext = ctx->priv;
169     Glyph *glyph;
170     struct AVTreeNode *node = NULL;
171     int ret;
172
173     /* load glyph into dtext->face->glyph */
174     if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
175         return AVERROR(EINVAL);
176
177     /* save glyph */
178     if (!(glyph = av_mallocz(sizeof(*glyph))) ||
179         !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
180         ret = AVERROR(ENOMEM);
181         goto error;
182     }
183     glyph->code  = code;
184
185     if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
186         ret = AVERROR(EINVAL);
187         goto error;
188     }
189
190     glyph->bitmap      = dtext->face->glyph->bitmap;
191     glyph->bitmap_left = dtext->face->glyph->bitmap_left;
192     glyph->bitmap_top  = dtext->face->glyph->bitmap_top;
193     glyph->advance     = dtext->face->glyph->advance.x >> 6;
194
195     /* measure text height to calculate text_height (or the maximum text height) */
196     FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
197
198     /* cache the newly created glyph */
199     if (!(node = av_mallocz(av_tree_node_size))) {
200         ret = AVERROR(ENOMEM);
201         goto error;
202     }
203     av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
204
205     if (glyph_ptr)
206         *glyph_ptr = glyph;
207     return 0;
208
209 error:
210     if (glyph)
211         av_freep(&glyph->glyph);
212     av_freep(&glyph);
213     av_freep(&node);
214     return ret;
215 }
216
217 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
218 {
219     int err;
220     DrawTextContext *dtext = ctx->priv;
221     Glyph *glyph;
222
223     dtext->class = &drawtext_class;
224     av_opt_set_defaults2(dtext, 0, 0);
225     dtext->fontcolor_string = av_strdup("black");
226     dtext->boxcolor_string = av_strdup("white");
227     dtext->shadowcolor_string = av_strdup("black");
228
229     if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
230         av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
231         return err;
232     }
233
234     if (!dtext->fontfile) {
235         av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
236         return AVERROR(EINVAL);
237     }
238
239     if (dtext->textfile) {
240         uint8_t *textbuf;
241         size_t textbuf_size;
242
243         if (dtext->text) {
244             av_log(ctx, AV_LOG_ERROR,
245                    "Both text and text file provided. Please provide only one\n");
246             return AVERROR(EINVAL);
247         }
248         if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
249             av_log(ctx, AV_LOG_ERROR,
250                    "The text file '%s' could not be read or is empty\n",
251                    dtext->textfile);
252             return err;
253         }
254
255         if (!(dtext->text = av_malloc(textbuf_size+1)))
256             return AVERROR(ENOMEM);
257         memcpy(dtext->text, textbuf, textbuf_size);
258         dtext->text[textbuf_size] = 0;
259         av_file_unmap(textbuf, textbuf_size);
260     }
261
262     if (!dtext->text) {
263         av_log(ctx, AV_LOG_ERROR,
264                "Either text or a valid file must be provided\n");
265         return AVERROR(EINVAL);
266     }
267
268     if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
269         av_log(ctx, AV_LOG_ERROR,
270                "Invalid font color '%s'\n", dtext->fontcolor_string);
271         return err;
272     }
273
274     if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
275         av_log(ctx, AV_LOG_ERROR,
276                "Invalid box color '%s'\n", dtext->boxcolor_string);
277         return err;
278     }
279
280     if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
281         av_log(ctx, AV_LOG_ERROR,
282                "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
283         return err;
284     }
285
286     if ((err = FT_Init_FreeType(&(dtext->library)))) {
287         av_log(ctx, AV_LOG_ERROR,
288                "Could not load FreeType: %s\n", FT_ERRMSG(err));
289         return AVERROR(EINVAL);
290     }
291
292     /* load the face, and set up the encoding, which is by default UTF-8 */
293     if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
294         av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
295                dtext->fontfile, FT_ERRMSG(err));
296         return AVERROR(EINVAL);
297     }
298     if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
299         av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
300                dtext->fontsize, FT_ERRMSG(err));
301         return AVERROR(EINVAL);
302     }
303
304     dtext->use_kerning = FT_HAS_KERNING(dtext->face);
305
306     /* load the fallback glyph with code 0 */
307     load_glyph(ctx, NULL, 0);
308
309     /* set the tabsize in pixels */
310     if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
311         av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
312         return err;
313     }
314     dtext->tabsize *= glyph->advance;
315
316 #if !HAVE_LOCALTIME_R
317     av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
318 #endif
319
320     return 0;
321 }
322
323 static int query_formats(AVFilterContext *ctx)
324 {
325     static const enum PixelFormat pix_fmts[] = {
326         PIX_FMT_ARGB,    PIX_FMT_RGBA,
327         PIX_FMT_ABGR,    PIX_FMT_BGRA,
328         PIX_FMT_RGB24,   PIX_FMT_BGR24,
329         PIX_FMT_YUV420P, PIX_FMT_YUV444P,
330         PIX_FMT_YUV422P, PIX_FMT_YUV411P,
331         PIX_FMT_YUV410P, PIX_FMT_YUV440P,
332         PIX_FMT_NONE
333     };
334
335     avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
336     return 0;
337 }
338
339 static int glyph_enu_free(void *opaque, void *elem)
340 {
341     av_free(elem);
342     return 0;
343 }
344
345 static av_cold void uninit(AVFilterContext *ctx)
346 {
347     DrawTextContext *dtext = ctx->priv;
348     int i;
349
350     av_freep(&dtext->fontfile);
351     av_freep(&dtext->text);
352     av_freep(&dtext->fontcolor_string);
353     av_freep(&dtext->boxcolor_string);
354     av_freep(&dtext->positions);
355     av_freep(&dtext->shadowcolor_string);
356     av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
357     av_tree_destroy(dtext->glyphs);
358     dtext->glyphs = 0;
359     FT_Done_Face(dtext->face);
360     FT_Done_FreeType(dtext->library);
361
362     for (i = 0; i < 4; i++) {
363         av_freep(&dtext->box_line[i]);
364         dtext->pixel_step[i] = 0;
365     }
366
367 }
368
369 static int config_input(AVFilterLink *inlink)
370 {
371     DrawTextContext *dtext = inlink->dst->priv;
372     const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
373     int ret;
374
375     dtext->hsub = pix_desc->log2_chroma_w;
376     dtext->vsub = pix_desc->log2_chroma_h;
377
378     if ((ret =
379          ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
380                                  inlink->w, dtext->boxcolor,
381                                  inlink->format, dtext->boxcolor_rgba,
382                                  &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
383         return ret;
384
385     if (!dtext->is_packed_rgb) {
386         uint8_t *rgba = dtext->fontcolor_rgba;
387         dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
388         dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
389         dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
390         dtext->fontcolor[3] = rgba[3];
391         rgba = dtext->shadowcolor_rgba;
392         dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
393         dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
394         dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
395         dtext->shadowcolor[3] = rgba[3];
396     }
397
398     return 0;
399 }
400
401 #define GET_BITMAP_VAL(r, c)                                            \
402     bitmap->pixel_mode == FT_PIXEL_MODE_MONO ?                          \
403         (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
404          bitmap->buffer[(r) * bitmap->pitch +  (c)]
405
406 #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) {           \
407     luma_pos    = ((x)          ) + ((y)          ) * picref->linesize[0]; \
408     alpha = yuva_color[3] * (val) * 129;                               \
409     picref->data[0][luma_pos]    = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos]   ) >> 23; \
410     if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
411         chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
412         chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
413         picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
414         picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
415     }\
416 }
417
418 static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
419                                  unsigned int y, unsigned int width, unsigned int height,
420                                  const uint8_t yuva_color[4], int hsub, int vsub)
421 {
422     int r, c, alpha;
423     unsigned int luma_pos, chroma_pos1, chroma_pos2;
424     uint8_t src_val, dst_pixel[4];
425
426     for (r = 0; r < bitmap->rows && r+y < height; r++) {
427         for (c = 0; c < bitmap->width && c+x < width; c++) {
428             /* get pixel in the picref (destination) */
429             dst_pixel[0] = picref->data[0][  c+x           +  (y+r)          * picref->linesize[0]];
430             dst_pixel[1] = picref->data[1][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[1]];
431             dst_pixel[2] = picref->data[2][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[2]];
432
433             /* get intensity value in the glyph bitmap (source) */
434             src_val = GET_BITMAP_VAL(r, c);
435             if (!src_val)
436                 continue;
437
438             SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
439         }
440     }
441
442     return 0;
443 }
444
445 #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
446     p   = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
447     alpha = rgba_color[3] * (val) * 129;                              \
448     *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
449     *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
450     *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
451 }
452
453 static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
454                                  unsigned int x, unsigned int y,
455                                  unsigned int width, unsigned int height, int pixel_step,
456                                  const uint8_t rgba_color[4], const uint8_t rgba_map[4])
457 {
458     int r, c, alpha;
459     uint8_t *p;
460     uint8_t src_val, dst_pixel[4];
461
462     for (r = 0; r < bitmap->rows && r+y < height; r++) {
463         for (c = 0; c < bitmap->width && c+x < width; c++) {
464             /* get pixel in the picref (destination) */
465             dst_pixel[0] = picref->data[0][(c+x + rgba_map[0]) * pixel_step +
466                                            (y+r) * picref->linesize[0]];
467             dst_pixel[1] = picref->data[0][(c+x + rgba_map[1]) * pixel_step +
468                                            (y+r) * picref->linesize[0]];
469             dst_pixel[2] = picref->data[0][(c+x + rgba_map[2]) * pixel_step +
470                                            (y+r) * picref->linesize[0]];
471
472             /* get intensity value in the glyph bitmap (source) */
473             src_val = GET_BITMAP_VAL(r, c);
474             if (!src_val)
475                 continue;
476
477             SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
478                           rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
479         }
480     }
481
482     return 0;
483 }
484
485 static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
486                            unsigned int width, unsigned int height,
487                            uint8_t *line[4], int pixel_step[4], uint8_t color[4],
488                            int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
489 {
490     int i, j, alpha;
491
492     if (color[3] != 0xFF) {
493         if (is_rgba_packed) {
494             uint8_t *p;
495             for (j = 0; j < height; j++)
496                 for (i = 0; i < width; i++)
497                     SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
498                                   rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
499         } else {
500             unsigned int luma_pos, chroma_pos1, chroma_pos2;
501             for (j = 0; j < height; j++)
502                 for (i = 0; i < width; i++)
503                     SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
504         }
505     } else {
506         ff_draw_rectangle(picref->data, picref->linesize,
507                           line, pixel_step, hsub, vsub,
508                           x, y, width, height);
509     }
510 }
511
512 static inline int is_newline(uint32_t c)
513 {
514     return (c == '\n' || c == '\r' || c == '\f' || c == '\v');
515 }
516
517 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
518                        int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
519 {
520     char *text = dtext->text;
521     uint32_t code = 0;
522     int i;
523     uint8_t *p;
524     Glyph *glyph = NULL;
525
526     for (i = 0, p = text; *p; i++) {
527         Glyph dummy = { 0 };
528         GET_UTF8(code, *p++, continue;);
529
530         /* skip new line chars, just go to new line */
531         if (code == '\n' || code == '\r' || code == '\t')
532             continue;
533
534         dummy.code = code;
535         glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
536
537         if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
538             glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
539             return AVERROR(EINVAL);
540
541         if (dtext->is_packed_rgb) {
542             draw_glyph_rgb(picref, &glyph->bitmap,
543                            dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
544                            dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
545         } else {
546             draw_glyph_yuv(picref, &glyph->bitmap,
547                            dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
548                            yuvcolor, dtext->hsub, dtext->vsub);
549         }
550     }
551
552     return 0;
553 }
554
555 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
556                      int width, int height)
557 {
558     DrawTextContext *dtext = ctx->priv;
559     uint32_t code = 0, prev_code = 0;
560     int x = 0, y = 0, i = 0, ret;
561     int text_height, baseline;
562     uint8_t *p;
563     int str_w = 0;
564     int y_min = 32000, y_max = -32000;
565     FT_Vector delta;
566     Glyph *glyph = NULL, *prev_glyph = NULL;
567     Glyph dummy = { 0 };
568
569     if (dtext->text != dtext->text_priv) {
570 #if HAVE_LOCALTIME_R
571         time_t now = time(0);
572         struct tm ltime;
573         uint8_t *buf = NULL;
574         int     buflen = 2*strlen(dtext->text) + 1, len;
575
576         localtime_r(&now, &ltime);
577
578         while ((buf = av_realloc(buf, buflen))) {
579             *buf = 1;
580             if ((len = strftime(buf, buflen, dtext->text, &ltime)) != 0 || *buf == 0)
581                 break;
582             buflen *= 2;
583         }
584         if (!buf)
585             return AVERROR(ENOMEM);
586         av_freep(&dtext->text);
587         dtext->text = dtext->text_priv = buf;
588 #else
589         dtext->text_priv = dtext->text;
590 #endif
591         if (!(dtext->positions = av_realloc(dtext->positions,
592                                             strlen(dtext->text)*sizeof(*dtext->positions))))
593             return AVERROR(ENOMEM);
594     }
595
596     x = dtext->x;
597     y = dtext->y;
598
599     /* load and cache glyphs */
600     for (i = 0, p = dtext->text; *p; i++) {
601         GET_UTF8(code, *p++, continue;);
602
603         /* get glyph */
604         dummy.code = code;
605         glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
606         if (!glyph)
607             load_glyph(ctx, &glyph, code);
608
609         y_min = FFMIN(glyph->bbox.yMin, y_min);
610         y_max = FFMAX(glyph->bbox.yMax, y_max);
611     }
612     text_height = y_max - y_min;
613     baseline    = y_max;
614
615     /* compute and save position for each glyph */
616     glyph = NULL;
617     for (i = 0, p = dtext->text; *p; i++) {
618         GET_UTF8(code, *p++, continue;);
619
620         /* skip the \n in the sequence \r\n */
621         if (prev_code == '\r' && code == '\n')
622             continue;
623
624         prev_code = code;
625         if (is_newline(code)) {
626             str_w = FFMAX(str_w, x - dtext->x);
627             y += text_height;
628             x = dtext->x;
629             continue;
630         }
631
632         /* get glyph */
633         prev_glyph = glyph;
634         dummy.code = code;
635         glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
636
637         /* kerning */
638         if (dtext->use_kerning && prev_glyph && glyph->code) {
639             FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
640                            ft_kerning_default, &delta);
641             x += delta.x >> 6;
642         }
643
644         if (x + glyph->bbox.xMax >= width) {
645             str_w = FFMAX(str_w, x - dtext->x);
646             y += text_height;
647             x = dtext->x;
648         }
649
650         /* save position */
651         dtext->positions[i].x = x + glyph->bitmap_left;
652         dtext->positions[i].y = y - glyph->bitmap_top + baseline;
653         if (code == '\t') x  = (x / dtext->tabsize + 1)*dtext->tabsize;
654         else              x += glyph->advance;
655     }
656
657     str_w = FFMIN(width - dtext->x - 1, FFMAX(str_w, x - dtext->x));
658     y     = FFMIN(y + text_height, height - 1);
659
660     /* draw box */
661     if (dtext->draw_box)
662         drawbox(picref, dtext->x, dtext->y, str_w, y-dtext->y,
663                 dtext->box_line, dtext->pixel_step, dtext->boxcolor,
664                 dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
665
666     if (dtext->shadowx || dtext->shadowy) {
667         if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor_rgba,
668                                dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
669             return ret;
670     }
671
672     if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor_rgba,
673                            dtext->fontcolor, 0, 0)) < 0)
674         return ret;
675
676     return 0;
677 }
678
679 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
680
681 static void end_frame(AVFilterLink *inlink)
682 {
683     AVFilterLink *outlink = inlink->dst->outputs[0];
684     AVFilterBufferRef *picref = inlink->cur_buf;
685
686     draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
687
688     avfilter_draw_slice(outlink, 0, picref->video->h, 1);
689     avfilter_end_frame(outlink);
690 }
691
692 AVFilter avfilter_vf_drawtext = {
693     .name          = "drawtext",
694     .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
695     .priv_size     = sizeof(DrawTextContext),
696     .init          = init,
697     .uninit        = uninit,
698     .query_formats = query_formats,
699
700     .inputs    = (AVFilterPad[]) {{ .name             = "default",
701                                     .type             = AVMEDIA_TYPE_VIDEO,
702                                     .get_video_buffer = avfilter_null_get_video_buffer,
703                                     .start_frame      = avfilter_null_start_frame,
704                                     .draw_slice       = null_draw_slice,
705                                     .end_frame        = end_frame,
706                                     .config_props     = config_input,
707                                     .min_perms        = AV_PERM_WRITE |
708                                                         AV_PERM_READ,
709                                     .rej_perms        = AV_PERM_PRESERVE },
710                                   { .name = NULL}},
711     .outputs   = (AVFilterPad[]) {{ .name             = "default",
712                                     .type             = AVMEDIA_TYPE_VIDEO, },
713                                   { .name = NULL}},
714 };