Statistics
| Branch: | Revision:

ffmpeg / libavfilter / vf_drawtext.c @ 476aaec6

History | View | Annotate | Download (25.3 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
    chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
375
    chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
376
    alpha = (yuva_color[3] * (val)) / 255;                               \
377
    picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255 - alpha) * picref->data[0][luma_pos]) >> 8; \
378
    picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255 - alpha) * picref->data[1][chroma_pos1]) >> 8; \
379
    picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255 - alpha) * picref->data[2][chroma_pos2]) >> 8; \
380
}
381

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

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

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

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

    
406
    return 0;
407
}
408

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

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

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

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

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

    
446
    return 0;
447
}
448

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

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

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

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

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

    
507
    str_w = str_w_max = 0;
508
    x = dtext->x;
509
    y = dtext->y;
510

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

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

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

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

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

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

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

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

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

    
568
    y += text_height;
569
    if (str_w_max == 0)
570
        str_w_max = str_w;
571

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

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

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

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

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

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

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

    
611
    return 0;
612
}
613

    
614
static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
615

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

    
621
    draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
622

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

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

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