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>
6 * This file is part of Libav.
8 * Libav is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2.1 of the License, or (at your option) any later version.
13 * Libav is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * You should have received a copy of the GNU Lesser General Public
19 * License along with Libav; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25 * drawtext filter, based on the original vhook/drawtext.c
26 * filter by Gustavo Sverzut Barbieri
32 #include "libavutil/colorspace.h"
33 #include "libavutil/file.h"
34 #include "libavutil/eval.h"
35 #include "libavutil/opt.h"
36 #include "libavutil/mathematics.h"
37 #include "libavutil/random_seed.h"
38 #include "libavutil/parseutils.h"
39 #include "libavutil/pixdesc.h"
40 #include "libavutil/tree.h"
41 #include "libavutil/lfg.h"
43 #include "drawutils.h"
49 #include <freetype/config/ftheader.h>
50 #include FT_FREETYPE_H
53 static const char *const var_names[] = {
57 "main_w", "W", ///< width of the main video
58 "main_h", "H", ///< height of the main video
59 "text_w", "w", ///< width of the overlay text
60 "text_h", "h", ///< height of the overlay text
63 "n", ///< number of processed frames
64 "t", ///< timestamp expressed in seconds
68 static const char *const fun2_names[] = {
72 static double drand(void *opaque, double min, double max)
74 return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
77 typedef double (*eval_func2)(void *, double a, double b);
79 static const eval_func2 fun2[] = {
100 const AVClass *class;
101 uint8_t *fontfile; ///< font to be used
102 uint8_t *text; ///< text to be drawn
103 uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
104 size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
105 int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
106 FT_Vector *positions; ///< positions for each element in the text
107 size_t nb_positions; ///< number of elements of positions array
108 char *textfile; ///< file with text to be drawn
109 int x, y; ///< position to start drawing text
110 int w, h; ///< dimension of the text block
111 int shadowx, shadowy;
112 unsigned int fontsize; ///< font size to use
113 char *fontcolor_string; ///< font color as string
114 char *boxcolor_string; ///< box color as string
115 char *shadowcolor_string; ///< shadow color as string
116 uint8_t fontcolor[4]; ///< foreground color
117 uint8_t boxcolor[4]; ///< background color
118 uint8_t shadowcolor[4]; ///< shadow color
119 uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
120 uint8_t boxcolor_rgba[4]; ///< background color in RGBA
121 uint8_t shadowcolor_rgba[4]; ///< shadow color in RGBA
123 short int draw_box; ///< draw box around text - true or false
124 int use_kerning; ///< font kerning is used - true/false
125 int tabsize; ///< tab size
126 int fix_bounds; ///< do we let it go out of frame bounds - t/f
128 FT_Library library; ///< freetype font library handle
129 FT_Face face; ///< freetype font face handle
130 struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
131 int hsub, vsub; ///< chroma subsampling values
133 int pixel_step[4]; ///< distance in bytes between the component of each pixel
134 uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
135 uint8_t *box_line[4]; ///< line used for filling the box background
136 char *x_expr, *y_expr;
137 AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
138 double var_values[VAR_VARS_NB];
141 int draw; ///< set to zero to prevent drawing
142 AVLFG prng; ///< random
145 #define OFFSET(x) offsetof(DrawTextContext, x)
147 static const AVOption drawtext_options[]= {
148 {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
149 {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
150 {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
151 {"fontcolor","set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
152 {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
153 {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
154 {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
155 {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.dbl=16}, 1, 72 },
156 {"x", "set x", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
157 {"y", "set y", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
158 {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
159 {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
160 {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
161 {"draw", "if false do not draw", OFFSET(d_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX },
162 {"fix_bounds", "if true, check and fix text coords to avoid clipping",
163 OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.dbl=1}, 0, 1 },
165 /* FT_LOAD_* flags */
166 {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.dbl=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, 0, "ft_load_flags" },
167 {"default", "set default", 0, AV_OPT_TYPE_CONST, {FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
168 {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
169 {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
170 {"render", "set render", 0, AV_OPT_TYPE_CONST, {FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
171 {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
172 {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
173 {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
174 {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
175 {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
176 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
177 {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
178 {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
179 {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
180 {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
181 {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
185 static const char *drawtext_get_name(void *ctx)
190 static const AVClass drawtext_class = {
196 #undef __FTERRORS_H__
197 #define FT_ERROR_START_LIST {
198 #define FT_ERRORDEF(e, v, s) { (e), (s) },
199 #define FT_ERROR_END_LIST { 0, NULL } };
205 } static ft_errors[] =
208 #define FT_ERRMSG(e) ft_errors[e].err_msg
213 FT_Bitmap bitmap; ///< array holding bitmaps of font
220 static int glyph_cmp(void *key, const void *b)
222 const Glyph *a = key, *bb = b;
223 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
224 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
228 * Load glyphs corresponding to the UTF-32 codepoint code.
230 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
232 DrawTextContext *dtext = ctx->priv;
234 struct AVTreeNode *node = NULL;
237 /* load glyph into dtext->face->glyph */
238 if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
239 return AVERROR(EINVAL);
242 if (!(glyph = av_mallocz(sizeof(*glyph))) ||
243 !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
244 ret = AVERROR(ENOMEM);
249 if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
250 ret = AVERROR(EINVAL);
254 glyph->bitmap = dtext->face->glyph->bitmap;
255 glyph->bitmap_left = dtext->face->glyph->bitmap_left;
256 glyph->bitmap_top = dtext->face->glyph->bitmap_top;
257 glyph->advance = dtext->face->glyph->advance.x >> 6;
259 /* measure text height to calculate text_height (or the maximum text height) */
260 FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
262 /* cache the newly created glyph */
263 if (!(node = av_mallocz(av_tree_node_size))) {
264 ret = AVERROR(ENOMEM);
267 av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
275 av_freep(&glyph->glyph);
281 static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
284 DrawTextContext *dtext = ctx->priv;
287 dtext->class = &drawtext_class;
288 av_opt_set_defaults(dtext);
289 dtext->fontcolor_string = av_strdup("black");
290 dtext->boxcolor_string = av_strdup("white");
291 dtext->shadowcolor_string = av_strdup("black");
293 if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
294 av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
298 if (!dtext->fontfile) {
299 av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
300 return AVERROR(EINVAL);
303 if (dtext->textfile) {
308 av_log(ctx, AV_LOG_ERROR,
309 "Both text and text file provided. Please provide only one\n");
310 return AVERROR(EINVAL);
312 if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
313 av_log(ctx, AV_LOG_ERROR,
314 "The text file '%s' could not be read or is empty\n",
319 if (!(dtext->text = av_malloc(textbuf_size+1)))
320 return AVERROR(ENOMEM);
321 memcpy(dtext->text, textbuf, textbuf_size);
322 dtext->text[textbuf_size] = 0;
323 av_file_unmap(textbuf, textbuf_size);
327 av_log(ctx, AV_LOG_ERROR,
328 "Either text or a valid file must be provided\n");
329 return AVERROR(EINVAL);
332 if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
333 av_log(ctx, AV_LOG_ERROR,
334 "Invalid font color '%s'\n", dtext->fontcolor_string);
338 if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
339 av_log(ctx, AV_LOG_ERROR,
340 "Invalid box color '%s'\n", dtext->boxcolor_string);
344 if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
345 av_log(ctx, AV_LOG_ERROR,
346 "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
350 if ((err = FT_Init_FreeType(&(dtext->library)))) {
351 av_log(ctx, AV_LOG_ERROR,
352 "Could not load FreeType: %s\n", FT_ERRMSG(err));
353 return AVERROR(EINVAL);
356 /* load the face, and set up the encoding, which is by default UTF-8 */
357 if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
358 av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
359 dtext->fontfile, FT_ERRMSG(err));
360 return AVERROR(EINVAL);
362 if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
363 av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
364 dtext->fontsize, FT_ERRMSG(err));
365 return AVERROR(EINVAL);
368 dtext->use_kerning = FT_HAS_KERNING(dtext->face);
370 /* load the fallback glyph with code 0 */
371 load_glyph(ctx, NULL, 0);
373 /* set the tabsize in pixels */
374 if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
375 av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
378 dtext->tabsize *= glyph->advance;
380 #if !HAVE_LOCALTIME_R
381 av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
387 static int query_formats(AVFilterContext *ctx)
389 static const enum PixelFormat pix_fmts[] = {
390 PIX_FMT_ARGB, PIX_FMT_RGBA,
391 PIX_FMT_ABGR, PIX_FMT_BGRA,
392 PIX_FMT_RGB24, PIX_FMT_BGR24,
393 PIX_FMT_YUV420P, PIX_FMT_YUV444P,
394 PIX_FMT_YUV422P, PIX_FMT_YUV411P,
395 PIX_FMT_YUV410P, PIX_FMT_YUV440P,
399 avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
403 static int glyph_enu_free(void *opaque, void *elem)
409 static av_cold void uninit(AVFilterContext *ctx)
411 DrawTextContext *dtext = ctx->priv;
414 av_freep(&dtext->fontfile);
415 av_freep(&dtext->text);
416 av_freep(&dtext->expanded_text);
417 av_freep(&dtext->fontcolor_string);
418 av_freep(&dtext->boxcolor_string);
419 av_freep(&dtext->positions);
420 av_freep(&dtext->shadowcolor_string);
421 av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
422 av_tree_destroy(dtext->glyphs);
424 FT_Done_Face(dtext->face);
425 FT_Done_FreeType(dtext->library);
427 for (i = 0; i < 4; i++) {
428 av_freep(&dtext->box_line[i]);
429 dtext->pixel_step[i] = 0;
434 static inline int is_newline(uint32_t c)
436 return c == '\n' || c == '\r' || c == '\f' || c == '\v';
439 static int dtext_prepare_text(AVFilterContext *ctx)
441 DrawTextContext *dtext = ctx->priv;
442 uint32_t code = 0, prev_code = 0;
443 int x = 0, y = 0, i = 0, ret;
444 int text_height, baseline;
445 char *text = dtext->text;
448 int y_min = 32000, y_max = -32000;
450 Glyph *glyph = NULL, *prev_glyph = NULL;
452 int width = ctx->inputs[0]->w;
453 int height = ctx->inputs[0]->h;
456 time_t now = time(0);
458 uint8_t *buf = dtext->expanded_text;
459 int buf_size = dtext->expanded_text_size;
462 buf_size = 2*strlen(dtext->text)+1;
464 localtime_r(&now, <ime);
466 while ((buf = av_realloc(buf, buf_size))) {
468 if (strftime(buf, buf_size, dtext->text, <ime) != 0 || *buf == 0)
474 return AVERROR(ENOMEM);
475 text = dtext->expanded_text = buf;
476 dtext->expanded_text_size = buf_size;
479 if ((len = strlen(text)) > dtext->nb_positions) {
480 FT_Vector *p = av_realloc(dtext->positions,
481 len * sizeof(*dtext->positions));
483 av_freep(dtext->positions);
484 dtext->nb_positions = 0;
485 return AVERROR(ENOMEM);
487 dtext->positions = p;
488 dtext->nb_positions = len;
492 /* load and cache glyphs */
493 for (i = 0, p = text; *p; i++) {
494 GET_UTF8(code, *p++, continue;);
498 glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
500 ret = load_glyph(ctx, &glyph, code);
505 y_min = FFMIN(glyph->bbox.yMin, y_min);
506 y_max = FFMAX(glyph->bbox.yMax, y_max);
508 text_height = y_max - y_min;
511 /* compute and save position for each glyph */
513 for (i = 0, p = text; *p; i++) {
514 GET_UTF8(code, *p++, continue;);
516 /* skip the \n in the sequence \r\n */
517 if (prev_code == '\r' && code == '\n')
521 if (is_newline(code)) {
522 str_w = FFMAX(str_w, x - dtext->x);
531 glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
534 if (dtext->use_kerning && prev_glyph && glyph->code) {
535 FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
536 ft_kerning_default, &delta);
540 if (x + glyph->bbox.xMax >= width) {
541 str_w = FFMAX(str_w, x);
547 dtext->positions[i].x = x + glyph->bitmap_left;
548 dtext->positions[i].y = y - glyph->bitmap_top + baseline;
549 if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
550 else x += glyph->advance;
553 str_w = FFMIN(width - 1, FFMAX(str_w, x));
554 y = FFMIN(y + text_height, height - 1);
557 dtext->var_values[VAR_TEXT_W] = dtext->var_values[VAR_TW] = dtext->w;
559 dtext->var_values[VAR_TEXT_H] = dtext->var_values[VAR_TH] = dtext->h;
565 static int config_input(AVFilterLink *inlink)
567 AVFilterContext *ctx = inlink->dst;
568 DrawTextContext *dtext = ctx->priv;
569 const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
572 dtext->hsub = pix_desc->log2_chroma_w;
573 dtext->vsub = pix_desc->log2_chroma_h;
575 dtext->var_values[VAR_E ] = M_E;
576 dtext->var_values[VAR_PHI] = M_PHI;
577 dtext->var_values[VAR_PI ] = M_PI;
579 dtext->var_values[VAR_MAIN_W] =
580 dtext->var_values[VAR_MW] = ctx->inputs[0]->w;
581 dtext->var_values[VAR_MAIN_H] =
582 dtext->var_values[VAR_MH] = ctx->inputs[0]->h;
584 dtext->var_values[VAR_X] = 0;
585 dtext->var_values[VAR_Y] = 0;
586 dtext->var_values[VAR_N] = 0;
587 dtext->var_values[VAR_T] = NAN;
589 av_lfg_init(&dtext->prng, av_get_random_seed());
591 if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
592 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
593 (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
594 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
595 (ret = av_expr_parse(&dtext->d_pexpr, dtext->d_expr, var_names,
596 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
597 return AVERROR(EINVAL);
600 ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
601 inlink->w, dtext->boxcolor,
602 inlink->format, dtext->boxcolor_rgba,
603 &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
606 if (!dtext->is_packed_rgb) {
607 uint8_t *rgba = dtext->fontcolor_rgba;
608 dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
609 dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
610 dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
611 dtext->fontcolor[3] = rgba[3];
612 rgba = dtext->shadowcolor_rgba;
613 dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
614 dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
615 dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
616 dtext->shadowcolor[3] = rgba[3];
621 return dtext_prepare_text(ctx);
624 #define GET_BITMAP_VAL(r, c) \
625 bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
626 (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
627 bitmap->buffer[(r) * bitmap->pitch + (c)]
629 #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
630 luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
631 alpha = yuva_color[3] * (val) * 129; \
632 picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
633 if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
634 chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
635 chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
636 picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
637 picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
641 static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
642 unsigned int y, unsigned int width, unsigned int height,
643 const uint8_t yuva_color[4], int hsub, int vsub)
646 unsigned int luma_pos, chroma_pos1, chroma_pos2;
649 for (r = 0; r < bitmap->rows && r+y < height; r++) {
650 for (c = 0; c < bitmap->width && c+x < width; c++) {
651 /* get intensity value in the glyph bitmap (source) */
652 src_val = GET_BITMAP_VAL(r, c);
656 SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
663 #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
664 p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
665 alpha = rgba_color[3] * (val) * 129; \
666 *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
667 *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
668 *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
671 static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
672 unsigned int x, unsigned int y,
673 unsigned int width, unsigned int height, int pixel_step,
674 const uint8_t rgba_color[4], const uint8_t rgba_map[4])
680 for (r = 0; r < bitmap->rows && r+y < height; r++) {
681 for (c = 0; c < bitmap->width && c+x < width; c++) {
682 /* get intensity value in the glyph bitmap (source) */
683 src_val = GET_BITMAP_VAL(r, c);
687 SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
688 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
695 static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
696 unsigned int width, unsigned int height,
697 uint8_t *line[4], int pixel_step[4], uint8_t color[4],
698 int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
702 if (color[3] != 0xFF) {
703 if (is_rgba_packed) {
705 for (j = 0; j < height; j++)
706 for (i = 0; i < width; i++)
707 SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
708 rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
710 unsigned int luma_pos, chroma_pos1, chroma_pos2;
711 for (j = 0; j < height; j++)
712 for (i = 0; i < width; i++)
713 SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
716 ff_draw_rectangle(picref->data, picref->linesize,
717 line, pixel_step, hsub, vsub,
718 x, y, width, height);
722 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
723 int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
725 char *text = HAVE_LOCALTIME_R ? dtext->expanded_text : dtext->text;
731 for (i = 0, p = text; *p; i++) {
733 GET_UTF8(code, *p++, continue;);
735 /* skip new line chars, just go to new line */
736 if (code == '\n' || code == '\r' || code == '\t')
740 glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
742 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
743 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
744 return AVERROR(EINVAL);
746 if (dtext->is_packed_rgb) {
747 draw_glyph_rgb(picref, &glyph->bitmap,
748 dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
749 dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
751 draw_glyph_yuv(picref, &glyph->bitmap,
752 dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
753 yuvcolor, dtext->hsub, dtext->vsub);
760 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
761 int width, int height)
763 DrawTextContext *dtext = ctx->priv;
768 drawbox(picref, dtext->x, dtext->y, dtext->w, dtext->h,
769 dtext->box_line, dtext->pixel_step, dtext->boxcolor,
770 dtext->hsub, dtext->vsub, dtext->is_packed_rgb,
773 if (dtext->shadowx || dtext->shadowy) {
774 if ((ret = draw_glyphs(dtext, picref, width, height,
775 dtext->shadowcolor_rgba,
777 dtext->x + dtext->shadowx,
778 dtext->y + dtext->shadowy)) < 0)
782 if ((ret = draw_glyphs(dtext, picref, width, height,
783 dtext->fontcolor_rgba,
792 static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
794 static inline int normalize_double(int *n, double d)
799 ret = AVERROR(EINVAL);
800 } else if (d > INT_MAX || d < INT_MIN) {
801 *n = d > INT_MAX ? INT_MAX : INT_MIN;
802 ret = AVERROR(EINVAL);
809 static void start_frame(AVFilterLink *inlink, AVFilterBufferRef *inpicref)
811 AVFilterContext *ctx = inlink->dst;
812 DrawTextContext *dtext = ctx->priv;
815 if (dtext_prepare_text(ctx) < 0) {
816 av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
820 dtext->var_values[VAR_T] = inpicref->pts == AV_NOPTS_VALUE ?
821 NAN : inpicref->pts * av_q2d(inlink->time_base);
822 dtext->var_values[VAR_X] =
823 av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
824 dtext->var_values[VAR_Y] =
825 av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
826 dtext->var_values[VAR_X] =
827 av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
829 dtext->draw = fail ? 0 :
830 av_expr_eval(dtext->d_pexpr, dtext->var_values, &dtext->prng);
832 normalize_double(&dtext->x, dtext->var_values[VAR_X]);
833 normalize_double(&dtext->y, dtext->var_values[VAR_Y]);
835 if (dtext->fix_bounds) {
836 if (dtext->x < 0) dtext->x = 0;
837 if (dtext->y < 0) dtext->y = 0;
838 if ((unsigned)dtext->x + (unsigned)dtext->w > inlink->w)
839 dtext->x = inlink->w - dtext->w;
840 if ((unsigned)dtext->y + (unsigned)dtext->h > inlink->h)
841 dtext->y = inlink->h - dtext->h;
844 dtext->x &= ~((1 << dtext->hsub) - 1);
845 dtext->y &= ~((1 << dtext->vsub) - 1);
847 av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
848 (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
849 dtext->x, dtext->y, dtext->x+dtext->w, dtext->y+dtext->h);
851 avfilter_start_frame(inlink->dst->outputs[0], inpicref);
854 static void end_frame(AVFilterLink *inlink)
856 AVFilterLink *outlink = inlink->dst->outputs[0];
857 AVFilterBufferRef *picref = inlink->cur_buf;
858 DrawTextContext *dtext = inlink->dst->priv;
861 draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
863 dtext->var_values[VAR_N] += 1.0;
865 avfilter_draw_slice(outlink, 0, picref->video->h, 1);
866 avfilter_end_frame(outlink);
869 AVFilter avfilter_vf_drawtext = {
871 .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
872 .priv_size = sizeof(DrawTextContext),
875 .query_formats = query_formats,
877 .inputs = (AVFilterPad[]) {{ .name = "default",
878 .type = AVMEDIA_TYPE_VIDEO,
879 .get_video_buffer = ff_null_get_video_buffer,
880 .start_frame = start_frame,
881 .draw_slice = null_draw_slice,
882 .end_frame = end_frame,
883 .config_props = config_input,
884 .min_perms = AV_PERM_WRITE |
886 .rej_perms = AV_PERM_PRESERVE },
888 .outputs = (AVFilterPad[]) {{ .name = "default",
889 .type = AVMEDIA_TYPE_VIDEO, },