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 FFmpeg.
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.
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.
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
25 * drawtext filter, based on the original vhook/drawtext.c
26 * filter by Gustavo Sverzut Barbieri
34 #include <sys/types.h>
42 #if CONFIG_LIBFONTCONFIG
43 #include <fontconfig/fontconfig.h>
46 #include "libavutil/avstring.h"
47 #include "libavutil/bprint.h"
48 #include "libavutil/common.h"
49 #include "libavutil/file.h"
50 #include "libavutil/eval.h"
51 #include "libavutil/opt.h"
52 #include "libavutil/random_seed.h"
53 #include "libavutil/parseutils.h"
54 #include "libavutil/timecode.h"
55 #include "libavutil/time_internal.h"
56 #include "libavutil/tree.h"
57 #include "libavutil/lfg.h"
59 #include "drawutils.h"
69 #include FT_FREETYPE_H
73 static const char *const var_names[] = {
76 "line_h", "lh", ///< line height, same as max_glyph_h
77 "main_h", "h", "H", ///< height of the input video
78 "main_w", "w", "W", ///< width of the input video
79 "max_glyph_a", "ascent", ///< max glyph ascent
80 "max_glyph_d", "descent", ///< min glyph descent
81 "max_glyph_h", ///< max glyph height
82 "max_glyph_w", ///< max glyph width
83 "n", ///< number of frame
85 "t", ///< timestamp expressed in seconds
86 "text_h", "th", ///< height of the rendered text
87 "text_w", "tw", ///< width of the rendered text
97 static const char *const fun2_names[] = {
101 static double drand(void *opaque, double min, double max)
103 return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
106 typedef double (*eval_func2)(void *, double a, double b);
108 static const eval_func2 fun2[] = {
117 VAR_MAIN_H, VAR_h, VAR_H,
118 VAR_MAIN_W, VAR_w, VAR_W,
119 VAR_MAX_GLYPH_A, VAR_ASCENT,
120 VAR_MAX_GLYPH_D, VAR_DESCENT,
137 enum expansion_mode {
143 typedef struct DrawTextContext {
144 const AVClass *class;
145 int exp_mode; ///< expansion mode to use for the text
146 int reinit; ///< tells if the filter is being reinited
147 #if CONFIG_LIBFONTCONFIG
148 uint8_t *font; ///< font to be used
150 uint8_t *fontfile; ///< font to be used
151 uint8_t *text; ///< text to be drawn
152 AVBPrint expanded_text; ///< used to contain the expanded text
153 uint8_t *fontcolor_expr; ///< fontcolor expression to evaluate
154 AVBPrint expanded_fontcolor; ///< used to contain the expanded fontcolor spec
155 int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
156 FT_Vector *positions; ///< positions for each element in the text
157 size_t nb_positions; ///< number of elements of positions array
158 char *textfile; ///< file with text to be drawn
159 int x; ///< x position to start drawing text
160 int y; ///< y position to start drawing text
161 int max_glyph_w; ///< max glyph width
162 int max_glyph_h; ///< max glyph height
163 int shadowx, shadowy;
164 int borderw; ///< border width
165 char *fontsize_expr; ///< expression for fontsize
166 AVExpr *fontsize_pexpr; ///< parsed expressions for fontsize
167 unsigned int fontsize; ///< font size to use
168 unsigned int default_fontsize; ///< default font size to use
170 int line_spacing; ///< lines spacing in pixels
171 short int draw_box; ///< draw box around text - true or false
172 int boxborderw; ///< box border width
173 int use_kerning; ///< font kerning is used - true/false
174 int tabsize; ///< tab size
175 int fix_bounds; ///< do we let it go out of frame bounds - t/f
178 FFDrawColor fontcolor; ///< foreground color
179 FFDrawColor shadowcolor; ///< shadow color
180 FFDrawColor bordercolor; ///< border color
181 FFDrawColor boxcolor; ///< background color
183 FT_Library library; ///< freetype font library handle
184 FT_Face face; ///< freetype font face handle
185 FT_Stroker stroker; ///< freetype stroker handle
186 struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
187 char *x_expr; ///< expression for x position
188 char *y_expr; ///< expression for y position
189 AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
190 int64_t basetime; ///< base pts time in the real world for display
191 double var_values[VAR_VARS_NB];
195 AVLFG prng; ///< random
196 char *tc_opt_string; ///< specified timecode option string
197 AVRational tc_rate; ///< frame rate for timecode
198 AVTimecode tc; ///< timecode context
199 int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
200 int reload; ///< reload text file for each frame
201 int start_number; ///< starting frame number for n/frame_num var
202 #if CONFIG_LIBFRIBIDI
203 int text_shaping; ///< 1 to shape the text before drawing it
205 AVDictionary *metadata;
208 #define OFFSET(x) offsetof(DrawTextContext, x)
209 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
211 static const AVOption drawtext_options[]= {
212 {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
213 {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
214 {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
215 {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, FLAGS},
216 {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, 0, 0, FLAGS},
217 {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, 0, 0, FLAGS},
218 {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, FLAGS},
219 {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, FLAGS},
220 {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 , FLAGS},
221 {"boxborderw", "set box border width", OFFSET(boxborderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
222 {"line_spacing", "set line spacing in pixels", OFFSET(line_spacing), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX,FLAGS},
223 {"fontsize", "set font size", OFFSET(fontsize_expr), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0 , FLAGS},
224 {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, FLAGS},
225 {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, FLAGS},
226 {"shadowx", "set shadow x offset", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
227 {"shadowy", "set shadow y offset", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
228 {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
229 {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
230 {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
231 #if CONFIG_LIBFONTCONFIG
232 { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
235 {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
236 {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
237 {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
238 {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
240 {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
241 {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
242 {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
243 {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
244 {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
245 {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
246 { "alpha", "apply alpha while rendering", OFFSET(a_expr), AV_OPT_TYPE_STRING, { .str = "1" }, .flags = FLAGS },
247 {"fix_bounds", "check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
248 {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
250 #if CONFIG_LIBFRIBIDI
251 {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
254 /* FT_LOAD_* flags */
255 { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, "ft_load_flags" },
256 { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
257 { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
258 { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
259 { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
260 { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
261 { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
262 { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
263 { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
264 { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
265 { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
266 { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
267 { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
268 { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
269 { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
270 { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
274 AVFILTER_DEFINE_CLASS(drawtext);
276 #undef __FTERRORS_H__
277 #define FT_ERROR_START_LIST {
278 #define FT_ERRORDEF(e, v, s) { (e), (s) },
279 #define FT_ERROR_END_LIST { 0, NULL } };
281 static const struct ft_error {
287 #define FT_ERRMSG(e) ft_errors[e].err_msg
289 typedef struct Glyph {
291 FT_Glyph border_glyph;
293 unsigned int fontsize;
294 FT_Bitmap bitmap; ///< array holding bitmaps of font
295 FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
302 static int glyph_cmp(const void *key, const void *b)
304 const Glyph *a = key, *bb = b;
305 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
308 return diff > 0 ? 1 : -1;
310 return FFDIFFSIGN((int64_t)a->fontsize, (int64_t)bb->fontsize);
314 * Load glyphs corresponding to the UTF-32 codepoint code.
316 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
318 DrawTextContext *s = ctx->priv;
319 FT_BitmapGlyph bitmapglyph;
321 struct AVTreeNode *node = NULL;
324 /* load glyph into s->face->glyph */
325 if (FT_Load_Char(s->face, code, s->ft_load_flags))
326 return AVERROR(EINVAL);
328 glyph = av_mallocz(sizeof(*glyph));
330 ret = AVERROR(ENOMEM);
334 glyph->fontsize = s->fontsize;
336 if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
337 ret = AVERROR(EINVAL);
341 glyph->border_glyph = glyph->glyph;
342 if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
343 FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
344 ret = AVERROR_EXTERNAL;
347 bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
348 glyph->border_bitmap = bitmapglyph->bitmap;
350 if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
351 ret = AVERROR_EXTERNAL;
354 bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
356 glyph->bitmap = bitmapglyph->bitmap;
357 glyph->bitmap_left = bitmapglyph->left;
358 glyph->bitmap_top = bitmapglyph->top;
359 glyph->advance = s->face->glyph->advance.x >> 6;
361 /* measure text height to calculate text_height (or the maximum text height) */
362 FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
364 /* cache the newly created glyph */
365 if (!(node = av_tree_node_alloc())) {
366 ret = AVERROR(ENOMEM);
369 av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
377 av_freep(&glyph->glyph);
384 static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
387 DrawTextContext *s = ctx->priv;
389 if ((err = FT_Set_Pixel_Sizes(s->face, 0, fontsize))) {
390 av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
391 fontsize, FT_ERRMSG(err));
392 return AVERROR(EINVAL);
395 s->fontsize = fontsize;
400 static av_cold int parse_fontsize(AVFilterContext *ctx)
402 DrawTextContext *s = ctx->priv;
405 if (s->fontsize_pexpr)
408 if (s->fontsize_expr == NULL)
409 return AVERROR(EINVAL);
411 if ((err = av_expr_parse(&s->fontsize_pexpr, s->fontsize_expr, var_names,
412 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
418 static av_cold int update_fontsize(AVFilterContext *ctx)
420 DrawTextContext *s = ctx->priv;
421 unsigned int fontsize = s->default_fontsize;
423 double size, roundedsize;
425 // if no fontsize specified use the default
426 if (s->fontsize_expr != NULL) {
427 if ((err = parse_fontsize(ctx)) < 0)
430 size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
433 roundedsize = round(size);
434 // test for overflow before cast
435 if (!(roundedsize > INT_MIN && roundedsize < INT_MAX)) {
436 av_log(ctx, AV_LOG_ERROR, "fontsize overflow\n");
437 return AVERROR(EINVAL);
440 fontsize = roundedsize;
448 if (fontsize == s->fontsize)
451 return set_fontsize(ctx, fontsize);
454 static int load_font_file(AVFilterContext *ctx, const char *path, int index)
456 DrawTextContext *s = ctx->priv;
459 err = FT_New_Face(s->library, path, index, &s->face);
461 #if !CONFIG_LIBFONTCONFIG
462 av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
463 s->fontfile, FT_ERRMSG(err));
465 return AVERROR(EINVAL);
470 #if CONFIG_LIBFONTCONFIG
471 static int load_font_fontconfig(AVFilterContext *ctx)
473 DrawTextContext *s = ctx->priv;
474 FcConfig *fontconfig;
475 FcPattern *pat, *best;
476 FcResult result = FcResultMatch;
480 int err = AVERROR(ENOENT);
483 fontconfig = FcInitLoadConfigAndFonts();
485 av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
486 return AVERROR_UNKNOWN;
488 pat = FcNameParse(s->fontfile ? s->fontfile :
489 (uint8_t *)(intptr_t)"default");
491 av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
492 return AVERROR(EINVAL);
495 FcPatternAddString(pat, FC_FAMILY, s->font);
497 parse_err = parse_fontsize(ctx);
499 double size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
502 av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
503 return AVERROR(EINVAL);
506 FcPatternAddDouble(pat, FC_SIZE, size);
509 FcDefaultSubstitute(pat);
511 if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
512 av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
513 FcPatternDestroy(pat);
514 return AVERROR(ENOMEM);
517 best = FcFontMatch(fontconfig, pat, &result);
518 FcPatternDestroy(pat);
520 if (!best || result != FcResultMatch) {
521 av_log(ctx, AV_LOG_ERROR,
522 "Cannot find a valid font for the family %s\n",
528 FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
529 FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
530 av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
531 return AVERROR(EINVAL);
534 if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
535 av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
540 av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
542 s->default_fontsize = size + 0.5;
544 err = load_font_file(ctx, filename, index);
547 FcConfigDestroy(fontconfig);
549 FcPatternDestroy(best);
554 static int load_font(AVFilterContext *ctx)
556 DrawTextContext *s = ctx->priv;
559 /* load the face, and set up the encoding, which is by default UTF-8 */
560 err = load_font_file(ctx, s->fontfile, 0);
563 #if CONFIG_LIBFONTCONFIG
564 err = load_font_fontconfig(ctx);
571 static inline int is_newline(uint32_t c)
573 return c == '\n' || c == '\r' || c == '\f' || c == '\v';
576 static int load_textfile(AVFilterContext *ctx)
578 DrawTextContext *s = ctx->priv;
584 if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
585 av_log(ctx, AV_LOG_ERROR,
586 "The text file '%s' could not be read or is empty\n",
591 if (textbuf_size > 0 && is_newline(textbuf[textbuf_size - 1]))
593 if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
594 av_file_unmap(textbuf, textbuf_size);
595 return AVERROR(ENOMEM);
598 memcpy(s->text, textbuf, textbuf_size);
599 s->text[textbuf_size] = 0;
600 av_file_unmap(textbuf, textbuf_size);
605 #if CONFIG_LIBFRIBIDI
606 static int shape_text(AVFilterContext *ctx)
608 DrawTextContext *s = ctx->priv;
610 int ret = AVERROR(ENOMEM);
611 static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
612 FRIBIDI_FLAGS_ARABIC;
613 FriBidiChar *unicodestr = NULL;
615 FriBidiParType direction = FRIBIDI_PAR_LTR;
616 FriBidiStrIndex line_start = 0;
617 FriBidiStrIndex line_end = 0;
618 FriBidiLevel *embedding_levels = NULL;
619 FriBidiArabicProp *ar_props = NULL;
620 FriBidiCharType *bidi_types = NULL;
623 len = strlen(s->text);
624 if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
627 len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
628 s->text, len, unicodestr);
630 bidi_types = av_malloc_array(len, sizeof(*bidi_types));
635 fribidi_get_bidi_types(unicodestr, len, bidi_types);
637 embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
638 if (!embedding_levels) {
642 if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
647 ar_props = av_malloc_array(len, sizeof(*ar_props));
652 fribidi_get_joining_types(unicodestr, len, ar_props);
653 fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
654 fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
656 for (line_end = 0, line_start = 0; line_end < len; line_end++) {
657 if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
658 if (!fribidi_reorder_line(flags, bidi_types,
659 line_end - line_start + 1, line_start,
660 direction, embedding_levels, unicodestr,
664 line_start = line_end + 1;
668 /* Remove zero-width fill chars put in by libfribidi */
669 for (i = 0, j = 0; i < len; i++)
670 if (unicodestr[i] != FRIBIDI_CHAR_FILL)
671 unicodestr[j++] = unicodestr[i];
674 if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
675 /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
680 len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
681 unicodestr, len, s->text);
686 av_free(embedding_levels);
693 static av_cold int init(AVFilterContext *ctx)
696 DrawTextContext *s = ctx->priv;
699 av_expr_free(s->fontsize_pexpr);
700 s->fontsize_pexpr = NULL;
703 s->default_fontsize = 16;
705 if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
706 av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
707 return AVERROR(EINVAL);
712 av_log(ctx, AV_LOG_ERROR,
713 "Both text and text file provided. Please provide only one\n");
714 return AVERROR(EINVAL);
716 if ((err = load_textfile(ctx)) < 0)
720 if (s->reload && !s->textfile)
721 av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
723 if (s->tc_opt_string) {
724 int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
725 s->tc_opt_string, ctx);
729 s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
731 s->text = av_strdup("");
735 av_log(ctx, AV_LOG_ERROR,
736 "Either text, a valid file or a timecode must be provided\n");
737 return AVERROR(EINVAL);
740 #if CONFIG_LIBFRIBIDI
742 if ((err = shape_text(ctx)) < 0)
746 if ((err = FT_Init_FreeType(&(s->library)))) {
747 av_log(ctx, AV_LOG_ERROR,
748 "Could not load FreeType: %s\n", FT_ERRMSG(err));
749 return AVERROR(EINVAL);
752 if ((err = load_font(ctx)) < 0)
755 if ((err = update_fontsize(ctx)) < 0)
759 if (FT_Stroker_New(s->library, &s->stroker)) {
760 av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
761 return AVERROR_EXTERNAL;
763 FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
764 FT_STROKER_LINEJOIN_ROUND, 0);
767 s->use_kerning = FT_HAS_KERNING(s->face);
769 /* load the fallback glyph with code 0 */
770 load_glyph(ctx, NULL, 0);
772 /* set the tabsize in pixels */
773 if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
774 av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
777 s->tabsize *= glyph->advance;
779 if (s->exp_mode == EXP_STRFTIME &&
780 (strchr(s->text, '%') || strchr(s->text, '\\')))
781 av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
783 av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
784 av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
789 static int query_formats(AVFilterContext *ctx)
791 return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
794 static int glyph_enu_free(void *opaque, void *elem)
798 FT_Done_Glyph(glyph->glyph);
799 FT_Done_Glyph(glyph->border_glyph);
804 static av_cold void uninit(AVFilterContext *ctx)
806 DrawTextContext *s = ctx->priv;
808 av_expr_free(s->x_pexpr);
809 av_expr_free(s->y_pexpr);
810 av_expr_free(s->a_pexpr);
811 av_expr_free(s->fontsize_pexpr);
813 s->x_pexpr = s->y_pexpr = s->a_pexpr = s->fontsize_pexpr = NULL;
815 av_freep(&s->positions);
818 av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
819 av_tree_destroy(s->glyphs);
822 FT_Done_Face(s->face);
823 FT_Stroker_Done(s->stroker);
824 FT_Done_FreeType(s->library);
826 av_bprint_finalize(&s->expanded_text, NULL);
827 av_bprint_finalize(&s->expanded_fontcolor, NULL);
830 static int config_input(AVFilterLink *inlink)
832 AVFilterContext *ctx = inlink->dst;
833 DrawTextContext *s = ctx->priv;
837 ff_draw_init(&s->dc, inlink->format, FF_DRAW_PROCESS_ALPHA);
838 ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
839 ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
840 ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
841 ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
843 s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
844 s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
845 s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
846 s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
847 s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
848 s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
849 s->var_values[VAR_X] = NAN;
850 s->var_values[VAR_Y] = NAN;
851 s->var_values[VAR_T] = NAN;
853 av_lfg_init(&s->prng, av_get_random_seed());
855 av_expr_free(s->x_pexpr);
856 av_expr_free(s->y_pexpr);
857 av_expr_free(s->a_pexpr);
858 s->x_pexpr = s->y_pexpr = s->a_pexpr = NULL;
860 if ((ret = av_expr_parse(&s->x_pexpr, expr = s->x_expr, var_names,
861 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
862 (ret = av_expr_parse(&s->y_pexpr, expr = s->y_expr, var_names,
863 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
864 (ret = av_expr_parse(&s->a_pexpr, expr = s->a_expr, var_names,
865 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0) {
866 av_log(ctx, AV_LOG_ERROR, "Failed to parse expression: %s \n", expr);
867 return AVERROR(EINVAL);
873 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
875 DrawTextContext *old = ctx->priv;
876 DrawTextContext *new = NULL;
879 if (!strcmp(cmd, "reinit")) {
880 new = av_mallocz(sizeof(DrawTextContext));
882 return AVERROR(ENOMEM);
884 new->class = &drawtext_class;
885 ret = av_opt_copy(new, old);
890 ret = av_set_options_string(ctx, arg, "=", ":");
910 return config_input(ctx->inputs[0]);
912 return AVERROR(ENOSYS);
915 av_log(ctx, AV_LOG_ERROR, "Failed to process command. Continuing with existing parameters.\n");
920 static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
921 char *fct, unsigned argc, char **argv, int tag)
923 DrawTextContext *s = ctx->priv;
925 av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
929 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
930 char *fct, unsigned argc, char **argv, int tag)
932 DrawTextContext *s = ctx->priv;
934 double pts = s->var_values[VAR_T];
937 fmt = argc >= 1 ? argv[0] : "flt";
940 if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
941 av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
944 pts += (double)delta / AV_TIME_BASE;
946 if (!strcmp(fmt, "flt")) {
947 av_bprintf(bp, "%.6f", pts);
948 } else if (!strcmp(fmt, "hms")) {
950 av_bprintf(bp, " ??:??:??.???");
952 int64_t ms = llrint(pts * 1000);
959 if (!strcmp(argv[2], "24HH")) {
960 ms %= 24 * 60 * 60 * 1000;
962 av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s'\n", argv[2]);
963 return AVERROR(EINVAL);
966 av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
967 (int)(ms / (60 * 60 * 1000)),
968 (int)(ms / (60 * 1000)) % 60,
969 (int)(ms / 1000) % 60,
972 } else if (!strcmp(fmt, "localtime") ||
973 !strcmp(fmt, "gmtime")) {
975 time_t ms = (time_t)pts;
976 const char *timefmt = argc >= 3 ? argv[2] : "%Y-%m-%d %H:%M:%S";
977 if (!strcmp(fmt, "localtime"))
978 localtime_r(&ms, &tm);
981 av_bprint_strftime(bp, timefmt, &tm);
983 av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
984 return AVERROR(EINVAL);
989 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
990 char *fct, unsigned argc, char **argv, int tag)
992 DrawTextContext *s = ctx->priv;
994 av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
998 static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
999 char *fct, unsigned argc, char **argv, int tag)
1001 DrawTextContext *s = ctx->priv;
1002 AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
1005 av_bprintf(bp, "%s", e->value);
1007 av_bprintf(bp, "%s", argv[1]);
1011 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
1012 char *fct, unsigned argc, char **argv, int tag)
1014 const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
1020 localtime_r(&now, &tm);
1022 tm = *gmtime_r(&now, &tm);
1023 av_bprint_strftime(bp, fmt, &tm);
1027 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
1028 char *fct, unsigned argc, char **argv, int tag)
1030 DrawTextContext *s = ctx->priv;
1034 ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
1035 NULL, NULL, fun2_names, fun2,
1038 av_log(ctx, AV_LOG_ERROR,
1039 "Expression '%s' for the expr text expansion function is not valid\n",
1042 av_bprintf(bp, "%f", res);
1047 static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
1048 char *fct, unsigned argc, char **argv, int tag)
1050 DrawTextContext *s = ctx->priv;
1054 unsigned int positions = 0;
1055 char fmt_str[30] = "%";
1058 * argv[0] expression to be converted to `int`
1059 * argv[1] format: 'x', 'X', 'd' or 'u'
1060 * argv[2] positions printed (optional)
1063 ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
1064 NULL, NULL, fun2_names, fun2,
1067 av_log(ctx, AV_LOG_ERROR,
1068 "Expression '%s' for the expr text expansion function is not valid\n",
1073 if (!strchr("xXdu", argv[1][0])) {
1074 av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
1075 " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
1076 return AVERROR(EINVAL);
1080 ret = sscanf(argv[2], "%u", &positions);
1082 av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
1083 " to print: '%s'\n", argv[2]);
1084 return AVERROR(EINVAL);
1088 feclearexcept(FE_ALL_EXCEPT);
1090 #if defined(FE_INVALID) && defined(FE_OVERFLOW) && defined(FE_UNDERFLOW)
1091 if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
1092 av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
1093 return AVERROR(EINVAL);
1098 av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
1099 av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
1101 av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
1102 res, argv[0], fmt_str);
1104 av_bprintf(bp, fmt_str, intval);
1109 static const struct drawtext_function {
1111 unsigned argc_min, argc_max;
1112 int tag; /**< opaque argument to func */
1113 int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
1115 { "expr", 1, 1, 0, func_eval_expr },
1116 { "e", 1, 1, 0, func_eval_expr },
1117 { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
1118 { "eif", 2, 3, 0, func_eval_expr_int_format },
1119 { "pict_type", 0, 0, 0, func_pict_type },
1120 { "pts", 0, 3, 0, func_pts },
1121 { "gmtime", 0, 1, 'G', func_strftime },
1122 { "localtime", 0, 1, 'L', func_strftime },
1123 { "frame_num", 0, 0, 0, func_frame_num },
1124 { "n", 0, 0, 0, func_frame_num },
1125 { "metadata", 1, 2, 0, func_metadata },
1128 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
1129 unsigned argc, char **argv)
1133 for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
1134 if (strcmp(fct, functions[i].name))
1136 if (argc < functions[i].argc_min) {
1137 av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
1138 fct, functions[i].argc_min);
1139 return AVERROR(EINVAL);
1141 if (argc > functions[i].argc_max) {
1142 av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
1143 fct, functions[i].argc_max);
1144 return AVERROR(EINVAL);
1148 if (i >= FF_ARRAY_ELEMS(functions)) {
1149 av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
1150 return AVERROR(EINVAL);
1152 return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
1155 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
1157 const char *text = *rtext;
1158 char *argv[16] = { NULL };
1159 unsigned argc = 0, i;
1163 av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
1164 return AVERROR(EINVAL);
1168 if (!(argv[argc++] = av_get_token(&text, ":}"))) {
1169 ret = AVERROR(ENOMEM);
1173 av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
1174 ret = AVERROR(EINVAL);
1177 if (argc == FF_ARRAY_ELEMS(argv))
1178 av_freep(&argv[--argc]); /* error will be caught later */
1184 if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
1187 *rtext = (char *)text + 1;
1190 for (i = 0; i < argc; i++)
1195 static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
1199 av_bprint_clear(bp);
1201 if (*text == '\\' && text[1]) {
1202 av_bprint_chars(bp, text[1], 1);
1204 } else if (*text == '%') {
1206 if ((ret = expand_function(ctx, bp, &text)) < 0)
1209 av_bprint_chars(bp, *text, 1);
1213 if (!av_bprint_is_complete(bp))
1214 return AVERROR(ENOMEM);
1218 static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
1219 int width, int height,
1221 int x, int y, int borderw)
1223 char *text = s->expanded_text.str;
1227 Glyph *glyph = NULL;
1229 for (i = 0, p = text; *p; i++) {
1231 Glyph dummy = { 0 };
1232 GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_invalid;);
1233 continue_on_invalid:
1235 /* skip new line chars, just go to new line */
1236 if (code == '\n' || code == '\r' || code == '\t')
1240 dummy.fontsize = s->fontsize;
1241 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1243 bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
1245 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
1246 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
1247 return AVERROR(EINVAL);
1249 x1 = s->positions[i].x+s->x+x - borderw;
1250 y1 = s->positions[i].y+s->y+y - borderw;
1252 ff_blend_mask(&s->dc, color,
1253 frame->data, frame->linesize, width, height,
1254 bitmap.buffer, bitmap.pitch,
1255 bitmap.width, bitmap.rows,
1256 bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
1264 static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
1267 color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
1268 ff_draw_color(&s->dc, color, color->rgba);
1271 static void update_alpha(DrawTextContext *s)
1273 double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
1280 else if (alpha <= 0)
1283 s->alpha = 256 * alpha;
1286 static int draw_text(AVFilterContext *ctx, AVFrame *frame,
1287 int width, int height)
1289 DrawTextContext *s = ctx->priv;
1290 AVFilterLink *inlink = ctx->inputs[0];
1292 uint32_t code = 0, prev_code = 0;
1293 int x = 0, y = 0, i = 0, ret;
1294 int max_text_line_w = 0, len;
1298 int y_min = 32000, y_max = -32000;
1299 int x_min = 32000, x_max = -32000;
1301 Glyph *glyph = NULL, *prev_glyph = NULL;
1302 Glyph dummy = { 0 };
1304 time_t now = time(0);
1306 AVBPrint *bp = &s->expanded_text;
1308 FFDrawColor fontcolor;
1309 FFDrawColor shadowcolor;
1310 FFDrawColor bordercolor;
1311 FFDrawColor boxcolor;
1313 av_bprint_clear(bp);
1315 if(s->basetime != AV_NOPTS_VALUE)
1316 now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
1318 switch (s->exp_mode) {
1320 av_bprintf(bp, "%s", s->text);
1323 if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
1327 localtime_r(&now, <ime);
1328 av_bprint_strftime(bp, s->text, <ime);
1332 if (s->tc_opt_string) {
1333 char tcbuf[AV_TIMECODE_STR_SIZE];
1334 av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count_out);
1335 av_bprint_clear(bp);
1336 av_bprintf(bp, "%s%s", s->text, tcbuf);
1339 if (!av_bprint_is_complete(bp))
1340 return AVERROR(ENOMEM);
1341 text = s->expanded_text.str;
1342 if ((len = s->expanded_text.len) > s->nb_positions) {
1343 if (!(s->positions =
1344 av_realloc(s->positions, len*sizeof(*s->positions))))
1345 return AVERROR(ENOMEM);
1346 s->nb_positions = len;
1349 if (s->fontcolor_expr[0]) {
1350 /* If expression is set, evaluate and replace the static value */
1351 av_bprint_clear(&s->expanded_fontcolor);
1352 if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
1354 if (!av_bprint_is_complete(&s->expanded_fontcolor))
1355 return AVERROR(ENOMEM);
1356 av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
1357 ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
1360 ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
1366 if ((ret = update_fontsize(ctx)) < 0)
1369 /* load and cache glyphs */
1370 for (i = 0, p = text; *p; i++) {
1371 GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_invalid;);
1372 continue_on_invalid:
1376 dummy.fontsize = s->fontsize;
1377 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1379 ret = load_glyph(ctx, &glyph, code);
1384 y_min = FFMIN(glyph->bbox.yMin, y_min);
1385 y_max = FFMAX(glyph->bbox.yMax, y_max);
1386 x_min = FFMIN(glyph->bbox.xMin, x_min);
1387 x_max = FFMAX(glyph->bbox.xMax, x_max);
1389 s->max_glyph_h = y_max - y_min;
1390 s->max_glyph_w = x_max - x_min;
1392 /* compute and save position for each glyph */
1394 for (i = 0, p = text; *p; i++) {
1395 GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_invalid2;);
1396 continue_on_invalid2:
1398 /* skip the \n in the sequence \r\n */
1399 if (prev_code == '\r' && code == '\n')
1403 if (is_newline(code)) {
1405 max_text_line_w = FFMAX(max_text_line_w, x);
1406 y += s->max_glyph_h + s->line_spacing;
1414 dummy.fontsize = s->fontsize;
1415 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1418 if (s->use_kerning && prev_glyph && glyph->code) {
1419 FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
1420 ft_kerning_default, &delta);
1425 s->positions[i].x = x + glyph->bitmap_left;
1426 s->positions[i].y = y - glyph->bitmap_top + y_max;
1427 if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
1428 else x += glyph->advance;
1431 max_text_line_w = FFMAX(x, max_text_line_w);
1433 s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
1434 s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
1436 s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
1437 s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
1438 s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
1439 s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
1441 s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
1443 s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1444 s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
1445 /* It is necessary if x is expressed from y */
1446 s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1449 update_color_with_alpha(s, &fontcolor , s->fontcolor );
1450 update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
1451 update_color_with_alpha(s, &bordercolor, s->bordercolor);
1452 update_color_with_alpha(s, &boxcolor , s->boxcolor );
1454 box_w = max_text_line_w;
1455 box_h = y + s->max_glyph_h;
1457 if (s->fix_bounds) {
1459 /* calculate footprint of text effects */
1460 int boxoffset = s->draw_box ? FFMAX(s->boxborderw, 0) : 0;
1461 int borderoffset = s->borderw ? FFMAX(s->borderw, 0) : 0;
1463 int offsetleft = FFMAX3(boxoffset, borderoffset,
1464 (s->shadowx < 0 ? FFABS(s->shadowx) : 0));
1465 int offsettop = FFMAX3(boxoffset, borderoffset,
1466 (s->shadowy < 0 ? FFABS(s->shadowy) : 0));
1468 int offsetright = FFMAX3(boxoffset, borderoffset,
1469 (s->shadowx > 0 ? s->shadowx : 0));
1470 int offsetbottom = FFMAX3(boxoffset, borderoffset,
1471 (s->shadowy > 0 ? s->shadowy : 0));
1474 if (s->x - offsetleft < 0) s->x = offsetleft;
1475 if (s->y - offsettop < 0) s->y = offsettop;
1477 if (s->x + box_w + offsetright > width)
1478 s->x = FFMAX(width - box_w - offsetright, 0);
1479 if (s->y + box_h + offsetbottom > height)
1480 s->y = FFMAX(height - box_h - offsetbottom, 0);
1485 ff_blend_rectangle(&s->dc, &boxcolor,
1486 frame->data, frame->linesize, width, height,
1487 s->x - s->boxborderw, s->y - s->boxborderw,
1488 box_w + s->boxborderw * 2, box_h + s->boxborderw * 2);
1490 if (s->shadowx || s->shadowy) {
1491 if ((ret = draw_glyphs(s, frame, width, height,
1492 &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
1497 if ((ret = draw_glyphs(s, frame, width, height,
1498 &bordercolor, 0, 0, s->borderw)) < 0)
1501 if ((ret = draw_glyphs(s, frame, width, height,
1502 &fontcolor, 0, 0, 0)) < 0)
1508 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
1510 AVFilterContext *ctx = inlink->dst;
1511 AVFilterLink *outlink = ctx->outputs[0];
1512 DrawTextContext *s = ctx->priv;
1516 if ((ret = load_textfile(ctx)) < 0) {
1517 av_frame_free(&frame);
1520 #if CONFIG_LIBFRIBIDI
1521 if (s->text_shaping)
1522 if ((ret = shape_text(ctx)) < 0) {
1523 av_frame_free(&frame);
1529 s->var_values[VAR_N] = inlink->frame_count_out + s->start_number;
1530 s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
1531 NAN : frame->pts * av_q2d(inlink->time_base);
1533 s->var_values[VAR_PICT_TYPE] = frame->pict_type;
1534 s->var_values[VAR_PKT_POS] = frame->pkt_pos;
1535 s->var_values[VAR_PKT_DURATION] = frame->pkt_duration * av_q2d(inlink->time_base);
1536 s->var_values[VAR_PKT_SIZE] = frame->pkt_size;
1537 s->metadata = frame->metadata;
1539 draw_text(ctx, frame, frame->width, frame->height);
1541 av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
1542 (int)s->var_values[VAR_N], s->var_values[VAR_T],
1543 (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
1546 return ff_filter_frame(outlink, frame);
1549 static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
1552 .type = AVMEDIA_TYPE_VIDEO,
1553 .filter_frame = filter_frame,
1554 .config_props = config_input,
1555 .needs_writable = 1,
1560 static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
1563 .type = AVMEDIA_TYPE_VIDEO,
1568 const AVFilter ff_vf_drawtext = {
1570 .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1571 .priv_size = sizeof(DrawTextContext),
1572 .priv_class = &drawtext_class,
1575 .query_formats = query_formats,
1576 .inputs = avfilter_vf_drawtext_inputs,
1577 .outputs = avfilter_vf_drawtext_outputs,
1578 .process_command = command,
1579 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,