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
94 static const char *const fun2_names[] = {
98 static double drand(void *opaque, double min, double max)
100 return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
103 typedef double (*eval_func2)(void *, double a, double b);
105 static const eval_func2 fun2[] = {
114 VAR_MAIN_H, VAR_h, VAR_H,
115 VAR_MAIN_W, VAR_w, VAR_W,
116 VAR_MAX_GLYPH_A, VAR_ASCENT,
117 VAR_MAX_GLYPH_D, VAR_DESCENT,
131 enum expansion_mode {
137 typedef struct DrawTextContext {
138 const AVClass *class;
139 int exp_mode; ///< expansion mode to use for the text
140 int reinit; ///< tells if the filter is being reinited
141 #if CONFIG_LIBFONTCONFIG
142 uint8_t *font; ///< font to be used
144 uint8_t *fontfile; ///< font to be used
145 uint8_t *text; ///< text to be drawn
146 AVBPrint expanded_text; ///< used to contain the expanded text
147 uint8_t *fontcolor_expr; ///< fontcolor expression to evaluate
148 AVBPrint expanded_fontcolor; ///< used to contain the expanded fontcolor spec
149 int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
150 FT_Vector *positions; ///< positions for each element in the text
151 size_t nb_positions; ///< number of elements of positions array
152 char *textfile; ///< file with text to be drawn
153 int x; ///< x position to start drawing text
154 int y; ///< y position to start drawing text
155 int max_glyph_w; ///< max glyph width
156 int max_glyph_h; ///< max glyph height
157 int shadowx, shadowy;
158 int borderw; ///< border width
159 char *fontsize_expr; ///< expression for fontsize
160 AVExpr *fontsize_pexpr; ///< parsed expressions for fontsize
161 unsigned int fontsize; ///< font size to use
162 unsigned int default_fontsize; ///< default font size to use
164 int line_spacing; ///< lines spacing in pixels
165 short int draw_box; ///< draw box around text - true or false
166 int boxborderw; ///< box border width
167 int use_kerning; ///< font kerning is used - true/false
168 int tabsize; ///< tab size
169 int fix_bounds; ///< do we let it go out of frame bounds - t/f
172 FFDrawColor fontcolor; ///< foreground color
173 FFDrawColor shadowcolor; ///< shadow color
174 FFDrawColor bordercolor; ///< border color
175 FFDrawColor boxcolor; ///< background color
177 FT_Library library; ///< freetype font library handle
178 FT_Face face; ///< freetype font face handle
179 FT_Stroker stroker; ///< freetype stroker handle
180 struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
181 char *x_expr; ///< expression for x position
182 char *y_expr; ///< expression for y position
183 AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
184 int64_t basetime; ///< base pts time in the real world for display
185 double var_values[VAR_VARS_NB];
189 AVLFG prng; ///< random
190 char *tc_opt_string; ///< specified timecode option string
191 AVRational tc_rate; ///< frame rate for timecode
192 AVTimecode tc; ///< timecode context
193 int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
194 int reload; ///< reload text file for each frame
195 int start_number; ///< starting frame number for n/frame_num var
196 #if CONFIG_LIBFRIBIDI
197 int text_shaping; ///< 1 to shape the text before drawing it
199 AVDictionary *metadata;
202 #define OFFSET(x) offsetof(DrawTextContext, x)
203 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
205 static const AVOption drawtext_options[]= {
206 {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
207 {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
208 {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
209 {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
210 {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, CHAR_MIN, CHAR_MAX, FLAGS},
211 {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
212 {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
213 {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
214 {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 , FLAGS},
215 {"boxborderw", "set box border width", OFFSET(boxborderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
216 {"line_spacing", "set line spacing in pixels", OFFSET(line_spacing), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX,FLAGS},
217 {"fontsize", "set font size", OFFSET(fontsize_expr), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX , FLAGS},
218 {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
219 {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
220 {"shadowx", "set shadow x offset", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
221 {"shadowy", "set shadow y offset", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
222 {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
223 {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
224 {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
225 #if CONFIG_LIBFONTCONFIG
226 { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
229 {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
230 {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
231 {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
232 {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
234 {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
235 {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
236 {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
237 {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
238 {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
239 {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
240 { "alpha", "apply alpha while rendering", OFFSET(a_expr), AV_OPT_TYPE_STRING, { .str = "1" }, .flags = FLAGS },
241 {"fix_bounds", "check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
242 {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
244 #if CONFIG_LIBFRIBIDI
245 {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
248 /* FT_LOAD_* flags */
249 { "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" },
250 { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
251 { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
252 { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
253 { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
254 { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
255 { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
256 { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
257 { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
258 { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
259 { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
260 { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
261 { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
262 { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
263 { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
264 { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
268 AVFILTER_DEFINE_CLASS(drawtext);
270 #undef __FTERRORS_H__
271 #define FT_ERROR_START_LIST {
272 #define FT_ERRORDEF(e, v, s) { (e), (s) },
273 #define FT_ERROR_END_LIST { 0, NULL } };
275 static const struct ft_error {
281 #define FT_ERRMSG(e) ft_errors[e].err_msg
283 typedef struct Glyph {
285 FT_Glyph border_glyph;
287 unsigned int fontsize;
288 FT_Bitmap bitmap; ///< array holding bitmaps of font
289 FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
296 static int glyph_cmp(const void *key, const void *b)
298 const Glyph *a = key, *bb = b;
299 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
302 return diff > 0 ? 1 : -1;
304 return FFDIFFSIGN((int64_t)a->fontsize, (int64_t)bb->fontsize);
308 * Load glyphs corresponding to the UTF-32 codepoint code.
310 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
312 DrawTextContext *s = ctx->priv;
313 FT_BitmapGlyph bitmapglyph;
315 struct AVTreeNode *node = NULL;
318 /* load glyph into s->face->glyph */
319 if (FT_Load_Char(s->face, code, s->ft_load_flags))
320 return AVERROR(EINVAL);
322 glyph = av_mallocz(sizeof(*glyph));
324 ret = AVERROR(ENOMEM);
328 glyph->fontsize = s->fontsize;
330 if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
331 ret = AVERROR(EINVAL);
335 glyph->border_glyph = glyph->glyph;
336 if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
337 FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
338 ret = AVERROR_EXTERNAL;
341 bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
342 glyph->border_bitmap = bitmapglyph->bitmap;
344 if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
345 ret = AVERROR_EXTERNAL;
348 bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
350 glyph->bitmap = bitmapglyph->bitmap;
351 glyph->bitmap_left = bitmapglyph->left;
352 glyph->bitmap_top = bitmapglyph->top;
353 glyph->advance = s->face->glyph->advance.x >> 6;
355 /* measure text height to calculate text_height (or the maximum text height) */
356 FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
358 /* cache the newly created glyph */
359 if (!(node = av_tree_node_alloc())) {
360 ret = AVERROR(ENOMEM);
363 av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
371 av_freep(&glyph->glyph);
378 static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
381 DrawTextContext *s = ctx->priv;
383 if ((err = FT_Set_Pixel_Sizes(s->face, 0, fontsize))) {
384 av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
385 fontsize, FT_ERRMSG(err));
386 return AVERROR(EINVAL);
389 s->fontsize = fontsize;
394 static av_cold int parse_fontsize(AVFilterContext *ctx)
396 DrawTextContext *s = ctx->priv;
399 if (s->fontsize_pexpr)
402 if (s->fontsize_expr == NULL)
403 return AVERROR(EINVAL);
405 if ((err = av_expr_parse(&s->fontsize_pexpr, s->fontsize_expr, var_names,
406 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
412 static av_cold int update_fontsize(AVFilterContext *ctx)
414 DrawTextContext *s = ctx->priv;
415 unsigned int fontsize = s->default_fontsize;
417 double size, roundedsize;
419 // if no fontsize specified use the default
420 if (s->fontsize_expr != NULL) {
421 if ((err = parse_fontsize(ctx)) < 0)
424 size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
427 roundedsize = round(size);
428 // test for overflow before cast
429 if (!(roundedsize > INT_MIN && roundedsize < INT_MAX)) {
430 av_log(ctx, AV_LOG_ERROR, "fontsize overflow\n");
431 return AVERROR(EINVAL);
434 fontsize = roundedsize;
442 if (fontsize == s->fontsize)
445 return set_fontsize(ctx, fontsize);
448 static int load_font_file(AVFilterContext *ctx, const char *path, int index)
450 DrawTextContext *s = ctx->priv;
453 err = FT_New_Face(s->library, path, index, &s->face);
455 #if !CONFIG_LIBFONTCONFIG
456 av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
457 s->fontfile, FT_ERRMSG(err));
459 return AVERROR(EINVAL);
464 #if CONFIG_LIBFONTCONFIG
465 static int load_font_fontconfig(AVFilterContext *ctx)
467 DrawTextContext *s = ctx->priv;
468 FcConfig *fontconfig;
469 FcPattern *pat, *best;
470 FcResult result = FcResultMatch;
474 int err = AVERROR(ENOENT);
477 fontconfig = FcInitLoadConfigAndFonts();
479 av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
480 return AVERROR_UNKNOWN;
482 pat = FcNameParse(s->fontfile ? s->fontfile :
483 (uint8_t *)(intptr_t)"default");
485 av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
486 return AVERROR(EINVAL);
489 FcPatternAddString(pat, FC_FAMILY, s->font);
491 parse_err = parse_fontsize(ctx);
493 double size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
496 av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
497 return AVERROR(EINVAL);
500 FcPatternAddDouble(pat, FC_SIZE, size);
503 FcDefaultSubstitute(pat);
505 if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
506 av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
507 FcPatternDestroy(pat);
508 return AVERROR(ENOMEM);
511 best = FcFontMatch(fontconfig, pat, &result);
512 FcPatternDestroy(pat);
514 if (!best || result != FcResultMatch) {
515 av_log(ctx, AV_LOG_ERROR,
516 "Cannot find a valid font for the family %s\n",
522 FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
523 FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
524 av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
525 return AVERROR(EINVAL);
528 if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
529 av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
534 av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
536 s->default_fontsize = size + 0.5;
538 err = load_font_file(ctx, filename, index);
541 FcConfigDestroy(fontconfig);
543 FcPatternDestroy(best);
548 static int load_font(AVFilterContext *ctx)
550 DrawTextContext *s = ctx->priv;
553 /* load the face, and set up the encoding, which is by default UTF-8 */
554 err = load_font_file(ctx, s->fontfile, 0);
557 #if CONFIG_LIBFONTCONFIG
558 err = load_font_fontconfig(ctx);
565 static int load_textfile(AVFilterContext *ctx)
567 DrawTextContext *s = ctx->priv;
573 if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
574 av_log(ctx, AV_LOG_ERROR,
575 "The text file '%s' could not be read or is empty\n",
580 if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
581 av_file_unmap(textbuf, textbuf_size);
582 return AVERROR(ENOMEM);
585 memcpy(s->text, textbuf, textbuf_size);
586 s->text[textbuf_size] = 0;
587 av_file_unmap(textbuf, textbuf_size);
592 static inline int is_newline(uint32_t c)
594 return c == '\n' || c == '\r' || c == '\f' || c == '\v';
597 #if CONFIG_LIBFRIBIDI
598 static int shape_text(AVFilterContext *ctx)
600 DrawTextContext *s = ctx->priv;
602 int ret = AVERROR(ENOMEM);
603 static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
604 FRIBIDI_FLAGS_ARABIC;
605 FriBidiChar *unicodestr = NULL;
607 FriBidiParType direction = FRIBIDI_PAR_LTR;
608 FriBidiStrIndex line_start = 0;
609 FriBidiStrIndex line_end = 0;
610 FriBidiLevel *embedding_levels = NULL;
611 FriBidiArabicProp *ar_props = NULL;
612 FriBidiCharType *bidi_types = NULL;
615 len = strlen(s->text);
616 if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
619 len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
620 s->text, len, unicodestr);
622 bidi_types = av_malloc_array(len, sizeof(*bidi_types));
627 fribidi_get_bidi_types(unicodestr, len, bidi_types);
629 embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
630 if (!embedding_levels) {
634 if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
639 ar_props = av_malloc_array(len, sizeof(*ar_props));
644 fribidi_get_joining_types(unicodestr, len, ar_props);
645 fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
646 fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
648 for (line_end = 0, line_start = 0; line_end < len; line_end++) {
649 if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
650 if (!fribidi_reorder_line(flags, bidi_types,
651 line_end - line_start + 1, line_start,
652 direction, embedding_levels, unicodestr,
656 line_start = line_end + 1;
660 /* Remove zero-width fill chars put in by libfribidi */
661 for (i = 0, j = 0; i < len; i++)
662 if (unicodestr[i] != FRIBIDI_CHAR_FILL)
663 unicodestr[j++] = unicodestr[i];
666 if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
667 /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
672 len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
673 unicodestr, len, s->text);
678 av_free(embedding_levels);
685 static av_cold int init(AVFilterContext *ctx)
688 DrawTextContext *s = ctx->priv;
691 av_expr_free(s->fontsize_pexpr);
692 s->fontsize_pexpr = NULL;
695 s->default_fontsize = 16;
697 if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
698 av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
699 return AVERROR(EINVAL);
704 av_log(ctx, AV_LOG_ERROR,
705 "Both text and text file provided. Please provide only one\n");
706 return AVERROR(EINVAL);
708 if ((err = load_textfile(ctx)) < 0)
712 if (s->reload && !s->textfile)
713 av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
715 if (s->tc_opt_string) {
716 int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
717 s->tc_opt_string, ctx);
721 s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
723 s->text = av_strdup("");
727 av_log(ctx, AV_LOG_ERROR,
728 "Either text, a valid file or a timecode must be provided\n");
729 return AVERROR(EINVAL);
732 #if CONFIG_LIBFRIBIDI
734 if ((err = shape_text(ctx)) < 0)
738 if ((err = FT_Init_FreeType(&(s->library)))) {
739 av_log(ctx, AV_LOG_ERROR,
740 "Could not load FreeType: %s\n", FT_ERRMSG(err));
741 return AVERROR(EINVAL);
744 if ((err = load_font(ctx)) < 0)
747 if ((err = update_fontsize(ctx)) < 0)
751 if (FT_Stroker_New(s->library, &s->stroker)) {
752 av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
753 return AVERROR_EXTERNAL;
755 FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
756 FT_STROKER_LINEJOIN_ROUND, 0);
759 s->use_kerning = FT_HAS_KERNING(s->face);
761 /* load the fallback glyph with code 0 */
762 load_glyph(ctx, NULL, 0);
764 /* set the tabsize in pixels */
765 if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
766 av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
769 s->tabsize *= glyph->advance;
771 if (s->exp_mode == EXP_STRFTIME &&
772 (strchr(s->text, '%') || strchr(s->text, '\\')))
773 av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
775 av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
776 av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
781 static int query_formats(AVFilterContext *ctx)
783 return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
786 static int glyph_enu_free(void *opaque, void *elem)
790 FT_Done_Glyph(glyph->glyph);
791 FT_Done_Glyph(glyph->border_glyph);
796 static av_cold void uninit(AVFilterContext *ctx)
798 DrawTextContext *s = ctx->priv;
800 av_expr_free(s->x_pexpr);
801 av_expr_free(s->y_pexpr);
802 av_expr_free(s->a_pexpr);
803 av_expr_free(s->fontsize_pexpr);
805 s->x_pexpr = s->y_pexpr = s->a_pexpr = s->fontsize_pexpr = NULL;
807 av_freep(&s->positions);
810 av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
811 av_tree_destroy(s->glyphs);
814 FT_Done_Face(s->face);
815 FT_Stroker_Done(s->stroker);
816 FT_Done_FreeType(s->library);
818 av_bprint_finalize(&s->expanded_text, NULL);
819 av_bprint_finalize(&s->expanded_fontcolor, NULL);
822 static int config_input(AVFilterLink *inlink)
824 AVFilterContext *ctx = inlink->dst;
825 DrawTextContext *s = ctx->priv;
828 ff_draw_init(&s->dc, inlink->format, FF_DRAW_PROCESS_ALPHA);
829 ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
830 ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
831 ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
832 ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
834 s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
835 s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
836 s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
837 s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
838 s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
839 s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
840 s->var_values[VAR_X] = NAN;
841 s->var_values[VAR_Y] = NAN;
842 s->var_values[VAR_T] = NAN;
844 av_lfg_init(&s->prng, av_get_random_seed());
846 av_expr_free(s->x_pexpr);
847 av_expr_free(s->y_pexpr);
848 av_expr_free(s->a_pexpr);
849 s->x_pexpr = s->y_pexpr = s->a_pexpr = NULL;
851 if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
852 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
853 (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
854 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
855 (ret = av_expr_parse(&s->a_pexpr, s->a_expr, var_names,
856 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
858 return AVERROR(EINVAL);
863 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
865 DrawTextContext *s = ctx->priv;
867 if (!strcmp(cmd, "reinit")) {
871 if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
873 if ((ret = init(ctx)) < 0)
875 return config_input(ctx->inputs[0]);
878 return AVERROR(ENOSYS);
881 static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
882 char *fct, unsigned argc, char **argv, int tag)
884 DrawTextContext *s = ctx->priv;
886 av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
890 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
891 char *fct, unsigned argc, char **argv, int tag)
893 DrawTextContext *s = ctx->priv;
895 double pts = s->var_values[VAR_T];
898 fmt = argc >= 1 ? argv[0] : "flt";
901 if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
902 av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
905 pts += (double)delta / AV_TIME_BASE;
907 if (!strcmp(fmt, "flt")) {
908 av_bprintf(bp, "%.6f", pts);
909 } else if (!strcmp(fmt, "hms")) {
911 av_bprintf(bp, " ??:??:??.???");
913 int64_t ms = llrint(pts * 1000);
920 if (!strcmp(argv[2], "24HH")) {
921 ms %= 24 * 60 * 60 * 1000;
923 av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s'\n", argv[2]);
924 return AVERROR(EINVAL);
927 av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
928 (int)(ms / (60 * 60 * 1000)),
929 (int)(ms / (60 * 1000)) % 60,
930 (int)(ms / 1000) % 60,
933 } else if (!strcmp(fmt, "localtime") ||
934 !strcmp(fmt, "gmtime")) {
936 time_t ms = (time_t)pts;
937 const char *timefmt = argc >= 3 ? argv[2] : "%Y-%m-%d %H:%M:%S";
938 if (!strcmp(fmt, "localtime"))
939 localtime_r(&ms, &tm);
942 av_bprint_strftime(bp, timefmt, &tm);
944 av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
945 return AVERROR(EINVAL);
950 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
951 char *fct, unsigned argc, char **argv, int tag)
953 DrawTextContext *s = ctx->priv;
955 av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
959 static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
960 char *fct, unsigned argc, char **argv, int tag)
962 DrawTextContext *s = ctx->priv;
963 AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
966 av_bprintf(bp, "%s", e->value);
968 av_bprintf(bp, "%s", argv[1]);
972 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
973 char *fct, unsigned argc, char **argv, int tag)
975 const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
981 localtime_r(&now, &tm);
983 tm = *gmtime_r(&now, &tm);
984 av_bprint_strftime(bp, fmt, &tm);
988 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
989 char *fct, unsigned argc, char **argv, int tag)
991 DrawTextContext *s = ctx->priv;
995 ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
996 NULL, NULL, fun2_names, fun2,
999 av_log(ctx, AV_LOG_ERROR,
1000 "Expression '%s' for the expr text expansion function is not valid\n",
1003 av_bprintf(bp, "%f", res);
1008 static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
1009 char *fct, unsigned argc, char **argv, int tag)
1011 DrawTextContext *s = ctx->priv;
1015 unsigned int positions = 0;
1016 char fmt_str[30] = "%";
1019 * argv[0] expression to be converted to `int`
1020 * argv[1] format: 'x', 'X', 'd' or 'u'
1021 * argv[2] positions printed (optional)
1024 ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
1025 NULL, NULL, fun2_names, fun2,
1028 av_log(ctx, AV_LOG_ERROR,
1029 "Expression '%s' for the expr text expansion function is not valid\n",
1034 if (!strchr("xXdu", argv[1][0])) {
1035 av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
1036 " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
1037 return AVERROR(EINVAL);
1041 ret = sscanf(argv[2], "%u", &positions);
1043 av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
1044 " to print: '%s'\n", argv[2]);
1045 return AVERROR(EINVAL);
1049 feclearexcept(FE_ALL_EXCEPT);
1051 if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
1052 av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
1053 return AVERROR(EINVAL);
1057 av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
1058 av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
1060 av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
1061 res, argv[0], fmt_str);
1063 av_bprintf(bp, fmt_str, intval);
1068 static const struct drawtext_function {
1070 unsigned argc_min, argc_max;
1071 int tag; /**< opaque argument to func */
1072 int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
1074 { "expr", 1, 1, 0, func_eval_expr },
1075 { "e", 1, 1, 0, func_eval_expr },
1076 { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
1077 { "eif", 2, 3, 0, func_eval_expr_int_format },
1078 { "pict_type", 0, 0, 0, func_pict_type },
1079 { "pts", 0, 3, 0, func_pts },
1080 { "gmtime", 0, 1, 'G', func_strftime },
1081 { "localtime", 0, 1, 'L', func_strftime },
1082 { "frame_num", 0, 0, 0, func_frame_num },
1083 { "n", 0, 0, 0, func_frame_num },
1084 { "metadata", 1, 2, 0, func_metadata },
1087 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
1088 unsigned argc, char **argv)
1092 for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
1093 if (strcmp(fct, functions[i].name))
1095 if (argc < functions[i].argc_min) {
1096 av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
1097 fct, functions[i].argc_min);
1098 return AVERROR(EINVAL);
1100 if (argc > functions[i].argc_max) {
1101 av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
1102 fct, functions[i].argc_max);
1103 return AVERROR(EINVAL);
1107 if (i >= FF_ARRAY_ELEMS(functions)) {
1108 av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
1109 return AVERROR(EINVAL);
1111 return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
1114 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
1116 const char *text = *rtext;
1117 char *argv[16] = { NULL };
1118 unsigned argc = 0, i;
1122 av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
1123 return AVERROR(EINVAL);
1127 if (!(argv[argc++] = av_get_token(&text, ":}"))) {
1128 ret = AVERROR(ENOMEM);
1132 av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
1133 ret = AVERROR(EINVAL);
1136 if (argc == FF_ARRAY_ELEMS(argv))
1137 av_freep(&argv[--argc]); /* error will be caught later */
1143 if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
1146 *rtext = (char *)text + 1;
1149 for (i = 0; i < argc; i++)
1154 static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
1158 av_bprint_clear(bp);
1160 if (*text == '\\' && text[1]) {
1161 av_bprint_chars(bp, text[1], 1);
1163 } else if (*text == '%') {
1165 if ((ret = expand_function(ctx, bp, &text)) < 0)
1168 av_bprint_chars(bp, *text, 1);
1172 if (!av_bprint_is_complete(bp))
1173 return AVERROR(ENOMEM);
1177 static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
1178 int width, int height,
1180 int x, int y, int borderw)
1182 char *text = s->expanded_text.str;
1186 Glyph *glyph = NULL;
1188 for (i = 0, p = text; *p; i++) {
1190 Glyph dummy = { 0 };
1191 GET_UTF8(code, *p++, continue;);
1193 /* skip new line chars, just go to new line */
1194 if (code == '\n' || code == '\r' || code == '\t')
1198 dummy.fontsize = s->fontsize;
1199 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1201 bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
1203 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
1204 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
1205 return AVERROR(EINVAL);
1207 x1 = s->positions[i].x+s->x+x - borderw;
1208 y1 = s->positions[i].y+s->y+y - borderw;
1210 ff_blend_mask(&s->dc, color,
1211 frame->data, frame->linesize, width, height,
1212 bitmap.buffer, bitmap.pitch,
1213 bitmap.width, bitmap.rows,
1214 bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
1222 static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
1225 color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
1226 ff_draw_color(&s->dc, color, color->rgba);
1229 static void update_alpha(DrawTextContext *s)
1231 double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
1238 else if (alpha <= 0)
1241 s->alpha = 256 * alpha;
1244 static int draw_text(AVFilterContext *ctx, AVFrame *frame,
1245 int width, int height)
1247 DrawTextContext *s = ctx->priv;
1248 AVFilterLink *inlink = ctx->inputs[0];
1250 uint32_t code = 0, prev_code = 0;
1251 int x = 0, y = 0, i = 0, ret;
1252 int max_text_line_w = 0, len;
1256 int y_min = 32000, y_max = -32000;
1257 int x_min = 32000, x_max = -32000;
1259 Glyph *glyph = NULL, *prev_glyph = NULL;
1260 Glyph dummy = { 0 };
1262 time_t now = time(0);
1264 AVBPrint *bp = &s->expanded_text;
1266 FFDrawColor fontcolor;
1267 FFDrawColor shadowcolor;
1268 FFDrawColor bordercolor;
1269 FFDrawColor boxcolor;
1271 av_bprint_clear(bp);
1273 if(s->basetime != AV_NOPTS_VALUE)
1274 now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
1276 switch (s->exp_mode) {
1278 av_bprintf(bp, "%s", s->text);
1281 if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
1285 localtime_r(&now, <ime);
1286 av_bprint_strftime(bp, s->text, <ime);
1290 if (s->tc_opt_string) {
1291 char tcbuf[AV_TIMECODE_STR_SIZE];
1292 av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count_out);
1293 av_bprint_clear(bp);
1294 av_bprintf(bp, "%s%s", s->text, tcbuf);
1297 if (!av_bprint_is_complete(bp))
1298 return AVERROR(ENOMEM);
1299 text = s->expanded_text.str;
1300 if ((len = s->expanded_text.len) > s->nb_positions) {
1301 if (!(s->positions =
1302 av_realloc(s->positions, len*sizeof(*s->positions))))
1303 return AVERROR(ENOMEM);
1304 s->nb_positions = len;
1307 if (s->fontcolor_expr[0]) {
1308 /* If expression is set, evaluate and replace the static value */
1309 av_bprint_clear(&s->expanded_fontcolor);
1310 if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
1312 if (!av_bprint_is_complete(&s->expanded_fontcolor))
1313 return AVERROR(ENOMEM);
1314 av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
1315 ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
1318 ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
1324 if ((ret = update_fontsize(ctx)) < 0)
1327 /* load and cache glyphs */
1328 for (i = 0, p = text; *p; i++) {
1329 GET_UTF8(code, *p++, continue;);
1333 dummy.fontsize = s->fontsize;
1334 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1336 ret = load_glyph(ctx, &glyph, code);
1341 y_min = FFMIN(glyph->bbox.yMin, y_min);
1342 y_max = FFMAX(glyph->bbox.yMax, y_max);
1343 x_min = FFMIN(glyph->bbox.xMin, x_min);
1344 x_max = FFMAX(glyph->bbox.xMax, x_max);
1346 s->max_glyph_h = y_max - y_min;
1347 s->max_glyph_w = x_max - x_min;
1349 /* compute and save position for each glyph */
1351 for (i = 0, p = text; *p; i++) {
1352 GET_UTF8(code, *p++, continue;);
1354 /* skip the \n in the sequence \r\n */
1355 if (prev_code == '\r' && code == '\n')
1359 if (is_newline(code)) {
1361 max_text_line_w = FFMAX(max_text_line_w, x);
1362 y += s->max_glyph_h + s->line_spacing;
1370 dummy.fontsize = s->fontsize;
1371 glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1374 if (s->use_kerning && prev_glyph && glyph->code) {
1375 FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
1376 ft_kerning_default, &delta);
1381 s->positions[i].x = x + glyph->bitmap_left;
1382 s->positions[i].y = y - glyph->bitmap_top + y_max;
1383 if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
1384 else x += glyph->advance;
1387 max_text_line_w = FFMAX(x, max_text_line_w);
1389 s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
1390 s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
1392 s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
1393 s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
1394 s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
1395 s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
1397 s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
1399 s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1400 s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
1401 /* It is necessary if x is expressed from y */
1402 s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1405 update_color_with_alpha(s, &fontcolor , s->fontcolor );
1406 update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
1407 update_color_with_alpha(s, &bordercolor, s->bordercolor);
1408 update_color_with_alpha(s, &boxcolor , s->boxcolor );
1410 box_w = max_text_line_w;
1411 box_h = y + s->max_glyph_h;
1413 if (s->fix_bounds) {
1415 /* calculate footprint of text effects */
1416 int boxoffset = s->draw_box ? FFMAX(s->boxborderw, 0) : 0;
1417 int borderoffset = s->borderw ? FFMAX(s->borderw, 0) : 0;
1419 int offsetleft = FFMAX3(boxoffset, borderoffset,
1420 (s->shadowx < 0 ? FFABS(s->shadowx) : 0));
1421 int offsettop = FFMAX3(boxoffset, borderoffset,
1422 (s->shadowy < 0 ? FFABS(s->shadowy) : 0));
1424 int offsetright = FFMAX3(boxoffset, borderoffset,
1425 (s->shadowx > 0 ? s->shadowx : 0));
1426 int offsetbottom = FFMAX3(boxoffset, borderoffset,
1427 (s->shadowy > 0 ? s->shadowy : 0));
1430 if (s->x - offsetleft < 0) s->x = offsetleft;
1431 if (s->y - offsettop < 0) s->y = offsettop;
1433 if (s->x + box_w + offsetright > width)
1434 s->x = FFMAX(width - box_w - offsetright, 0);
1435 if (s->y + box_h + offsetbottom > height)
1436 s->y = FFMAX(height - box_h - offsetbottom, 0);
1441 ff_blend_rectangle(&s->dc, &boxcolor,
1442 frame->data, frame->linesize, width, height,
1443 s->x - s->boxborderw, s->y - s->boxborderw,
1444 box_w + s->boxborderw * 2, box_h + s->boxborderw * 2);
1446 if (s->shadowx || s->shadowy) {
1447 if ((ret = draw_glyphs(s, frame, width, height,
1448 &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
1453 if ((ret = draw_glyphs(s, frame, width, height,
1454 &bordercolor, 0, 0, s->borderw)) < 0)
1457 if ((ret = draw_glyphs(s, frame, width, height,
1458 &fontcolor, 0, 0, 0)) < 0)
1464 static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
1466 AVFilterContext *ctx = inlink->dst;
1467 AVFilterLink *outlink = ctx->outputs[0];
1468 DrawTextContext *s = ctx->priv;
1472 if ((ret = load_textfile(ctx)) < 0) {
1473 av_frame_free(&frame);
1476 #if CONFIG_LIBFRIBIDI
1477 if (s->text_shaping)
1478 if ((ret = shape_text(ctx)) < 0) {
1479 av_frame_free(&frame);
1485 s->var_values[VAR_N] = inlink->frame_count_out + s->start_number;
1486 s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
1487 NAN : frame->pts * av_q2d(inlink->time_base);
1489 s->var_values[VAR_PICT_TYPE] = frame->pict_type;
1490 s->metadata = frame->metadata;
1492 draw_text(ctx, frame, frame->width, frame->height);
1494 av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
1495 (int)s->var_values[VAR_N], s->var_values[VAR_T],
1496 (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
1499 return ff_filter_frame(outlink, frame);
1502 static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
1505 .type = AVMEDIA_TYPE_VIDEO,
1506 .filter_frame = filter_frame,
1507 .config_props = config_input,
1508 .needs_writable = 1,
1513 static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
1516 .type = AVMEDIA_TYPE_VIDEO,
1521 AVFilter ff_vf_drawtext = {
1523 .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1524 .priv_size = sizeof(DrawTextContext),
1525 .priv_class = &drawtext_class,
1528 .query_formats = query_formats,
1529 .inputs = avfilter_vf_drawtext_inputs,
1530 .outputs = avfilter_vf_drawtext_outputs,
1531 .process_command = command,
1532 .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,