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