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