Statistics
| Branch: | Revision:

ffmpeg / libavfilter / vf_drawtext.c @ f9c61974

History | View | Annotate | Download (27.2 KB)

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
#define MAX_EXPANDED_TEXT_SIZE 2048
49

    
50
typedef struct {
51
    const AVClass *class;
52
    char *fontfile;                 ///< font to be used
53
    char *text;                     ///< text to be drawn
54
    int ft_load_flags;              ///< flags used for loading fonts, see FT_LOAD_*
55
    /** buffer containing the text expanded by strftime */
56
    char expanded_text[MAX_EXPANDED_TEXT_SIZE];
57
    /** positions for each element in the text */
58
    FT_Vector positions[MAX_EXPANDED_TEXT_SIZE];
59
    char *textfile;                 ///< file with text to be drawn
60
    unsigned int x;                 ///< x position to start drawing text
61
    unsigned int y;                 ///< y position to start drawing text
62
    int shadowx, shadowy;
63
    unsigned int fontsize;          ///< font size to use
64
    char *fontcolor_string;         ///< font color as string
65
    char *boxcolor_string;          ///< box color as string
66
    char *shadowcolor_string;       ///< shadow color as string
67
    uint8_t fontcolor[4];           ///< foreground color
68
    uint8_t boxcolor[4];            ///< background color
69
    uint8_t shadowcolor[4];         ///< shadow color
70
    uint8_t fontcolor_rgba[4];      ///< foreground color in RGBA
71
    uint8_t boxcolor_rgba[4];       ///< background color in RGBA
72
    uint8_t shadowcolor_rgba[4];    ///< shadow color in RGBA
73

    
74
    short int draw_box;             ///< draw box around text - true or false
75
    int use_kerning;                ///< font kerning is used - true/false
76
    int tabsize;                    ///< tab size
77

    
78
    FT_Library library;             ///< freetype font library handle
79
    FT_Face face;                   ///< freetype font face handle
80
    struct AVTreeNode *glyphs;      ///< rendered glyphs, stored using the UTF-32 char code
81
    int hsub, vsub;                 ///< chroma subsampling values
82
    int is_packed_rgb;
83
    int pixel_step[4];              ///< distance in bytes between the component of each pixel
84
    uint8_t rgba_map[4];            ///< map RGBA offsets to the positions in the packed RGBA format
85
    uint8_t *box_line[4];           ///< line used for filling the box background
86
} DrawTextContext;
87

    
88
#define OFFSET(x) offsetof(DrawTextContext, x)
89

    
90
static const AVOption drawtext_options[]= {
91
{"fontfile", "set font file",        OFFSET(fontfile),         FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
92
{"text",     "set text",             OFFSET(text),             FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
93
{"textfile", "set text file",        OFFSET(textfile),         FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
94
{"fontcolor","set foreground color", OFFSET(fontcolor_string), FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
95
{"boxcolor", "set box color",        OFFSET(boxcolor_string),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
96
{"shadowcolor", "set shadow color",  OFFSET(shadowcolor_string),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
97
{"box",      "set box",              OFFSET(draw_box),         FF_OPT_TYPE_INT,    0,         0,        1 },
98
{"fontsize", "set font size",        OFFSET(fontsize),         FF_OPT_TYPE_INT,   16,         1,       72 },
99
{"x",        "set x",                OFFSET(x),                FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
100
{"y",        "set y",                OFFSET(y),                FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
101
{"shadowx",  "set x",                OFFSET(shadowx),          FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
102
{"shadowy",  "set y",                OFFSET(shadowy),          FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
103
{"tabsize",  "set tab size",         OFFSET(tabsize),          FF_OPT_TYPE_INT,    4,         0,  INT_MAX },
104

    
105
/* FT_LOAD_* flags */
106
{"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" },
107
{"default",                     "set default",                     0, FF_OPT_TYPE_CONST, FT_LOAD_DEFAULT,                     INT_MIN, INT_MAX, 0, "ft_load_flags" },
108
{"no_scale",                    "set no_scale",                    0, FF_OPT_TYPE_CONST, FT_LOAD_NO_SCALE,                    INT_MIN, INT_MAX, 0, "ft_load_flags" },
109
{"no_hinting",                  "set no_hinting",                  0, FF_OPT_TYPE_CONST, FT_LOAD_NO_HINTING,                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
110
{"render",                      "set render",                      0, FF_OPT_TYPE_CONST, FT_LOAD_RENDER,                      INT_MIN, INT_MAX, 0, "ft_load_flags" },
111
{"no_bitmap",                   "set no_bitmap",                   0, FF_OPT_TYPE_CONST, FT_LOAD_NO_BITMAP,                   INT_MIN, INT_MAX, 0, "ft_load_flags" },
112
{"vertical_layout",             "set vertical_layout",             0, FF_OPT_TYPE_CONST, FT_LOAD_VERTICAL_LAYOUT,             INT_MIN, INT_MAX, 0, "ft_load_flags" },
113
{"force_autohint",              "set force_autohint",              0, FF_OPT_TYPE_CONST, FT_LOAD_FORCE_AUTOHINT,              INT_MIN, INT_MAX, 0, "ft_load_flags" },
114
{"crop_bitmap",                 "set crop_bitmap",                 0, FF_OPT_TYPE_CONST, FT_LOAD_CROP_BITMAP,                 INT_MIN, INT_MAX, 0, "ft_load_flags" },
115
{"pedantic",                    "set pedantic",                    0, FF_OPT_TYPE_CONST, FT_LOAD_PEDANTIC,                    INT_MIN, INT_MAX, 0, "ft_load_flags" },
116
{"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" },
117
{"no_recurse",                  "set no_recurse",                  0, FF_OPT_TYPE_CONST, FT_LOAD_NO_RECURSE,                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
118
{"ignore_transform",            "set ignore_transform",            0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_TRANSFORM,            INT_MIN, INT_MAX, 0, "ft_load_flags" },
119
{"monochrome",                  "set monochrome",                  0, FF_OPT_TYPE_CONST, FT_LOAD_MONOCHROME,                  INT_MIN, INT_MAX, 0, "ft_load_flags" },
120
{"linear_design",               "set linear_design",               0, FF_OPT_TYPE_CONST, FT_LOAD_LINEAR_DESIGN,               INT_MIN, INT_MAX, 0, "ft_load_flags" },
121
{"no_autohint",                 "set no_autohint",                 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_AUTOHINT,                 INT_MIN, INT_MAX, 0, "ft_load_flags" },
122
{NULL},
123
};
124

    
125
static const char *drawtext_get_name(void *ctx)
126
{
127
    return "drawtext";
128
}
129

    
130
static const AVClass drawtext_class = {
131
    "DrawTextContext",
132
    drawtext_get_name,
133
    drawtext_options
134
};
135

    
136
#undef __FTERRORS_H__
137
#define FT_ERROR_START_LIST {
138
#define FT_ERRORDEF(e, v, s) { (e), (s) },
139
#define FT_ERROR_END_LIST { 0, NULL } };
140

    
141
struct ft_error
142
{
143
    int err;
144
    const char *err_msg;
145
} static ft_errors[] =
146
#include FT_ERRORS_H
147

    
148
#define FT_ERRMSG(e) ft_errors[e].err_msg
149

    
150
typedef struct {
151
    FT_Glyph *glyph;
152
    uint32_t code;
153
    FT_Bitmap bitmap; ///< array holding bitmaps of font
154
    FT_BBox bbox;
155
    int advance;
156
    int bitmap_left;
157
    int bitmap_top;
158
} Glyph;
159

    
160
static int glyph_cmp(const Glyph *a, const Glyph *b)
161
{
162
    int64_t diff = (int64_t)a->code - (int64_t)b->code;
163
    return diff > 0 ? 1 : diff < 0 ? -1 : 0;
164
}
165

    
166
/**
167
 * Load glyphs corresponding to the UTF-32 codepoint code.
168
 */
169
static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
170
{
171
    DrawTextContext *dtext = ctx->priv;
172
    Glyph *glyph = av_mallocz(sizeof(Glyph));
173
    struct AVTreeNode *node = NULL;
174
    int ret;
175

    
176
    /* load glyph into dtext->face->glyph */
177
    ret = FT_Load_Char(dtext->face, code, dtext->ft_load_flags);
178
    if (ret)
179
        return AVERROR(EINVAL);
180

    
181
    /* save glyph */
182
    glyph->code  = code;
183
    glyph->glyph = av_mallocz(sizeof(FT_Glyph));
184
    ret = FT_Get_Glyph(dtext->face->glyph, glyph->glyph);
185
    if (ret)
186
        return AVERROR(EINVAL);
187

    
188
    glyph->bitmap      = dtext->face->glyph->bitmap;
189
    glyph->bitmap_left = dtext->face->glyph->bitmap_left;
190
    glyph->bitmap_top  = dtext->face->glyph->bitmap_top;
191
    glyph->advance     = dtext->face->glyph->advance.x >> 6;
192

    
193
    /* measure text height to calculate text_height (or the maximum text height) */
194
    FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
195

    
196
    /* cache the newly created glyph */
197
    if (!node)
198
        node = av_mallocz(av_tree_node_size);
199
    av_tree_insert(&dtext->glyphs, glyph, (void *)glyph_cmp, &node);
200

    
201
    if (glyph_ptr)
202
        *glyph_ptr = glyph;
203
    return 0;
204
}
205

    
206
static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
207
{
208
    int err;
209
    DrawTextContext *dtext = ctx->priv;
210

    
211
    dtext->class = &drawtext_class;
212
    av_opt_set_defaults2(dtext, 0, 0);
213
    dtext->fontcolor_string = av_strdup("black");
214
    dtext->boxcolor_string = av_strdup("white");
215
    dtext->shadowcolor_string = av_strdup("black");
216

    
217
    if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
218
        av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
219
        return err;
220
    }
221

    
222
    if (!dtext->fontfile) {
223
        av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
224
        return AVERROR(EINVAL);
225
    }
226

    
227
    if (dtext->textfile) {
228
        uint8_t *textbuf;
229
        size_t textbuf_size;
230

    
231
        if (dtext->text) {
232
            av_log(ctx, AV_LOG_ERROR,
233
                   "Both text and text file provided. Please provide only one\n");
234
            return AVERROR(EINVAL);
235
        }
236
        if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
237
            av_log(ctx, AV_LOG_ERROR,
238
                   "The text file '%s' could not be read or is empty\n",
239
                   dtext->textfile);
240
            return err;
241
        }
242

    
243
        if (!(dtext->text = av_malloc(textbuf_size+1)))
244
            return AVERROR(ENOMEM);
245
        memcpy(dtext->text, textbuf, textbuf_size);
246
        dtext->text[textbuf_size] = 0;
247
        av_file_unmap(textbuf, textbuf_size);
248
    }
249

    
250
    if (!dtext->text) {
251
        av_log(ctx, AV_LOG_ERROR,
252
               "Either text or a valid file must be provided\n");
253
        return AVERROR(EINVAL);
254
    }
255

    
256
    if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
257
        av_log(ctx, AV_LOG_ERROR,
258
               "Invalid font color '%s'\n", dtext->fontcolor_string);
259
        return err;
260
    }
261

    
262
    if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
263
        av_log(ctx, AV_LOG_ERROR,
264
               "Invalid box color '%s'\n", dtext->boxcolor_string);
265
        return err;
266
    }
267

    
268
    if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
269
        av_log(ctx, AV_LOG_ERROR,
270
               "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
271
        return err;
272
    }
273

    
274
    if ((err = FT_Init_FreeType(&(dtext->library)))) {
275
        av_log(ctx, AV_LOG_ERROR,
276
               "Could not load FreeType: %s\n", FT_ERRMSG(err));
277
        return AVERROR(EINVAL);
278
    }
279

    
280
    /* load the face, and set up the encoding, which is by default UTF-8 */
281
    if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
282
        av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
283
               dtext->fontfile, FT_ERRMSG(err));
284
        return AVERROR(EINVAL);
285
    }
286
    if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
287
        av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
288
               dtext->fontsize, FT_ERRMSG(err));
289
        return AVERROR(EINVAL);
290
    }
291

    
292
    dtext->use_kerning = FT_HAS_KERNING(dtext->face);
293

    
294
    /* load the fallback glyph with code 0 */
295
    load_glyph(ctx, NULL, 0);
296

    
297
#if !HAVE_LOCALTIME_R
298
    av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
299
#else
300
    if (strlen(dtext->text) >= MAX_EXPANDED_TEXT_SIZE) {
301
        av_log(ctx, AV_LOG_ERROR,
302
               "Impossible to print text, string is too big\n");
303
        return AVERROR(EINVAL);
304
    }
305
#endif
306

    
307
    return 0;
308
}
309

    
310
static int query_formats(AVFilterContext *ctx)
311
{
312
    static const enum PixelFormat pix_fmts[] = {
313
        PIX_FMT_ARGB,    PIX_FMT_RGBA,
314
        PIX_FMT_ABGR,    PIX_FMT_BGRA,
315
        PIX_FMT_RGB24,   PIX_FMT_BGR24,
316
        PIX_FMT_YUV420P, PIX_FMT_YUV444P,
317
        PIX_FMT_YUV422P, PIX_FMT_YUV411P,
318
        PIX_FMT_YUV410P, PIX_FMT_YUV440P,
319
        PIX_FMT_NONE
320
    };
321

    
322
    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
323
    return 0;
324
}
325

    
326
static int glyph_enu_free(void *opaque, void *elem)
327
{
328
    av_free(elem);
329
    return 0;
330
}
331

    
332
static av_cold void uninit(AVFilterContext *ctx)
333
{
334
    DrawTextContext *dtext = ctx->priv;
335
    int i;
336

    
337
    av_freep(&dtext->fontfile);
338
    av_freep(&dtext->text);
339
    av_freep(&dtext->fontcolor_string);
340
    av_freep(&dtext->boxcolor_string);
341
    av_freep(&dtext->shadowcolor_string);
342
    av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
343
    av_tree_destroy(dtext->glyphs);
344
    dtext->glyphs = 0;
345
    FT_Done_Face(dtext->face);
346
    FT_Done_FreeType(dtext->library);
347

    
348
    for (i = 0; i < 4; i++) {
349
        av_freep(&dtext->box_line[i]);
350
        dtext->pixel_step[i] = 0;
351
    }
352

    
353
}
354

    
355
static int config_input(AVFilterLink *inlink)
356
{
357
    DrawTextContext *dtext = inlink->dst->priv;
358
    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
359
    int ret;
360

    
361
    dtext->hsub = pix_desc->log2_chroma_w;
362
    dtext->vsub = pix_desc->log2_chroma_h;
363

    
364
    if ((ret =
365
         ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
366
                                 inlink->w, dtext->boxcolor,
367
                                 inlink->format, dtext->boxcolor_rgba,
368
                                 &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
369
        return ret;
370

    
371
    if (!dtext->is_packed_rgb) {
372
        uint8_t *rgba = dtext->fontcolor_rgba;
373
        dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
374
        dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
375
        dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
376
        dtext->fontcolor[3] = rgba[3];
377
        rgba = dtext->shadowcolor_rgba;
378
        dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
379
        dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
380
        dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
381
        dtext->shadowcolor[3] = rgba[3];
382
    }
383

    
384
    return 0;
385
}
386

    
387
#define GET_BITMAP_VAL(r, c)                                            \
388
    bitmap->pixel_mode == FT_PIXEL_MODE_MONO ?                          \
389
        (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
390
         bitmap->buffer[(r) * bitmap->pitch +  (c)]
391

    
392
#define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) {           \
393
    luma_pos    = ((x)          ) + ((y)          ) * picref->linesize[0]; \
394
    alpha = yuva_color[3] * (val) * 129;                               \
395
    picref->data[0][luma_pos]    = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos]   ) >> 23; \
396
    if(((x) & ((1<<(hsub))-1))==0 && ((y) & ((1<<(vsub))-1))==0){\
397
        chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
398
        chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
399
        picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
400
        picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
401
    }\
402
}
403

    
404
static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
405
                                 unsigned int y, unsigned int width, unsigned int height,
406
                                 unsigned char yuva_color[4], int hsub, int vsub)
407
{
408
    int r, c, alpha;
409
    unsigned int luma_pos, chroma_pos1, chroma_pos2;
410
    uint8_t src_val, dst_pixel[4];
411

    
412
    for (r = 0; r < bitmap->rows && r+y < height; r++) {
413
        for (c = 0; c < bitmap->width && c+x < width; c++) {
414
            /* get pixel in the picref (destination) */
415
            dst_pixel[0] = picref->data[0][  c+x           +  (y+r)          * picref->linesize[0]];
416
            dst_pixel[1] = picref->data[1][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[1]];
417
            dst_pixel[2] = picref->data[2][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[2]];
418

    
419
            /* get intensity value in the glyph bitmap (source) */
420
            src_val = GET_BITMAP_VAL(r, c);
421
            if (!src_val)
422
                continue;
423

    
424
            SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
425
        }
426
    }
427

    
428
    return 0;
429
}
430

    
431
#define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
432
    p   = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
433
    alpha = rgba_color[3] * (val) * 129;                              \
434
    *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
435
    *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
436
    *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
437
}
438

    
439
static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
440
                                 unsigned int x, unsigned int y,
441
                                 unsigned int width, unsigned int height, int pixel_step,
442
                                 unsigned char rgba_color[4], uint8_t rgba_map[4])
443
{
444
    int r, c, alpha;
445
    uint8_t *p;
446
    uint8_t src_val, dst_pixel[4];
447

    
448
    for (r = 0; r < bitmap->rows && r+y < height; r++) {
449
        for (c = 0; c < bitmap->width && c+x < width; c++) {
450
            /* get pixel in the picref (destination) */
451
            dst_pixel[0] = picref->data[0][(c+x + rgba_map[0]) * pixel_step +
452
                                           (y+r) * picref->linesize[0]];
453
            dst_pixel[1] = picref->data[0][(c+x + rgba_map[1]) * pixel_step +
454
                                           (y+r) * picref->linesize[0]];
455
            dst_pixel[2] = picref->data[0][(c+x + rgba_map[2]) * pixel_step +
456
                                           (y+r) * picref->linesize[0]];
457

    
458
            /* get intensity value in the glyph bitmap (source) */
459
            src_val = GET_BITMAP_VAL(r, c);
460
            if (!src_val)
461
                continue;
462

    
463
            SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
464
                          rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
465
        }
466
    }
467

    
468
    return 0;
469
}
470

    
471
static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
472
                           unsigned int width, unsigned int height,
473
                           uint8_t *line[4], int pixel_step[4], uint8_t color[4],
474
                           int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
475
{
476
    int i, j, alpha;
477

    
478
    if (color[3] != 0xFF) {
479
        if (is_rgba_packed) {
480
            uint8_t *p;
481
            for (j = 0; j < height; j++)
482
                for (i = 0; i < width; i++)
483
                    SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
484
                                  rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
485
        } else {
486
            unsigned int luma_pos, chroma_pos1, chroma_pos2;
487
            for (j = 0; j < height; j++)
488
                for (i = 0; i < width; i++)
489
                    SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
490
        }
491
    } else {
492
        ff_draw_rectangle(picref->data, picref->linesize,
493
                          line, pixel_step, hsub, vsub,
494
                          x, y, width, height);
495
    }
496
}
497

    
498
static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
499
                       int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
500
{
501
    char *text = dtext->text;
502
    uint32_t code = 0;
503
    int i;
504
    uint8_t *p;
505
    Glyph *glyph = NULL;
506

    
507
    for (i = 0, p = text; *p; i++) {
508
        Glyph dummy = { 0 };
509
        GET_UTF8(code, *p++, continue;);
510

    
511
        /* skip new line chars, just go to new line */
512
        if (code == '\n' || code == '\r' || code == '\t')
513
            continue;
514

    
515
        dummy.code = code;
516
        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
517

    
518
        if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
519
            glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
520
            return AVERROR(EINVAL);
521

    
522
        if (dtext->is_packed_rgb) {
523
            draw_glyph_rgb(picref, &glyph->bitmap,
524
                           dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
525
                           dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
526
        } else {
527
            draw_glyph_yuv(picref, &glyph->bitmap,
528
                           dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
529
                           yuvcolor, dtext->hsub, dtext->vsub);
530
        }
531
    }
532

    
533
    return 0;
534
}
535

    
536
static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
537
                     int width, int height)
538
{
539
    DrawTextContext *dtext = ctx->priv;
540
    char *text = dtext->text;
541
    uint32_t code = 0, prev_code = 0;
542
    int x = 0, y = 0, i = 0, ret;
543
    int text_height, baseline;
544
    uint8_t *p;
545
    int str_w, str_w_max;
546
    int y_min = 32000, y_max = -32000;
547
    FT_Vector delta;
548
    Glyph *glyph = NULL, *prev_glyph = NULL;
549
    Glyph dummy = { 0 };
550

    
551
#if HAVE_LOCALTIME_R
552
    time_t now = time(0);
553
    struct tm ltime;
554
    size_t expanded_text_len;
555

    
556
    dtext->expanded_text[0] = '\1';
557
    expanded_text_len = strftime(dtext->expanded_text, MAX_EXPANDED_TEXT_SIZE,
558
                                 text, localtime_r(&now, &ltime));
559
    text = dtext->expanded_text;
560
    if (expanded_text_len == 0 && dtext->expanded_text[0] != '\0') {
561
        av_log(ctx, AV_LOG_ERROR,
562
               "Impossible to print text, string is too big\n");
563
        return AVERROR(EINVAL);
564
    }
565
#endif
566

    
567
    str_w = str_w_max = 0;
568
    x = dtext->x;
569
    y = dtext->y;
570

    
571
    /* load and cache glyphs */
572
    for (i = 0, p = text; *p; i++) {
573
        GET_UTF8(code, *p++, continue;);
574

    
575
        /* get glyph */
576
        dummy.code = code;
577
        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
578
        if (!glyph)
579
            load_glyph(ctx, &glyph, code);
580

    
581
        y_min = FFMIN(glyph->bbox.yMin, y_min);
582
        y_max = FFMAX(glyph->bbox.yMax, y_max);
583
    }
584
    text_height = y_max - y_min;
585
    baseline    = y_max;
586

    
587
    /* compute and save position for each glyph */
588
    glyph = NULL;
589
    for (i = 0, p = text; *p; i++) {
590
        GET_UTF8(code, *p++, continue;);
591

    
592
        /* skip the \n in the sequence \r\n */
593
        if (prev_code == '\r' && code == '\n')
594
            continue;
595

    
596
        /* get glyph */
597
        prev_glyph = glyph;
598
        dummy.code = code;
599
        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
600

    
601
        /* kerning */
602
        if (dtext->use_kerning && prev_glyph && glyph->code) {
603
            FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
604
                           ft_kerning_default, &delta);
605
            x += delta.x >> 6;
606
        }
607

    
608
        if (x + glyph->advance >= width || code == '\r' || code == '\n') {
609
            if (x + glyph->advance >= width)
610
                str_w_max = width - dtext->x - 1;
611
            y += text_height;
612
            x = dtext->x;
613
        }
614

    
615
        /* save position */
616
        dtext->positions[i].x = x + glyph->bitmap_left;
617
        dtext->positions[i].y = y - glyph->bitmap_top + baseline;
618
        if (code != '\n' && code != '\r') {
619
            int advance = glyph->advance;
620
            if (code == '\t')
621
                advance *= dtext->tabsize;
622
            x     += advance;
623
            str_w += advance;
624
        }
625
        prev_code = code;
626
    }
627

    
628
    y += text_height;
629
    if (str_w_max == 0)
630
        str_w_max = str_w;
631

    
632
    /* draw box */
633
    if (dtext->draw_box) {
634
        /* check if it doesn't pass the limits */
635
        str_w_max = FFMIN(str_w_max, width - dtext->x - 1);
636
        y = FFMIN(y, height - 1);
637

    
638
        /* draw background */
639
        drawbox(picref, dtext->x, dtext->y, str_w_max, y-dtext->y,
640
                dtext->box_line, dtext->pixel_step, dtext->boxcolor,
641
                dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
642
    }
643

    
644
    if(dtext->shadowx || dtext->shadowy){
645
        if((ret=draw_glyphs(dtext, picref, width, height, dtext->shadowcolor_rgba, dtext->shadowcolor, dtext->shadowx, dtext->shadowy))<0)
646
            return ret;
647
    }
648

    
649
    if((ret=draw_glyphs(dtext, picref, width, height, dtext->fontcolor_rgba, dtext->fontcolor, 0, 0))<0)
650
        return ret;
651

    
652
    return 0;
653
}
654

    
655
static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
656

    
657
static void end_frame(AVFilterLink *inlink)
658
{
659
    AVFilterLink *outlink = inlink->dst->outputs[0];
660
    AVFilterBufferRef *picref = inlink->cur_buf;
661

    
662
    draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
663

    
664
    avfilter_draw_slice(outlink, 0, picref->video->h, 1);
665
    avfilter_end_frame(outlink);
666
}
667

    
668
AVFilter avfilter_vf_drawtext = {
669
    .name          = "drawtext",
670
    .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
671
    .priv_size     = sizeof(DrawTextContext),
672
    .init          = init,
673
    .uninit        = uninit,
674
    .query_formats = query_formats,
675

    
676
    .inputs    = (AVFilterPad[]) {{ .name             = "default",
677
                                    .type             = AVMEDIA_TYPE_VIDEO,
678
                                    .get_video_buffer = avfilter_null_get_video_buffer,
679
                                    .start_frame      = avfilter_null_start_frame,
680
                                    .draw_slice       = null_draw_slice,
681
                                    .end_frame        = end_frame,
682
                                    .config_props     = config_input,
683
                                    .min_perms        = AV_PERM_WRITE |
684
                                                        AV_PERM_READ,
685
                                    .rej_perms        = AV_PERM_PRESERVE },
686
                                  { .name = NULL}},
687
    .outputs   = (AVFilterPad[]) {{ .name             = "default",
688
                                    .type             = AVMEDIA_TYPE_VIDEO, },
689
                                  { .name = NULL}},
690
};