Statistics
| Branch: | Revision:

ffmpeg / libavfilter / vf_drawtext.c @ bccea088

History | View | Annotate | Download (25.4 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
    unsigned int fontsize;          ///< font size to use
63
    char *fontcolor_string;         ///< font color as string
64
    char *boxcolor_string;          ///< box color as string
65
    uint8_t fontcolor[4];           ///< foreground color
66
    uint8_t boxcolor[4];            ///< background color
67
    uint8_t fontcolor_rgba[4];      ///< foreground color in RGBA
68
    uint8_t boxcolor_rgba[4];       ///< background color in RGBA
69

    
70
    short int draw_box;             ///< draw box around text - true or false
71
    int use_kerning;                ///< font kerning is used - true/false
72
    int tabsize;                    ///< tab size
73

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

    
84
#define OFFSET(x) offsetof(DrawTextContext, x)
85

    
86
static const AVOption drawtext_options[]= {
87
{"fontfile", "set font file",        OFFSET(fontfile),         FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
88
{"text",     "set text",             OFFSET(text),             FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
89
{"textfile", "set text file",        OFFSET(textfile),         FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
90
{"fontcolor","set foreground color", OFFSET(fontcolor_string), FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
91
{"boxcolor", "set box color",        OFFSET(boxcolor_string),  FF_OPT_TYPE_STRING, 0,  CHAR_MIN, CHAR_MAX },
92
{"box",      "set box",              OFFSET(draw_box),         FF_OPT_TYPE_INT,    0,         0,        1 },
93
{"fontsize", "set font size",        OFFSET(fontsize),         FF_OPT_TYPE_INT,   16,         1,       72 },
94
{"x",        "set x",                OFFSET(x),                FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
95
{"y",        "set y",                OFFSET(y),                FF_OPT_TYPE_INT,    0,         0,  INT_MAX },
96
{"tabsize",  "set tab size",         OFFSET(tabsize),          FF_OPT_TYPE_INT,    4,         0,  INT_MAX },
97

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

    
118
static const char *drawtext_get_name(void *ctx)
119
{
120
    return "drawtext";
121
}
122

    
123
static const AVClass drawtext_class = {
124
    "DrawTextContext",
125
    drawtext_get_name,
126
    drawtext_options
127
};
128

    
129
#undef __FTERRORS_H__
130
#define FT_ERROR_START_LIST {
131
#define FT_ERRORDEF(e, v, s) { (e), (s) },
132
#define FT_ERROR_END_LIST { 0, NULL } };
133

    
134
struct ft_error
135
{
136
    int err;
137
    const char *err_msg;
138
} static ft_errors[] =
139
#include FT_ERRORS_H
140

    
141
#define FT_ERRMSG(e) ft_errors[e].err_msg
142

    
143
typedef struct {
144
    FT_Glyph *glyph;
145
    uint32_t code;
146
    FT_Bitmap bitmap; ///< array holding bitmaps of font
147
    FT_BBox bbox;
148
    int advance;
149
    int bitmap_left;
150
    int bitmap_top;
151
} Glyph;
152

    
153
static int glyph_cmp(const Glyph *a, const Glyph *b)
154
{
155
    int64_t diff = (int64_t)a->code - (int64_t)b->code;
156
    return diff > 0 ? 1 : diff < 0 ? -1 : 0;
157
}
158

    
159
/**
160
 * Load glyphs corresponding to the UTF-32 codepoint code.
161
 */
162
static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
163
{
164
    DrawTextContext *dtext = ctx->priv;
165
    Glyph *glyph = av_mallocz(sizeof(Glyph));
166
    struct AVTreeNode *node = NULL;
167
    int ret;
168

    
169
    /* load glyph into dtext->face->glyph */
170
    ret = FT_Load_Char(dtext->face, code, dtext->ft_load_flags);
171
    if (ret)
172
        return AVERROR(EINVAL);
173

    
174
    /* save glyph */
175
    glyph->code  = code;
176
    glyph->glyph = av_mallocz(sizeof(FT_Glyph));
177
    ret = FT_Get_Glyph(dtext->face->glyph, glyph->glyph);
178
    if (ret)
179
        return AVERROR(EINVAL);
180

    
181
    glyph->bitmap      = dtext->face->glyph->bitmap;
182
    glyph->bitmap_left = dtext->face->glyph->bitmap_left;
183
    glyph->bitmap_top  = dtext->face->glyph->bitmap_top;
184
    glyph->advance     = dtext->face->glyph->advance.x >> 6;
185

    
186
    /* measure text height to calculate text_height (or the maximum text height) */
187
    FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
188

    
189
    /* cache the newly created glyph */
190
    if (!node)
191
        node = av_mallocz(av_tree_node_size);
192
    av_tree_insert(&dtext->glyphs, glyph, (void *)glyph_cmp, &node);
193

    
194
    if (glyph_ptr)
195
        *glyph_ptr = glyph;
196
    return 0;
197
}
198

    
199
static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
200
{
201
    int err;
202
    DrawTextContext *dtext = ctx->priv;
203

    
204
    dtext->class = &drawtext_class;
205
    av_opt_set_defaults2(dtext, 0, 0);
206
    dtext->fontcolor_string = av_strdup("black");
207
    dtext->boxcolor_string = av_strdup("white");
208

    
209
    if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
210
        av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
211
        return err;
212
    }
213

    
214
    if (!dtext->fontfile) {
215
        av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
216
        return AVERROR(EINVAL);
217
    }
218

    
219
    if (dtext->textfile) {
220
        uint8_t *textbuf;
221
        size_t textbuf_size;
222

    
223
        if (dtext->text) {
224
            av_log(ctx, AV_LOG_ERROR,
225
                   "Both text and text file provided. Please provide only one\n");
226
            return AVERROR(EINVAL);
227
        }
228
        if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
229
            av_log(ctx, AV_LOG_ERROR,
230
                   "The text file '%s' could not be read or is empty\n",
231
                   dtext->textfile);
232
            return err;
233
        }
234

    
235
        if (!(dtext->text = av_malloc(textbuf_size+1)))
236
            return AVERROR(ENOMEM);
237
        memcpy(dtext->text, textbuf, textbuf_size);
238
        dtext->text[textbuf_size] = 0;
239
        av_file_unmap(textbuf, textbuf_size);
240
    }
241

    
242
    if (!dtext->text) {
243
        av_log(ctx, AV_LOG_ERROR,
244
               "Either text or a valid file must be provided\n");
245
        return AVERROR(EINVAL);
246
    }
247

    
248
    if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
249
        av_log(ctx, AV_LOG_ERROR,
250
               "Invalid font color '%s'\n", dtext->fontcolor_string);
251
        return err;
252
    }
253

    
254
    if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
255
        av_log(ctx, AV_LOG_ERROR,
256
               "Invalid box color '%s'\n", dtext->boxcolor_string);
257
        return err;
258
    }
259

    
260
    if ((err = FT_Init_FreeType(&(dtext->library)))) {
261
        av_log(ctx, AV_LOG_ERROR,
262
               "Could not load FreeType: %s\n", FT_ERRMSG(err));
263
        return AVERROR(EINVAL);
264
    }
265

    
266
    /* load the face, and set up the encoding, which is by default UTF-8 */
267
    if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
268
        av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
269
               dtext->fontfile, FT_ERRMSG(err));
270
        return AVERROR(EINVAL);
271
    }
272
    if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
273
        av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
274
               dtext->fontsize, FT_ERRMSG(err));
275
        return AVERROR(EINVAL);
276
    }
277

    
278
    dtext->use_kerning = FT_HAS_KERNING(dtext->face);
279

    
280
    /* load the fallback glyph with code 0 */
281
    load_glyph(ctx, NULL, 0);
282

    
283
#if !HAVE_LOCALTIME_R
284
    av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
285
#else
286
    if (strlen(dtext->text) >= MAX_EXPANDED_TEXT_SIZE) {
287
        av_log(ctx, AV_LOG_ERROR,
288
               "Impossible to print text, string is too big\n");
289
        return AVERROR(EINVAL);
290
    }
291
#endif
292

    
293
    return 0;
294
}
295

    
296
static int query_formats(AVFilterContext *ctx)
297
{
298
    static const enum PixelFormat pix_fmts[] = {
299
        PIX_FMT_ARGB,    PIX_FMT_RGBA,
300
        PIX_FMT_ABGR,    PIX_FMT_BGRA,
301
        PIX_FMT_RGB24,   PIX_FMT_BGR24,
302
        PIX_FMT_YUV420P, PIX_FMT_YUV444P,
303
        PIX_FMT_YUV422P, PIX_FMT_YUV411P,
304
        PIX_FMT_YUV410P, PIX_FMT_YUV440P,
305
        PIX_FMT_NONE
306
    };
307

    
308
    avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
309
    return 0;
310
}
311

    
312
static int glyph_enu_free(void *opaque, void *elem)
313
{
314
    av_free(elem);
315
    return 0;
316
}
317

    
318
static av_cold void uninit(AVFilterContext *ctx)
319
{
320
    DrawTextContext *dtext = ctx->priv;
321
    int i;
322

    
323
    av_freep(&dtext->fontfile);
324
    av_freep(&dtext->text);
325
    av_freep(&dtext->fontcolor_string);
326
    av_freep(&dtext->boxcolor_string);
327
    av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
328
    av_tree_destroy(dtext->glyphs);
329
    dtext->glyphs = 0;
330
    FT_Done_Face(dtext->face);
331
    FT_Done_FreeType(dtext->library);
332

    
333
    for (i = 0; i < 4; i++) {
334
        av_freep(&dtext->box_line[i]);
335
        dtext->pixel_step[i] = 0;
336
    }
337

    
338
}
339

    
340
static int config_input(AVFilterLink *inlink)
341
{
342
    DrawTextContext *dtext = inlink->dst->priv;
343
    const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
344
    int ret;
345

    
346
    dtext->hsub = pix_desc->log2_chroma_w;
347
    dtext->vsub = pix_desc->log2_chroma_h;
348

    
349
    if ((ret =
350
         ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
351
                                 inlink->w, dtext->boxcolor,
352
                                 inlink->format, dtext->boxcolor_rgba,
353
                                 &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
354
        return ret;
355

    
356
    if (!dtext->is_packed_rgb) {
357
        uint8_t *rgba = dtext->fontcolor_rgba;
358
        dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
359
        dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
360
        dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
361
        dtext->fontcolor[3] = rgba[3];
362
    }
363

    
364
    return 0;
365
}
366

    
367
#define GET_BITMAP_VAL(r, c)                                            \
368
    bitmap->pixel_mode == FT_PIXEL_MODE_MONO ?                          \
369
        (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
370
         bitmap->buffer[(r) * bitmap->pitch +  (c)]
371

    
372
#define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) {           \
373
    luma_pos    = ((x)          ) + ((y)          ) * picref->linesize[0]; \
374
    alpha = yuva_color[3] * (val) * 129;                               \
375
    picref->data[0][luma_pos]    = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos]   ) >> 23; \
376
    if(((x) & ((1<<(hsub))-1))==0 && ((y) & ((1<<(vsub))-1))==0){\
377
        chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
378
        chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
379
        picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
380
        picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
381
    }\
382
}
383

    
384
static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
385
                                 unsigned int y, unsigned int width, unsigned int height,
386
                                 unsigned char yuva_color[4], int hsub, int vsub)
387
{
388
    int r, c, alpha;
389
    unsigned int luma_pos, chroma_pos1, chroma_pos2;
390
    uint8_t src_val, dst_pixel[4];
391

    
392
    for (r = 0; r < bitmap->rows && r+y < height; r++) {
393
        for (c = 0; c < bitmap->width && c+x < width; c++) {
394
            /* get pixel in the picref (destination) */
395
            dst_pixel[0] = picref->data[0][  c+x           +  (y+r)          * picref->linesize[0]];
396
            dst_pixel[1] = picref->data[1][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[1]];
397
            dst_pixel[2] = picref->data[2][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[2]];
398

    
399
            /* get intensity value in the glyph bitmap (source) */
400
            src_val = GET_BITMAP_VAL(r, c);
401
            if (!src_val)
402
                continue;
403

    
404
            SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
405
        }
406
    }
407

    
408
    return 0;
409
}
410

    
411
#define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
412
    p   = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
413
    alpha = rgba_color[3] * (val) * 129;                              \
414
    *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
415
    *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
416
    *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
417
}
418

    
419
static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
420
                                 unsigned int x, unsigned int y,
421
                                 unsigned int width, unsigned int height, int pixel_step,
422
                                 unsigned char rgba_color[4], uint8_t rgba_map[4])
423
{
424
    int r, c, alpha;
425
    uint8_t *p;
426
    uint8_t src_val, dst_pixel[4];
427

    
428
    for (r = 0; r < bitmap->rows && r+y < height; r++) {
429
        for (c = 0; c < bitmap->width && c+x < width; c++) {
430
            /* get pixel in the picref (destination) */
431
            dst_pixel[0] = picref->data[0][(c+x + rgba_map[0]) * pixel_step +
432
                                           (y+r) * picref->linesize[0]];
433
            dst_pixel[1] = picref->data[0][(c+x + rgba_map[1]) * pixel_step +
434
                                           (y+r) * picref->linesize[0]];
435
            dst_pixel[2] = picref->data[0][(c+x + rgba_map[2]) * pixel_step +
436
                                           (y+r) * picref->linesize[0]];
437

    
438
            /* get intensity value in the glyph bitmap (source) */
439
            src_val = GET_BITMAP_VAL(r, c);
440
            if (!src_val)
441
                continue;
442

    
443
            SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
444
                          rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
445
        }
446
    }
447

    
448
    return 0;
449
}
450

    
451
static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
452
                           unsigned int width, unsigned int height,
453
                           uint8_t *line[4], int pixel_step[4], uint8_t color[4],
454
                           int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
455
{
456
    int i, j, alpha;
457

    
458
    if (color[3] != 0xFF) {
459
        if (is_rgba_packed) {
460
            uint8_t *p;
461
            for (j = 0; j < height; j++)
462
                for (i = 0; i < width; i++)
463
                    SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
464
                                  rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
465
        } else {
466
            unsigned int luma_pos, chroma_pos1, chroma_pos2;
467
            for (j = 0; j < height; j++)
468
                for (i = 0; i < width; i++)
469
                    SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
470
        }
471
    } else {
472
        ff_draw_rectangle(picref->data, picref->linesize,
473
                          line, pixel_step, hsub, vsub,
474
                          x, y, width, height);
475
    }
476
}
477

    
478
static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
479
                     int width, int height)
480
{
481
    DrawTextContext *dtext = ctx->priv;
482
    char *text = dtext->text;
483
    uint32_t code = 0, prev_code = 0;
484
    int x = 0, y = 0, i = 0;
485
    int text_height, baseline;
486
    uint8_t *p;
487
    int str_w, str_w_max;
488
    int y_min = 32000, y_max = -32000;
489
    FT_Vector delta;
490
    Glyph *glyph = NULL, *prev_glyph = NULL;
491
    Glyph dummy = { 0 };
492

    
493
#if HAVE_LOCALTIME_R
494
    time_t now = time(0);
495
    struct tm ltime;
496
    size_t expanded_text_len;
497

    
498
    dtext->expanded_text[0] = '\1';
499
    expanded_text_len = strftime(dtext->expanded_text, MAX_EXPANDED_TEXT_SIZE,
500
                                 text, localtime_r(&now, &ltime));
501
    text = dtext->expanded_text;
502
    if (expanded_text_len == 0 && dtext->expanded_text[0] != '\0') {
503
        av_log(ctx, AV_LOG_ERROR,
504
               "Impossible to print text, string is too big\n");
505
        return AVERROR(EINVAL);
506
    }
507
#endif
508

    
509
    str_w = str_w_max = 0;
510
    x = dtext->x;
511
    y = dtext->y;
512

    
513
    /* load and cache glyphs */
514
    for (i = 0, p = text; *p; i++) {
515
        GET_UTF8(code, *p++, continue;);
516

    
517
        /* get glyph */
518
        dummy.code = code;
519
        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
520
        if (!glyph)
521
            load_glyph(ctx, &glyph, code);
522

    
523
        y_min = FFMIN(glyph->bbox.yMin, y_min);
524
        y_max = FFMAX(glyph->bbox.yMax, y_max);
525
    }
526
    text_height = y_max - y_min;
527
    baseline    = y_max;
528

    
529
    /* compute and save position for each glyph */
530
    glyph = NULL;
531
    for (i = 0, p = text; *p; i++) {
532
        GET_UTF8(code, *p++, continue;);
533

    
534
        /* skip the \n in the sequence \r\n */
535
        if (prev_code == '\r' && code == '\n')
536
            continue;
537

    
538
        /* get glyph */
539
        prev_glyph = glyph;
540
        dummy.code = code;
541
        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
542

    
543
        /* kerning */
544
        if (dtext->use_kerning && prev_glyph && glyph->code) {
545
            FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
546
                           ft_kerning_default, &delta);
547
            x += delta.x >> 6;
548
        }
549

    
550
        if (x + glyph->advance >= width || code == '\r' || code == '\n') {
551
            if (x + glyph->advance >= width)
552
                str_w_max = width - dtext->x - 1;
553
            y += text_height;
554
            x = dtext->x;
555
        }
556

    
557
        /* save position */
558
        dtext->positions[i].x = x + glyph->bitmap_left;
559
        dtext->positions[i].y = y - glyph->bitmap_top + baseline;
560
        if (code != '\n' && code != '\r') {
561
            int advance = glyph->advance;
562
            if (code == '\t')
563
                advance *= dtext->tabsize;
564
            x     += advance;
565
            str_w += advance;
566
        }
567
        prev_code = code;
568
    }
569

    
570
    y += text_height;
571
    if (str_w_max == 0)
572
        str_w_max = str_w;
573

    
574
    /* draw box */
575
    if (dtext->draw_box) {
576
        /* check if it doesn't pass the limits */
577
        str_w_max = FFMIN(str_w_max, width - dtext->x - 1);
578
        y = FFMIN(y, height - 1);
579

    
580
        /* draw background */
581
        drawbox(picref, dtext->x, dtext->y, str_w_max, y-dtext->y,
582
                dtext->box_line, dtext->pixel_step, dtext->boxcolor,
583
                dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
584
    }
585

    
586
    /* draw glyphs */
587
    for (i = 0, p = text; *p; i++) {
588
        Glyph dummy = { 0 };
589
        GET_UTF8(code, *p++, continue;);
590

    
591
        /* skip new line chars, just go to new line */
592
        if (code == '\n' || code == '\r' || code == '\t')
593
            continue;
594

    
595
        dummy.code = code;
596
        glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
597

    
598
        if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
599
            glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
600
            return AVERROR(EINVAL);
601

    
602
        if (dtext->is_packed_rgb) {
603
            draw_glyph_rgb(picref, &glyph->bitmap,
604
                           dtext->positions[i].x, dtext->positions[i].y, width, height,
605
                           dtext->pixel_step[0], dtext->fontcolor_rgba, dtext->rgba_map);
606
        } else {
607
            draw_glyph_yuv(picref, &glyph->bitmap,
608
                           dtext->positions[i].x, dtext->positions[i].y, width, height,
609
                           dtext->fontcolor, dtext->hsub, dtext->vsub);
610
        }
611
    }
612

    
613
    return 0;
614
}
615

    
616
static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
617

    
618
static void end_frame(AVFilterLink *inlink)
619
{
620
    AVFilterLink *outlink = inlink->dst->outputs[0];
621
    AVFilterBufferRef *picref = inlink->cur_buf;
622

    
623
    draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
624

    
625
    avfilter_draw_slice(outlink, 0, picref->video->h, 1);
626
    avfilter_end_frame(outlink);
627
}
628

    
629
AVFilter avfilter_vf_drawtext = {
630
    .name          = "drawtext",
631
    .description   = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
632
    .priv_size     = sizeof(DrawTextContext),
633
    .init          = init,
634
    .uninit        = uninit,
635
    .query_formats = query_formats,
636

    
637
    .inputs    = (AVFilterPad[]) {{ .name             = "default",
638
                                    .type             = AVMEDIA_TYPE_VIDEO,
639
                                    .get_video_buffer = avfilter_null_get_video_buffer,
640
                                    .start_frame      = avfilter_null_start_frame,
641
                                    .draw_slice       = null_draw_slice,
642
                                    .end_frame        = end_frame,
643
                                    .config_props     = config_input,
644
                                    .min_perms        = AV_PERM_WRITE |
645
                                                        AV_PERM_READ,
646
                                    .rej_perms        = AV_PERM_PRESERVE },
647
                                  { .name = NULL}},
648
    .outputs   = (AVFilterPad[]) {{ .name             = "default",
649
                                    .type             = AVMEDIA_TYPE_VIDEO, },
650
                                  { .name = NULL}},
651
};