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
33 #include "libavutil/avstring.h"
34 #include "libavutil/bprint.h"
35 #include "libavutil/common.h"
36 #include "libavutil/file.h"
37 #include "libavutil/eval.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/random_seed.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/timecode.h"
42 #include "libavutil/tree.h"
43 #include "libavutil/lfg.h"
45 #include "drawutils.h"
51 #include <freetype/config/ftheader.h>
52 #include FT_FREETYPE_H
55 #include <fontconfig/fontconfig.h>
58 static const char *const var_names[] = {
61 "line_h", "lh", ///< line height, same as max_glyph_h
62 "main_h", "h", "H", ///< height of the input video
63 "main_w", "w", "W", ///< width of the input video
64 "max_glyph_a", "ascent", ///< max glyph ascent
65 "max_glyph_d", "descent", ///< min glyph descent
66 "max_glyph_h", ///< max glyph height
67 "max_glyph_w", ///< max glyph width
68 "n", ///< number of frame
70 "t", ///< timestamp expressed in seconds
71 "text_h", "th", ///< height of the rendered text
72 "text_w", "tw", ///< width of the rendered text
78 static const char *const fun2_names[] = {
82 static double drand(void *opaque, double min, double max)
84 return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
87 typedef double (*eval_func2)(void *, double a, double b);
89 static const eval_func2 fun2[] = {
98 VAR_MAIN_H, VAR_h, VAR_H,
99 VAR_MAIN_W, VAR_w, VAR_W,
100 VAR_MAX_GLYPH_A, VAR_ASCENT,
101 VAR_MAX_GLYPH_D, VAR_DESCENT,
114 enum expansion_mode {
121 const AVClass *class;
122 enum expansion_mode exp_mode; ///< expansion mode to use for the text
123 int reinit; ///< tells if the filter is being reinited
124 uint8_t *fontfile; ///< font to be used
125 uint8_t *text; ///< text to be drawn
126 AVBPrint expanded_text; ///< used to contain the expanded text
127 int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
128 FT_Vector *positions; ///< positions for each element in the text
129 size_t nb_positions; ///< number of elements of positions array
130 char *textfile; ///< file with text to be drawn
131 int x; ///< x position to start drawing text
132 int y; ///< y position to start drawing text
133 int max_glyph_w; ///< max glyph width
134 int max_glyph_h; ///< max glyph height
135 int shadowx, shadowy;
136 unsigned int fontsize; ///< font size to use
137 char *fontcolor_string; ///< font color as string
138 char *boxcolor_string; ///< box color as string
139 char *shadowcolor_string; ///< shadow color as string
141 short int draw_box; ///< draw box around text - true or false
142 int use_kerning; ///< font kerning is used - true/false
143 int tabsize; ///< tab size
144 int fix_bounds; ///< do we let it go out of frame bounds - t/f
147 FFDrawColor fontcolor; ///< foreground color
148 FFDrawColor shadowcolor; ///< shadow color
149 FFDrawColor boxcolor; ///< background color
151 FT_Library library; ///< freetype font library handle
152 FT_Face face; ///< freetype font face handle
153 struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
154 char *x_expr; ///< expression for x position
155 char *y_expr; ///< expression for y position
156 AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
157 int64_t basetime; ///< base pts time in the real world for display
158 double var_values[VAR_VARS_NB];
159 char *draw_expr; ///< expression for draw
160 AVExpr *draw_pexpr; ///< parsed expression for draw
161 int draw; ///< set to zero to prevent drawing
162 AVLFG prng; ///< random
163 char *tc_opt_string; ///< specified timecode option string
164 AVRational tc_rate; ///< frame rate for timecode
165 AVTimecode tc; ///< timecode context
166 int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
168 int reload; ///< reload text file for each frame
171 #define OFFSET(x) offsetof(DrawTextContext, x)
172 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
174 static const AVOption drawtext_options[]= {
175 {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
176 {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
177 {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
178 {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
179 {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
180 {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
181 {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
182 {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
183 {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
184 {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
185 {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
186 {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
187 {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
188 {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
189 {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
191 {"expansion","set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
192 {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
193 {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
194 {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
196 {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
197 {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
198 {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
199 {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
200 {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
201 {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
202 {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
204 /* FT_LOAD_* flags */
205 {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.i64=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, FLAGS, "ft_load_flags"},
206 {"default", "set default", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
207 {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
208 {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
209 {"render", "set render", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_RENDER}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
210 {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
211 {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
212 {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
213 {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
214 {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
215 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
216 {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
217 {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
218 {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
219 {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
220 {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
224 AVFILTER_DEFINE_CLASS(drawtext);
226 #undef __FTERRORS_H__
227 #define FT_ERROR_START_LIST {
228 #define FT_ERRORDEF(e, v, s) { (e), (s) },
229 #define FT_ERROR_END_LIST { 0, NULL } };
235 } static ft_errors[] =
238 #define FT_ERRMSG(e) ft_errors[e].err_msg
243 FT_Bitmap bitmap; ///< array holding bitmaps of font
250 static int glyph_cmp(void *key, const void *b)
252 const Glyph *a = key, *bb = b;
253 int64_t diff = (int64_t)a->code - (int64_t)bb->code;
254 return diff > 0 ? 1 : diff < 0 ? -1 : 0;
258 * Load glyphs corresponding to the UTF-32 codepoint code.
260 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
262 DrawTextContext *dtext = ctx->priv;
264 struct AVTreeNode *node = NULL;
267 /* load glyph into dtext->face->glyph */
268 if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
269 return AVERROR(EINVAL);
272 if (!(glyph = av_mallocz(sizeof(*glyph))) ||
273 !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
274 ret = AVERROR(ENOMEM);
279 if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
280 ret = AVERROR(EINVAL);
284 glyph->bitmap = dtext->face->glyph->bitmap;
285 glyph->bitmap_left = dtext->face->glyph->bitmap_left;
286 glyph->bitmap_top = dtext->face->glyph->bitmap_top;
287 glyph->advance = dtext->face->glyph->advance.x >> 6;
289 /* measure text height to calculate text_height (or the maximum text height) */
290 FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
292 /* cache the newly created glyph */
293 if (!(node = av_tree_node_alloc())) {
294 ret = AVERROR(ENOMEM);
297 av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
305 av_freep(&glyph->glyph);
311 static int load_font_file(AVFilterContext *ctx, const char *path, int index,
314 DrawTextContext *dtext = ctx->priv;
317 err = FT_New_Face(dtext->library, path, index, &dtext->face);
319 *error = FT_ERRMSG(err);
320 return AVERROR(EINVAL);
325 #if CONFIG_FONTCONFIG
326 static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
328 DrawTextContext *dtext = ctx->priv;
329 FcConfig *fontconfig;
330 FcPattern *pattern, *fpat;
331 FcResult result = FcResultMatch;
336 fontconfig = FcInitLoadConfigAndFonts();
338 *error = "impossible to init fontconfig\n";
339 return AVERROR(EINVAL);
341 pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
342 (uint8_t *)(intptr_t)"default");
344 *error = "could not parse fontconfig pattern";
345 return AVERROR(EINVAL);
347 if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
348 *error = "could not substitue fontconfig options"; /* very unlikely */
349 return AVERROR(EINVAL);
351 FcDefaultSubstitute(pattern);
352 fpat = FcFontMatch(fontconfig, pattern, &result);
353 if (!fpat || result != FcResultMatch) {
354 *error = "impossible to find a matching font";
355 return AVERROR(EINVAL);
357 if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
358 FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
359 FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
360 *error = "impossible to find font information";
361 return AVERROR(EINVAL);
363 av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
364 if (!dtext->fontsize)
365 dtext->fontsize = size + 0.5;
366 err = load_font_file(ctx, filename, index, error);
369 FcPatternDestroy(fpat);
370 FcPatternDestroy(pattern);
371 FcConfigDestroy(fontconfig);
376 static int load_font(AVFilterContext *ctx)
378 DrawTextContext *dtext = ctx->priv;
380 const char *error = "unknown error\n";
382 /* load the face, and set up the encoding, which is by default UTF-8 */
383 err = load_font_file(ctx, dtext->fontfile, 0, &error);
386 #if CONFIG_FONTCONFIG
387 err = load_font_fontconfig(ctx, &error);
391 av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
392 dtext->fontfile, error);
396 static int load_textfile(AVFilterContext *ctx)
398 DrawTextContext *dtext = ctx->priv;
403 if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
404 av_log(ctx, AV_LOG_ERROR,
405 "The text file '%s' could not be read or is empty\n",
410 if (!(dtext->text = av_realloc(dtext->text, textbuf_size + 1)))
411 return AVERROR(ENOMEM);
412 memcpy(dtext->text, textbuf, textbuf_size);
413 dtext->text[textbuf_size] = 0;
414 av_file_unmap(textbuf, textbuf_size);
419 static av_cold int init(AVFilterContext *ctx, const char *args)
422 DrawTextContext *dtext = ctx->priv;
425 dtext->class = &drawtext_class;
426 av_opt_set_defaults(dtext);
428 if ((err = av_set_options_string(dtext, args, "=", ":")) < 0)
431 if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
432 av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
433 return AVERROR(EINVAL);
436 if (dtext->textfile) {
438 av_log(ctx, AV_LOG_ERROR,
439 "Both text and text file provided. Please provide only one\n");
440 return AVERROR(EINVAL);
442 if ((err = load_textfile(ctx)) < 0)
446 if (dtext->reload && !dtext->textfile)
447 av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
449 if (dtext->tc_opt_string) {
450 int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
451 dtext->tc_opt_string, ctx);
455 dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
457 dtext->text = av_strdup("");
461 av_log(ctx, AV_LOG_ERROR,
462 "Either text, a valid file or a timecode must be provided\n");
463 return AVERROR(EINVAL);
466 if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
467 av_log(ctx, AV_LOG_ERROR,
468 "Invalid font color '%s'\n", dtext->fontcolor_string);
472 if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
473 av_log(ctx, AV_LOG_ERROR,
474 "Invalid box color '%s'\n", dtext->boxcolor_string);
478 if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
479 av_log(ctx, AV_LOG_ERROR,
480 "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
484 if ((err = FT_Init_FreeType(&(dtext->library)))) {
485 av_log(ctx, AV_LOG_ERROR,
486 "Could not load FreeType: %s\n", FT_ERRMSG(err));
487 return AVERROR(EINVAL);
490 err = load_font(ctx);
493 if (!dtext->fontsize)
494 dtext->fontsize = 16;
495 if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
496 av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
497 dtext->fontsize, FT_ERRMSG(err));
498 return AVERROR(EINVAL);
501 dtext->use_kerning = FT_HAS_KERNING(dtext->face);
503 /* load the fallback glyph with code 0 */
504 load_glyph(ctx, NULL, 0);
506 /* set the tabsize in pixels */
507 if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
508 av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
511 dtext->tabsize *= glyph->advance;
513 if (dtext->exp_mode == EXP_STRFTIME &&
514 (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
515 av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
517 av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
522 static int query_formats(AVFilterContext *ctx)
524 ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
528 static int glyph_enu_free(void *opaque, void *elem)
532 FT_Done_Glyph(*glyph->glyph);
533 av_freep(&glyph->glyph);
538 static av_cold void uninit(AVFilterContext *ctx)
540 DrawTextContext *dtext = ctx->priv;
542 av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
543 av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
544 av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
547 av_freep(&dtext->positions);
548 dtext->nb_positions = 0;
550 av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
551 av_tree_destroy(dtext->glyphs);
552 dtext->glyphs = NULL;
554 FT_Done_Face(dtext->face);
555 FT_Done_FreeType(dtext->library);
557 av_bprint_finalize(&dtext->expanded_text, NULL);
560 static inline int is_newline(uint32_t c)
562 return c == '\n' || c == '\r' || c == '\f' || c == '\v';
565 static int config_input(AVFilterLink *inlink)
567 AVFilterContext *ctx = inlink->dst;
568 DrawTextContext *dtext = ctx->priv;
571 ff_draw_init(&dtext->dc, inlink->format, 0);
572 ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
573 ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
574 ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
576 dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
577 dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
578 dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
579 dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
580 dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
581 dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
582 dtext->var_values[VAR_X] = NAN;
583 dtext->var_values[VAR_Y] = NAN;
585 dtext->var_values[VAR_N] = 0;
586 dtext->var_values[VAR_T] = NAN;
588 av_lfg_init(&dtext->prng, av_get_random_seed());
590 if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
591 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
592 (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
593 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
594 (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
595 NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
597 return AVERROR(EINVAL);
602 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
604 DrawTextContext *dtext = ctx->priv;
606 if (!strcmp(cmd, "reinit")) {
610 if ((ret = init(ctx, arg)) < 0)
612 return config_input(ctx->inputs[0]);
615 return AVERROR(ENOSYS);
618 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
619 char *fct, unsigned argc, char **argv, int tag)
621 DrawTextContext *dtext = ctx->priv;
623 av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
627 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
628 char *fct, unsigned argc, char **argv, int tag)
630 DrawTextContext *dtext = ctx->priv;
632 av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
636 #if !HAVE_LOCALTIME_R
637 static void localtime_r(const time_t *t, struct tm *tm)
643 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
644 char *fct, unsigned argc, char **argv, int tag)
646 const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
652 localtime_r(&now, &tm);
655 av_bprint_strftime(bp, fmt, &tm);
659 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
660 char *fct, unsigned argc, char **argv, int tag)
662 DrawTextContext *dtext = ctx->priv;
666 ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
667 NULL, NULL, fun2_names, fun2,
668 &dtext->prng, 0, ctx);
670 av_log(ctx, AV_LOG_ERROR,
671 "Expression '%s' for the expr text expansion function is not valid\n",
674 av_bprintf(bp, "%f", res);
679 static const struct drawtext_function {
681 unsigned argc_min, argc_max;
682 int tag; /** opaque argument to func */
683 int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
685 { "expr", 1, 1, 0, func_eval_expr },
686 { "e", 1, 1, 0, func_eval_expr },
687 { "pts", 0, 0, 0, func_pts },
688 { "gmtime", 0, 1, 'G', func_strftime },
689 { "localtime", 0, 1, 'L', func_strftime },
690 { "frame_num", 0, 0, 0, func_frame_num },
691 { "n", 0, 0, 0, func_frame_num },
694 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
695 unsigned argc, char **argv)
699 for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
700 if (strcmp(fct, functions[i].name))
702 if (argc < functions[i].argc_min) {
703 av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
704 fct, functions[i].argc_min);
705 return AVERROR(EINVAL);
707 if (argc > functions[i].argc_max) {
708 av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
709 fct, functions[i].argc_max);
710 return AVERROR(EINVAL);
714 if (i >= FF_ARRAY_ELEMS(functions)) {
715 av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
716 return AVERROR(EINVAL);
718 return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
721 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
723 const char *text = *rtext;
724 char *argv[16] = { NULL };
725 unsigned argc = 0, i;
729 av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
730 return AVERROR(EINVAL);
734 if (!(argv[argc++] = av_get_token(&text, ":}"))) {
735 ret = AVERROR(ENOMEM);
739 av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
740 ret = AVERROR(EINVAL);
743 if (argc == FF_ARRAY_ELEMS(argv))
744 av_freep(&argv[--argc]); /* error will be caught later */
750 if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
753 *rtext = (char *)text + 1;
756 for (i = 0; i < argc; i++)
761 static int expand_text(AVFilterContext *ctx)
763 DrawTextContext *dtext = ctx->priv;
764 char *text = dtext->text;
765 AVBPrint *bp = &dtext->expanded_text;
770 if (*text == '\\' && text[1]) {
771 av_bprint_chars(bp, text[1], 1);
773 } else if (*text == '%') {
775 if ((ret = expand_function(ctx, bp, &text)) < 0)
778 av_bprint_chars(bp, *text, 1);
782 if (!av_bprint_is_complete(bp))
783 return AVERROR(ENOMEM);
787 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
788 int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
790 char *text = dtext->expanded_text.str;
796 for (i = 0, p = text; *p; i++) {
798 GET_UTF8(code, *p++, continue;);
800 /* skip new line chars, just go to new line */
801 if (code == '\n' || code == '\r' || code == '\t')
805 glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
807 if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
808 glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
809 return AVERROR(EINVAL);
811 x1 = dtext->positions[i].x+dtext->x+x;
812 y1 = dtext->positions[i].y+dtext->y+y;
814 ff_blend_mask(&dtext->dc, color,
815 picref->data, picref->linesize, width, height,
816 glyph->bitmap.buffer, glyph->bitmap.pitch,
817 glyph->bitmap.width, glyph->bitmap.rows,
818 glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
825 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
826 int width, int height)
828 DrawTextContext *dtext = ctx->priv;
829 uint32_t code = 0, prev_code = 0;
830 int x = 0, y = 0, i = 0, ret;
831 int max_text_line_w = 0, len;
833 char *text = dtext->text;
835 int y_min = 32000, y_max = -32000;
836 int x_min = 32000, x_max = -32000;
838 Glyph *glyph = NULL, *prev_glyph = NULL;
841 time_t now = time(0);
843 AVBPrint *bp = &dtext->expanded_text;
847 if(dtext->basetime != AV_NOPTS_VALUE)
848 now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
850 switch (dtext->exp_mode) {
852 av_bprintf(bp, "%s", dtext->text);
855 if ((ret = expand_text(ctx)) < 0)
859 localtime_r(&now, <ime);
860 av_bprint_strftime(bp, dtext->text, <ime);
864 if (dtext->tc_opt_string) {
865 char tcbuf[AV_TIMECODE_STR_SIZE];
866 av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
868 av_bprintf(bp, "%s%s", dtext->text, tcbuf);
871 if (!av_bprint_is_complete(bp))
872 return AVERROR(ENOMEM);
873 text = dtext->expanded_text.str;
874 if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
875 if (!(dtext->positions =
876 av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
877 return AVERROR(ENOMEM);
878 dtext->nb_positions = len;
884 /* load and cache glyphs */
885 for (i = 0, p = text; *p; i++) {
886 GET_UTF8(code, *p++, continue;);
890 glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
892 load_glyph(ctx, &glyph, code);
895 y_min = FFMIN(glyph->bbox.yMin, y_min);
896 y_max = FFMAX(glyph->bbox.yMax, y_max);
897 x_min = FFMIN(glyph->bbox.xMin, x_min);
898 x_max = FFMAX(glyph->bbox.xMax, x_max);
900 dtext->max_glyph_h = y_max - y_min;
901 dtext->max_glyph_w = x_max - x_min;
903 /* compute and save position for each glyph */
905 for (i = 0, p = text; *p; i++) {
906 GET_UTF8(code, *p++, continue;);
908 /* skip the \n in the sequence \r\n */
909 if (prev_code == '\r' && code == '\n')
913 if (is_newline(code)) {
914 max_text_line_w = FFMAX(max_text_line_w, x);
915 y += dtext->max_glyph_h;
923 glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
926 if (dtext->use_kerning && prev_glyph && glyph->code) {
927 FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
928 ft_kerning_default, &delta);
933 dtext->positions[i].x = x + glyph->bitmap_left;
934 dtext->positions[i].y = y - glyph->bitmap_top + y_max;
935 if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
936 else x += glyph->advance;
939 max_text_line_w = FFMAX(x, max_text_line_w);
941 dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
942 dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
944 dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
945 dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
946 dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
947 dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
949 dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
951 dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
952 dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
953 dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
954 dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
959 box_w = FFMIN(width - 1 , max_text_line_w);
960 box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
964 ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
965 picref->data, picref->linesize, width, height,
966 dtext->x, dtext->y, box_w, box_h);
968 if (dtext->shadowx || dtext->shadowy) {
969 if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,
970 &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
974 if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,
975 &dtext->fontcolor, 0, 0)) < 0)
981 static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
983 AVFilterContext *ctx = inlink->dst;
984 AVFilterLink *outlink = ctx->outputs[0];
985 DrawTextContext *dtext = ctx->priv;
989 if ((ret = load_textfile(ctx)) < 0)
992 dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
993 NAN : frame->pts * av_q2d(inlink->time_base);
995 draw_text(ctx, frame, frame->video->w, frame->video->h);
997 av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
998 (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
999 (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
1000 dtext->x, dtext->y);
1002 dtext->var_values[VAR_N] += 1.0;
1004 return ff_filter_frame(outlink, frame);
1007 static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
1010 .type = AVMEDIA_TYPE_VIDEO,
1011 .get_video_buffer = ff_null_get_video_buffer,
1012 .filter_frame = filter_frame,
1013 .config_props = config_input,
1014 .min_perms = AV_PERM_WRITE |
1020 static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
1023 .type = AVMEDIA_TYPE_VIDEO,
1028 AVFilter avfilter_vf_drawtext = {
1030 .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1031 .priv_size = sizeof(DrawTextContext),
1034 .query_formats = query_formats,
1036 .inputs = avfilter_vf_drawtext_inputs,
1037 .outputs = avfilter_vf_drawtext_outputs,
1038 .process_command = command,
1039 .priv_class = &drawtext_class,