FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
vf_drawtext.c
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2011 Stefano Sabatini
3  * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
4  * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
5  *
6  * This file is part of FFmpeg.
7  *
8  * FFmpeg is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * FFmpeg is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with FFmpeg; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
21  */
22 
23 /**
24  * @file
25  * drawtext filter, based on the original vhook/drawtext.c
26  * filter by Gustavo Sverzut Barbieri
27  */
28 
29 #include "config.h"
30 
31 #if HAVE_SYS_TIME_H
32 #include <sys/time.h>
33 #endif
34 #include <sys/types.h>
35 #include <sys/stat.h>
36 #include <time.h>
37 #if HAVE_UNISTD_H
38 #include <unistd.h>
39 #endif
40 #include <fenv.h>
41 
42 #if CONFIG_LIBFONTCONFIG
43 #include <fontconfig/fontconfig.h>
44 #endif
45 
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"
56 #include "libavutil/tree.h"
57 #include "libavutil/lfg.h"
58 #include "avfilter.h"
59 #include "drawutils.h"
60 #include "formats.h"
61 #include "internal.h"
62 #include "video.h"
63 
64 #if CONFIG_LIBFRIBIDI
65 #include <fribidi.h>
66 #endif
67 
68 #include <ft2build.h>
69 #include FT_FREETYPE_H
70 #include FT_GLYPH_H
71 #include FT_STROKER_H
72 
73 static const char *const var_names[] = {
74  "dar",
75  "hsub", "vsub",
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
84  "sar",
85  "t", ///< timestamp expressed in seconds
86  "text_h", "th", ///< height of the rendered text
87  "text_w", "tw", ///< width of the rendered text
88  "x",
89  "y",
90  "pict_type",
91  NULL
92 };
93 
94 static const char *const fun2_names[] = {
95  "rand"
96 };
97 
98 static double drand(void *opaque, double min, double max)
99 {
100  return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
101 }
102 
103 typedef double (*eval_func2)(void *, double a, double b);
104 
105 static const eval_func2 fun2[] = {
106  drand,
107  NULL
108 };
109 
110 enum var_name {
129 };
130 
135 };
136 
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
143 #endif
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
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
163 
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
170 
172  FFDrawColor fontcolor; ///< foreground color
173  FFDrawColor shadowcolor; ///< shadow color
174  FFDrawColor bordercolor; ///< border color
175  FFDrawColor boxcolor; ///< background color
176 
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
186  char *a_expr;
188  int alpha;
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
198 #endif
201 
202 #define OFFSET(x) offsetof(DrawTextContext, x)
203 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
204 
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 },
227 #endif
228 
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"},
233 
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},
243 
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},
246 #endif
247 
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" },
265  { NULL }
266 };
267 
269 
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 } };
274 
275 static const struct ft_error {
276  int err;
277  const char *err_msg;
278 } ft_errors[] =
279 #include FT_ERRORS_H
280 
281 #define FT_ERRMSG(e) ft_errors[e].err_msg
282 
283 typedef struct Glyph {
284  FT_Glyph glyph;
285  FT_Glyph border_glyph;
286  uint32_t code;
287  unsigned int fontsize;
288  FT_Bitmap bitmap; ///< array holding bitmaps of font
289  FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
290  FT_BBox bbox;
291  int advance;
292  int bitmap_left;
293  int bitmap_top;
294 } Glyph;
295 
296 static int glyph_cmp(const void *key, const void *b)
297 {
298  const Glyph *a = key, *bb = b;
299  int64_t diff = (int64_t)a->code - (int64_t)bb->code;
300 
301  if (diff != 0)
302  return diff > 0 ? 1 : -1;
303  else
304  return FFDIFFSIGN((int64_t)a->fontsize, (int64_t)bb->fontsize);
305 }
306 
307 /**
308  * Load glyphs corresponding to the UTF-32 codepoint code.
309  */
310 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
311 {
312  DrawTextContext *s = ctx->priv;
313  FT_BitmapGlyph bitmapglyph;
314  Glyph *glyph;
315  struct AVTreeNode *node = NULL;
316  int ret;
317 
318  /* load glyph into s->face->glyph */
319  if (FT_Load_Char(s->face, code, s->ft_load_flags))
320  return AVERROR(EINVAL);
321 
322  glyph = av_mallocz(sizeof(*glyph));
323  if (!glyph) {
324  ret = AVERROR(ENOMEM);
325  goto error;
326  }
327  glyph->code = code;
328  glyph->fontsize = s->fontsize;
329 
330  if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
331  ret = AVERROR(EINVAL);
332  goto error;
333  }
334  if (s->borderw) {
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;
339  goto error;
340  }
341  bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
342  glyph->border_bitmap = bitmapglyph->bitmap;
343  }
344  if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
345  ret = AVERROR_EXTERNAL;
346  goto error;
347  }
348  bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
349 
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;
354 
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);
357 
358  /* cache the newly created glyph */
359  if (!(node = av_tree_node_alloc())) {
360  ret = AVERROR(ENOMEM);
361  goto error;
362  }
363  av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
364 
365  if (glyph_ptr)
366  *glyph_ptr = glyph;
367  return 0;
368 
369 error:
370  if (glyph)
371  av_freep(&glyph->glyph);
372 
373  av_freep(&glyph);
374  av_freep(&node);
375  return ret;
376 }
377 
378 static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
379 {
380  int err;
381  DrawTextContext *s = ctx->priv;
382 
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);
387  }
388 
389  s->fontsize = fontsize;
390 
391  return 0;
392 }
393 
395 {
396  DrawTextContext *s = ctx->priv;
397  int err;
398 
399  if (s->fontsize_pexpr)
400  return 0;
401 
402  if (s->fontsize_expr == NULL)
403  return AVERROR(EINVAL);
404 
406  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
407  return err;
408 
409  return 0;
410 }
411 
413 {
414  DrawTextContext *s = ctx->priv;
415  unsigned int fontsize = s->default_fontsize;
416  int err;
417  double size, roundedsize;
418 
419  // if no fontsize specified use the default
420  if (s->fontsize_expr != NULL) {
421  if ((err = parse_fontsize(ctx)) < 0)
422  return err;
423 
424  size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
425 
426  if (!isnan(size)) {
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);
432  }
433 
434  fontsize = roundedsize;
435  }
436  }
437 
438  if (fontsize == 0)
439  fontsize = 1;
440 
441  // no change
442  if (fontsize == s->fontsize)
443  return 0;
444 
445  return set_fontsize(ctx, fontsize);
446 }
447 
448 static int load_font_file(AVFilterContext *ctx, const char *path, int index)
449 {
450  DrawTextContext *s = ctx->priv;
451  int err;
452 
453  err = FT_New_Face(s->library, path, index, &s->face);
454  if (err) {
455 #if !CONFIG_LIBFONTCONFIG
456  av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
457  s->fontfile, FT_ERRMSG(err));
458 #endif
459  return AVERROR(EINVAL);
460  }
461  return 0;
462 }
463 
464 #if CONFIG_LIBFONTCONFIG
465 static int load_font_fontconfig(AVFilterContext *ctx)
466 {
467  DrawTextContext *s = ctx->priv;
468  FcConfig *fontconfig;
469  FcPattern *pat, *best;
470  FcResult result = FcResultMatch;
471  FcChar8 *filename;
472  int index;
473  double size;
474  int err = AVERROR(ENOENT);
475  int parse_err;
476 
477  fontconfig = FcInitLoadConfigAndFonts();
478  if (!fontconfig) {
479  av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
480  return AVERROR_UNKNOWN;
481  }
482  pat = FcNameParse(s->fontfile ? s->fontfile :
483  (uint8_t *)(intptr_t)"default");
484  if (!pat) {
485  av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
486  return AVERROR(EINVAL);
487  }
488 
489  FcPatternAddString(pat, FC_FAMILY, s->font);
490 
491  parse_err = parse_fontsize(ctx);
492  if (!parse_err) {
493  double size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
494 
495  if (isnan(size)) {
496  av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
497  return AVERROR(EINVAL);
498  }
499 
500  FcPatternAddDouble(pat, FC_SIZE, size);
501  }
502 
503  FcDefaultSubstitute(pat);
504 
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);
509  }
510 
511  best = FcFontMatch(fontconfig, pat, &result);
512  FcPatternDestroy(pat);
513 
514  if (!best || result != FcResultMatch) {
515  av_log(ctx, AV_LOG_ERROR,
516  "Cannot find a valid font for the family %s\n",
517  s->font);
518  goto fail;
519  }
520 
521  if (
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);
526  }
527 
528  if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
529  av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
530  s->font);
531  goto fail;
532  }
533 
534  av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
535  if (parse_err)
536  s->default_fontsize = size + 0.5;
537 
538  err = load_font_file(ctx, filename, index);
539  if (err)
540  return err;
541  FcConfigDestroy(fontconfig);
542 fail:
543  FcPatternDestroy(best);
544  return err;
545 }
546 #endif
547 
548 static int load_font(AVFilterContext *ctx)
549 {
550  DrawTextContext *s = ctx->priv;
551  int err;
552 
553  /* load the face, and set up the encoding, which is by default UTF-8 */
554  err = load_font_file(ctx, s->fontfile, 0);
555  if (!err)
556  return 0;
557 #if CONFIG_LIBFONTCONFIG
558  err = load_font_fontconfig(ctx);
559  if (!err)
560  return 0;
561 #endif
562  return err;
563 }
564 
566 {
567  DrawTextContext *s = ctx->priv;
568  int err;
569  uint8_t *textbuf;
570  uint8_t *tmp;
571  size_t textbuf_size;
572 
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",
576  s->textfile);
577  return err;
578  }
579 
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);
583  }
584  s->text = tmp;
585  memcpy(s->text, textbuf, textbuf_size);
586  s->text[textbuf_size] = 0;
587  av_file_unmap(textbuf, textbuf_size);
588 
589  return 0;
590 }
591 
592 static inline int is_newline(uint32_t c)
593 {
594  return c == '\n' || c == '\r' || c == '\f' || c == '\v';
595 }
596 
597 #if CONFIG_LIBFRIBIDI
598 static int shape_text(AVFilterContext *ctx)
599 {
600  DrawTextContext *s = ctx->priv;
601  uint8_t *tmp;
602  int ret = AVERROR(ENOMEM);
603  static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
604  FRIBIDI_FLAGS_ARABIC;
605  FriBidiChar *unicodestr = NULL;
606  FriBidiStrIndex len;
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;
613  FriBidiStrIndex i,j;
614 
615  len = strlen(s->text);
616  if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
617  goto out;
618  }
619  len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
620  s->text, len, unicodestr);
621 
622  bidi_types = av_malloc_array(len, sizeof(*bidi_types));
623  if (!bidi_types) {
624  goto out;
625  }
626 
627  fribidi_get_bidi_types(unicodestr, len, bidi_types);
628 
629  embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
630  if (!embedding_levels) {
631  goto out;
632  }
633 
634  if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
635  embedding_levels)) {
636  goto out;
637  }
638 
639  ar_props = av_malloc_array(len, sizeof(*ar_props));
640  if (!ar_props) {
641  goto out;
642  }
643 
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);
647 
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,
653  NULL)) {
654  goto out;
655  }
656  line_start = line_end + 1;
657  }
658  }
659 
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];
664  len = j;
665 
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 */
668  goto out;
669  }
670 
671  s->text = tmp;
672  len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
673  unicodestr, len, s->text);
674  ret = 0;
675 
676 out:
677  av_free(unicodestr);
678  av_free(embedding_levels);
679  av_free(ar_props);
680  av_free(bidi_types);
681  return ret;
682 }
683 #endif
684 
685 static av_cold int init(AVFilterContext *ctx)
686 {
687  int err;
688  DrawTextContext *s = ctx->priv;
689  Glyph *glyph;
690 
692  s->fontsize_pexpr = NULL;
693 
694  s->fontsize = 0;
695  s->default_fontsize = 16;
696 
697  if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
698  av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
699  return AVERROR(EINVAL);
700  }
701 
702  if (s->textfile) {
703  if (s->text) {
704  av_log(ctx, AV_LOG_ERROR,
705  "Both text and text file provided. Please provide only one\n");
706  return AVERROR(EINVAL);
707  }
708  if ((err = load_textfile(ctx)) < 0)
709  return err;
710  }
711 
712  if (s->reload && !s->textfile)
713  av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
714 
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);
718  if (ret < 0)
719  return ret;
720  if (s->tc24hmax)
722  if (!s->text)
723  s->text = av_strdup("");
724  }
725 
726  if (!s->text) {
727  av_log(ctx, AV_LOG_ERROR,
728  "Either text, a valid file or a timecode must be provided\n");
729  return AVERROR(EINVAL);
730  }
731 
732 #if CONFIG_LIBFRIBIDI
733  if (s->text_shaping)
734  if ((err = shape_text(ctx)) < 0)
735  return err;
736 #endif
737 
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);
742  }
743 
744  if ((err = load_font(ctx)) < 0)
745  return err;
746 
747  if ((err = update_fontsize(ctx)) < 0)
748  return err;
749 
750  if (s->borderw) {
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;
754  }
755  FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
756  FT_STROKER_LINEJOIN_ROUND, 0);
757  }
758 
759  s->use_kerning = FT_HAS_KERNING(s->face);
760 
761  /* load the fallback glyph with code 0 */
762  load_glyph(ctx, NULL, 0);
763 
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");
767  return err;
768  }
769  s->tabsize *= glyph->advance;
770 
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");
774 
777 
778  return 0;
779 }
780 
782 {
784 }
785 
786 static int glyph_enu_free(void *opaque, void *elem)
787 {
788  Glyph *glyph = elem;
789 
790  FT_Done_Glyph(glyph->glyph);
791  FT_Done_Glyph(glyph->border_glyph);
792  av_free(elem);
793  return 0;
794 }
795 
796 static av_cold void uninit(AVFilterContext *ctx)
797 {
798  DrawTextContext *s = ctx->priv;
799 
800  av_expr_free(s->x_pexpr);
801  av_expr_free(s->y_pexpr);
802  av_expr_free(s->a_pexpr);
804 
805  s->x_pexpr = s->y_pexpr = s->a_pexpr = s->fontsize_pexpr = NULL;
806 
807  av_freep(&s->positions);
808  s->nb_positions = 0;
809 
812  s->glyphs = NULL;
813 
814  FT_Done_Face(s->face);
815  FT_Stroker_Done(s->stroker);
816  FT_Done_FreeType(s->library);
817 
820 }
821 
822 static int config_input(AVFilterLink *inlink)
823 {
824  AVFilterContext *ctx = inlink->dst;
825  DrawTextContext *s = ctx->priv;
826  int ret;
827 
829  ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
832  ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
833 
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;
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;
843 
845 
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;
850 
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)
857 
858  return AVERROR(EINVAL);
859 
860  return 0;
861 }
862 
863 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
864 {
865  DrawTextContext *s = ctx->priv;
866 
867  if (!strcmp(cmd, "reinit")) {
868  int ret;
869  uninit(ctx);
870  s->reinit = 1;
871  if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
872  return ret;
873  if ((ret = init(ctx)) < 0)
874  return ret;
875  return config_input(ctx->inputs[0]);
876  }
877 
878  return AVERROR(ENOSYS);
879 }
880 
881 static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
882  char *fct, unsigned argc, char **argv, int tag)
883 {
884  DrawTextContext *s = ctx->priv;
885 
887  return 0;
888 }
889 
890 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
891  char *fct, unsigned argc, char **argv, int tag)
892 {
893  DrawTextContext *s = ctx->priv;
894  const char *fmt;
895  double pts = s->var_values[VAR_T];
896  int ret;
897 
898  fmt = argc >= 1 ? argv[0] : "flt";
899  if (argc >= 2) {
900  int64_t delta;
901  if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
902  av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
903  return ret;
904  }
905  pts += (double)delta / AV_TIME_BASE;
906  }
907  if (!strcmp(fmt, "flt")) {
908  av_bprintf(bp, "%.6f", pts);
909  } else if (!strcmp(fmt, "hms")) {
910  if (isnan(pts)) {
911  av_bprintf(bp, " ??:??:??.???");
912  } else {
913  int64_t ms = llrint(pts * 1000);
914  char sign = ' ';
915  if (ms < 0) {
916  sign = '-';
917  ms = -ms;
918  }
919  if (argc >= 3) {
920  if (!strcmp(argv[2], "24HH")) {
921  ms %= 24 * 60 * 60 * 1000;
922  } else {
923  av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s'\n", argv[2]);
924  return AVERROR(EINVAL);
925  }
926  }
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,
931  (int)(ms % 1000));
932  }
933  } else if (!strcmp(fmt, "localtime") ||
934  !strcmp(fmt, "gmtime")) {
935  struct tm tm;
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);
940  else
941  gmtime_r(&ms, &tm);
942  av_bprint_strftime(bp, timefmt, &tm);
943  } else {
944  av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
945  return AVERROR(EINVAL);
946  }
947  return 0;
948 }
949 
950 static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
951  char *fct, unsigned argc, char **argv, int tag)
952 {
953  DrawTextContext *s = ctx->priv;
954 
955  av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
956  return 0;
957 }
958 
959 static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
960  char *fct, unsigned argc, char **argv, int tag)
961 {
962  DrawTextContext *s = ctx->priv;
963  AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
964 
965  if (e && e->value)
966  av_bprintf(bp, "%s", e->value);
967  else if (argc >= 2)
968  av_bprintf(bp, "%s", argv[1]);
969  return 0;
970 }
971 
972 static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
973  char *fct, unsigned argc, char **argv, int tag)
974 {
975  const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
976  time_t now;
977  struct tm tm;
978 
979  time(&now);
980  if (tag == 'L')
981  localtime_r(&now, &tm);
982  else
983  tm = *gmtime_r(&now, &tm);
984  av_bprint_strftime(bp, fmt, &tm);
985  return 0;
986 }
987 
988 static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
989  char *fct, unsigned argc, char **argv, int tag)
990 {
991  DrawTextContext *s = ctx->priv;
992  double res;
993  int ret;
994 
995  ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
997  &s->prng, 0, ctx);
998  if (ret < 0)
999  av_log(ctx, AV_LOG_ERROR,
1000  "Expression '%s' for the expr text expansion function is not valid\n",
1001  argv[0]);
1002  else
1003  av_bprintf(bp, "%f", res);
1004 
1005  return ret;
1006 }
1007 
1008 static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
1009  char *fct, unsigned argc, char **argv, int tag)
1010 {
1011  DrawTextContext *s = ctx->priv;
1012  double res;
1013  int intval;
1014  int ret;
1015  unsigned int positions = 0;
1016  char fmt_str[30] = "%";
1017 
1018  /*
1019  * argv[0] expression to be converted to `int`
1020  * argv[1] format: 'x', 'X', 'd' or 'u'
1021  * argv[2] positions printed (optional)
1022  */
1023 
1024  ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
1025  NULL, NULL, fun2_names, fun2,
1026  &s->prng, 0, ctx);
1027  if (ret < 0) {
1028  av_log(ctx, AV_LOG_ERROR,
1029  "Expression '%s' for the expr text expansion function is not valid\n",
1030  argv[0]);
1031  return ret;
1032  }
1033 
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);
1038  }
1039 
1040  if (argc == 3) {
1041  ret = sscanf(argv[2], "%u", &positions);
1042  if (ret != 1) {
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);
1046  }
1047  }
1048 
1049  feclearexcept(FE_ALL_EXCEPT);
1050  intval = res;
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);
1054  }
1055 
1056  if (argc == 3)
1057  av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
1058  av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
1059 
1060  av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
1061  res, argv[0], fmt_str);
1062 
1063  av_bprintf(bp, fmt_str, intval);
1064 
1065  return 0;
1066 }
1067 
1068 static const struct drawtext_function {
1069  const char *name;
1070  unsigned argc_min, argc_max;
1071  int tag; /**< opaque argument to func */
1072  int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
1073 } functions[] = {
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 },
1085 };
1086 
1087 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
1088  unsigned argc, char **argv)
1089 {
1090  unsigned i;
1091 
1092  for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
1093  if (strcmp(fct, functions[i].name))
1094  continue;
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);
1099  }
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);
1104  }
1105  break;
1106  }
1107  if (i >= FF_ARRAY_ELEMS(functions)) {
1108  av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
1109  return AVERROR(EINVAL);
1110  }
1111  return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
1112 }
1113 
1114 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
1115 {
1116  const char *text = *rtext;
1117  char *argv[16] = { NULL };
1118  unsigned argc = 0, i;
1119  int ret;
1120 
1121  if (*text != '{') {
1122  av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
1123  return AVERROR(EINVAL);
1124  }
1125  text++;
1126  while (1) {
1127  if (!(argv[argc++] = av_get_token(&text, ":}"))) {
1128  ret = AVERROR(ENOMEM);
1129  goto end;
1130  }
1131  if (!*text) {
1132  av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
1133  ret = AVERROR(EINVAL);
1134  goto end;
1135  }
1136  if (argc == FF_ARRAY_ELEMS(argv))
1137  av_freep(&argv[--argc]); /* error will be caught later */
1138  if (*text == '}')
1139  break;
1140  text++;
1141  }
1142 
1143  if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
1144  goto end;
1145  ret = 0;
1146  *rtext = (char *)text + 1;
1147 
1148 end:
1149  for (i = 0; i < argc; i++)
1150  av_freep(&argv[i]);
1151  return ret;
1152 }
1153 
1154 static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
1155 {
1156  int ret;
1157 
1158  av_bprint_clear(bp);
1159  while (*text) {
1160  if (*text == '\\' && text[1]) {
1161  av_bprint_chars(bp, text[1], 1);
1162  text += 2;
1163  } else if (*text == '%') {
1164  text++;
1165  if ((ret = expand_function(ctx, bp, &text)) < 0)
1166  return ret;
1167  } else {
1168  av_bprint_chars(bp, *text, 1);
1169  text++;
1170  }
1171  }
1172  if (!av_bprint_is_complete(bp))
1173  return AVERROR(ENOMEM);
1174  return 0;
1175 }
1176 
1178  int width, int height,
1179  FFDrawColor *color,
1180  int x, int y, int borderw)
1181 {
1182  char *text = s->expanded_text.str;
1183  uint32_t code = 0;
1184  int i, x1, y1;
1185  uint8_t *p;
1186  Glyph *glyph = NULL;
1187 
1188  for (i = 0, p = text; *p; i++) {
1189  FT_Bitmap bitmap;
1190  Glyph dummy = { 0 };
1191  GET_UTF8(code, *p++, continue;);
1192 
1193  /* skip new line chars, just go to new line */
1194  if (code == '\n' || code == '\r' || code == '\t')
1195  continue;
1196 
1197  dummy.code = code;
1198  dummy.fontsize = s->fontsize;
1199  glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1200 
1201  bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
1202 
1203  if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
1204  glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
1205  return AVERROR(EINVAL);
1206 
1207  x1 = s->positions[i].x+s->x+x - borderw;
1208  y1 = s->positions[i].y+s->y+y - borderw;
1209 
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,
1215  0, x1, y1);
1216  }
1217 
1218  return 0;
1219 }
1220 
1221 
1223 {
1224  *color = incolor;
1225  color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
1226  ff_draw_color(&s->dc, color, color->rgba);
1227 }
1228 
1230 {
1231  double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
1232 
1233  if (isnan(alpha))
1234  return;
1235 
1236  if (alpha >= 1.0)
1237  s->alpha = 255;
1238  else if (alpha <= 0)
1239  s->alpha = 0;
1240  else
1241  s->alpha = 256 * alpha;
1242 }
1243 
1245  int width, int height)
1246 {
1247  DrawTextContext *s = ctx->priv;
1248  AVFilterLink *inlink = ctx->inputs[0];
1249 
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;
1253  int box_w, box_h;
1254  char *text;
1255  uint8_t *p;
1256  int y_min = 32000, y_max = -32000;
1257  int x_min = 32000, x_max = -32000;
1258  FT_Vector delta;
1259  Glyph *glyph = NULL, *prev_glyph = NULL;
1260  Glyph dummy = { 0 };
1261 
1262  time_t now = time(0);
1263  struct tm ltime;
1264  AVBPrint *bp = &s->expanded_text;
1265 
1266  FFDrawColor fontcolor;
1267  FFDrawColor shadowcolor;
1268  FFDrawColor bordercolor;
1269  FFDrawColor boxcolor;
1270 
1271  av_bprint_clear(bp);
1272 
1273  if(s->basetime != AV_NOPTS_VALUE)
1274  now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
1275 
1276  switch (s->exp_mode) {
1277  case EXP_NONE:
1278  av_bprintf(bp, "%s", s->text);
1279  break;
1280  case EXP_NORMAL:
1281  if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
1282  return ret;
1283  break;
1284  case EXP_STRFTIME:
1285  localtime_r(&now, &ltime);
1286  av_bprint_strftime(bp, s->text, &ltime);
1287  break;
1288  }
1289 
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);
1295  }
1296 
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;
1305  }
1306 
1307  if (s->fontcolor_expr[0]) {
1308  /* If expression is set, evaluate and replace the static value */
1310  if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
1311  return ret;
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);
1316  if (ret)
1317  return ret;
1318  ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
1319  }
1320 
1321  x = 0;
1322  y = 0;
1323 
1324  if ((ret = update_fontsize(ctx)) < 0)
1325  return ret;
1326 
1327  /* load and cache glyphs */
1328  for (i = 0, p = text; *p; i++) {
1329  GET_UTF8(code, *p++, continue;);
1330 
1331  /* get glyph */
1332  dummy.code = code;
1333  dummy.fontsize = s->fontsize;
1334  glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1335  if (!glyph) {
1336  ret = load_glyph(ctx, &glyph, code);
1337  if (ret < 0)
1338  return ret;
1339  }
1340 
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);
1345  }
1346  s->max_glyph_h = y_max - y_min;
1347  s->max_glyph_w = x_max - x_min;
1348 
1349  /* compute and save position for each glyph */
1350  glyph = NULL;
1351  for (i = 0, p = text; *p; i++) {
1352  GET_UTF8(code, *p++, continue;);
1353 
1354  /* skip the \n in the sequence \r\n */
1355  if (prev_code == '\r' && code == '\n')
1356  continue;
1357 
1358  prev_code = code;
1359  if (is_newline(code)) {
1360 
1361  max_text_line_w = FFMAX(max_text_line_w, x);
1362  y += s->max_glyph_h + s->line_spacing;
1363  x = 0;
1364  continue;
1365  }
1366 
1367  /* get glyph */
1368  prev_glyph = glyph;
1369  dummy.code = code;
1370  dummy.fontsize = s->fontsize;
1371  glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1372 
1373  /* kerning */
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);
1377  x += delta.x >> 6;
1378  }
1379 
1380  /* save position */
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;
1385  }
1386 
1387  max_text_line_w = FFMAX(x, max_text_line_w);
1388 
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;
1391 
1394  s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
1396 
1398 
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);
1403 
1404  update_alpha(s);
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 );
1409 
1410  box_w = max_text_line_w;
1411  box_h = y + s->max_glyph_h;
1412 
1413  if (s->fix_bounds) {
1414 
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;
1418 
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));
1423 
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));
1428 
1429 
1430  if (s->x - offsetleft < 0) s->x = offsetleft;
1431  if (s->y - offsettop < 0) s->y = offsettop;
1432 
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);
1437  }
1438 
1439  /* draw box */
1440  if (s->draw_box)
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);
1445 
1446  if (s->shadowx || s->shadowy) {
1447  if ((ret = draw_glyphs(s, frame, width, height,
1448  &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
1449  return ret;
1450  }
1451 
1452  if (s->borderw) {
1453  if ((ret = draw_glyphs(s, frame, width, height,
1454  &bordercolor, 0, 0, s->borderw)) < 0)
1455  return ret;
1456  }
1457  if ((ret = draw_glyphs(s, frame, width, height,
1458  &fontcolor, 0, 0, 0)) < 0)
1459  return ret;
1460 
1461  return 0;
1462 }
1463 
1465 {
1466  AVFilterContext *ctx = inlink->dst;
1467  AVFilterLink *outlink = ctx->outputs[0];
1468  DrawTextContext *s = ctx->priv;
1469  int ret;
1470 
1471  if (s->reload) {
1472  if ((ret = load_textfile(ctx)) < 0) {
1473  av_frame_free(&frame);
1474  return ret;
1475  }
1476 #if CONFIG_LIBFRIBIDI
1477  if (s->text_shaping)
1478  if ((ret = shape_text(ctx)) < 0) {
1479  av_frame_free(&frame);
1480  return ret;
1481  }
1482 #endif
1483  }
1484 
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);
1488 
1489  s->var_values[VAR_PICT_TYPE] = frame->pict_type;
1490  s->metadata = frame->metadata;
1491 
1492  draw_text(ctx, frame, frame->width, frame->height);
1493 
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],
1497  s->x, s->y);
1498 
1499  return ff_filter_frame(outlink, frame);
1500 }
1501 
1503  {
1504  .name = "default",
1505  .type = AVMEDIA_TYPE_VIDEO,
1506  .filter_frame = filter_frame,
1507  .config_props = config_input,
1508  .needs_writable = 1,
1509  },
1510  { NULL }
1511 };
1512 
1514  {
1515  .name = "default",
1516  .type = AVMEDIA_TYPE_VIDEO,
1517  },
1518  { NULL }
1519 };
1520 
1522  .name = "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,
1526  .init = init,
1527  .uninit = uninit,
1529  .inputs = avfilter_vf_drawtext_inputs,
1530  .outputs = avfilter_vf_drawtext_outputs,
1533 };
Definition: lfg.h:27
AVFilterFormats * ff_draw_supported_pixel_formats(unsigned flags)
Return the list of pixel formats supported by the draw functions.
Definition: drawutils.c:731
#define NULL
Definition: coverity.c:32
static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:950
char * y_expr
expression for y position
Definition: vf_drawtext.c:182
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition: bprint.c:94
#define GET_UTF8(val, GET_BYTE, ERROR)
Convert a UTF-8 character (up to 4 bytes) to its 32-bit UCS-4 encoded form.
Definition: common.h:385
int tc24hmax
1 if timecode is wrapped to 24 hours, 0 otherwise
Definition: vf_drawtext.c:193
This structure describes decoded (raw) audio or video data.
Definition: frame.h:226
uint8_t * fontcolor_expr
fontcolor expression to evaluate
Definition: vf_drawtext.c:147
AVOption.
Definition: opt.h:246
void * av_realloc(void *ptr, size_t size)
Allocate, reallocate, or free a block of memory.
Definition: mem.c:135
int x
x position to start drawing text
Definition: vf_drawtext.c:153
static double drand(void *opaque, double min, double max)
Definition: vf_drawtext.c:98
static int func_metadata(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:959
static const AVOption drawtext_options[]
Definition: vf_drawtext.c:205
const char * fmt
Definition: avisynth_c.h:769
unsigned int fontsize
font size to use
Definition: vf_drawtext.c:161
FFDrawColor boxcolor
background color
Definition: vf_drawtext.c:175
#define AV_LOG_WARNING
Something somehow does not look correct.
Definition: log.h:182
static av_cold int parse_fontsize(AVFilterContext *ctx)
Definition: vf_drawtext.c:394
char * x_expr
expression for x position
Definition: vf_drawtext.c:181
Main libavfilter public API header.
uint8_t * fontfile
font to be used
Definition: vf_drawtext.c:144
int av_parse_time(int64_t *timeval, const char *timestr, int duration)
Parse timestr and return in *time a corresponding number of microseconds.
Definition: parseutils.c:587
static void drawtext(AVFrame *pic, int x, int y, const char *txt, uint32_t color)
Definition: af_afir.c:162
#define FLAGS
Definition: vf_drawtext.c:203
int num
Numerator.
Definition: rational.h:59
static const struct drawtext_function functions[]
const char * b
Definition: vf_curves.c:116
int av_set_options_string(void *ctx, const char *opts, const char *key_val_sep, const char *pairs_sep)
Parse the key/value pairs list in opts.
Definition: opt.c:1426
static int draw_text(AVFilterContext *ctx, AVFrame *frame, int width, int height)
Definition: vf_drawtext.c:1244
uint8_t * text
text to be drawn
Definition: vf_drawtext.c:145
void * av_tree_find(const AVTreeNode *t, void *key, int(*cmp)(const void *key, const void *b), void *next[2])
Definition: tree.c:39
const char * key
void * av_mallocz(size_t size)
Allocate a memory block with alignment suitable for all memory accesses (including vectors if availab...
Definition: mem.c:236
int av_expr_parse(AVExpr **expr, const char *s, const char *const *const_names, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), int log_offset, void *log_ctx)
Parse an expression.
Definition: eval.c:679
char * tc_opt_string
specified timecode option string
Definition: vf_drawtext.c:190
static int draw_glyphs(DrawTextContext *s, AVFrame *frame, int width, int height, FFDrawColor *color, int x, int y, int borderw)
Definition: vf_drawtext.c:1177
int(* func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int)
Definition: vf_drawtext.c:1072
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition: bprint.c:235
int boxborderw
box border width
Definition: vf_drawtext.c:166
#define AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC
Some filters support a generic "enable" expression option that can be used to enable or disable a fil...
Definition: avfilter.h:125
struct AVTreeNode * av_tree_node_alloc(void)
Allocate an AVTreeNode.
Definition: tree.c:34
expansion_mode
Definition: vf_drawtext.c:131
const char * name
Pad name.
Definition: internal.h:60
AVFilterLink ** inputs
array of pointers to input links
Definition: avfilter.h:346
int av_timecode_init_from_string(AVTimecode *tc, AVRational rate, const char *str, void *log_ctx)
Parse timecode representation (hh:mm:ss[:;.
Definition: timecode.c:194
int ff_filter_frame(AVFilterLink *link, AVFrame *frame)
Send a frame of data to the next filter.
Definition: avfilter.c:1080
FT_Stroker stroker
freetype stroker handle
Definition: vf_drawtext.c:179
static int glyph_enu_free(void *opaque, void *elem)
Definition: vf_drawtext.c:786
uint8_t
#define av_cold
Definition: attributes.h:82
static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:881
AVExpr * fontsize_pexpr
parsed expressions for fontsize
Definition: vf_drawtext.c:160
float delta
AVOptions.
A tree container.
AVLFG prng
random
Definition: vf_drawtext.c:189
static av_cold int end(AVCodecContext *avctx)
Definition: avrndec.c:90
FT_Face face
freetype font face handle
Definition: vf_drawtext.c:178
static int glyph_cmp(const void *key, const void *b)
Definition: vf_drawtext.c:296
int64_t pts
Presentation timestamp in time_base units (time when frame should be shown to user).
Definition: frame.h:319
static av_cold int init(AVFilterContext *ctx)
Definition: vf_drawtext.c:685
Definition: eval.c:157
int start_number
starting frame number for n/frame_num var
Definition: vf_drawtext.c:195
static AVFrame * frame
static int load_font_file(AVFilterContext *ctx, const char *path, int index)
Definition: vf_drawtext.c:448
Misc file utilities.
#define height
static const AVFilterPad avfilter_vf_drawtext_inputs[]
Definition: vf_drawtext.c:1502
AVDictionaryEntry * av_dict_get(const AVDictionary *m, const char *key, const AVDictionaryEntry *prev, int flags)
Get a dictionary entry with matching key.
Definition: dict.c:40
static double av_q2d(AVRational a)
Convert an AVRational to a double.
Definition: rational.h:104
uint32_t tag
Definition: movenc.c:1483
char av_get_picture_type_char(enum AVPictureType pict_type)
Return a single letter to describe the given picture type pict_type.
Definition: utils.c:88
const char * name
Definition: vf_drawtext.c:1069
AVDictionary * metadata
metadata.
Definition: frame.h:513
static av_cold void uninit(AVFilterContext *ctx)
Definition: vf_drawtext.c:796
ptrdiff_t size
Definition: opengl_enc.c:101
FT_Vector * positions
positions for each element in the text
Definition: vf_drawtext.c:150
AVExpr * x_pexpr
Definition: vf_drawtext.c:183
#define av_log(a,...)
void av_tree_destroy(AVTreeNode *t)
Definition: tree.c:146
int av_parse_color(uint8_t *rgba_color, const char *color_string, int slen, void *log_ctx)
Put the RGBA values that correspond to color_string in rgba_color.
Definition: parseutils.c:354
A filter pad used for either input or output.
Definition: internal.h:54
int av_expr_parse_and_eval(double *d, const char *s, const char *const *const_names, const double *const_values, const char *const *func1_names, double(*const *funcs1)(void *, double), const char *const *func2_names, double(*const *funcs2)(void *, double, double), void *opaque, int log_offset, void *log_ctx)
Parse and evaluate an expression.
Definition: eval.c:744
double var_values[VAR_VARS_NB]
Definition: vf_drawtext.c:185
int width
Definition: frame.h:284
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition: log.h:176
void av_file_unmap(uint8_t *bufptr, size_t size)
Unmap or free the buffer bufptr created by av_file_map().
Definition: file.c:139
int ff_set_common_formats(AVFilterContext *ctx, AVFilterFormats *formats)
A helper for query_formats() which sets all links to the same list of formats.
Definition: formats.c:568
AVBPrint expanded_text
used to contain the expanded text
Definition: vf_drawtext.c:146
int av_file_map(const char *filename, uint8_t **bufptr, size_t *size, int log_offset, void *log_ctx)
Read the file with name filename, and put its content in a newly allocated buffer or map it with mmap...
Definition: file.c:53
#define AV_BPRINT_SIZE_UNLIMITED
static const uint16_t positions[][14][3]
#define AVERROR(e)
Definition: error.h:43
void av_frame_free(AVFrame **frame)
Free the frame and any dynamically allocated objects in it, e.g.
Definition: frame.c:202
AVExpr * y_pexpr
parsed expressions for x and y
Definition: vf_drawtext.c:183
const char * err_msg
Definition: vf_drawtext.c:277
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:186
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition: bprint.c:69
void * priv
private data for use by the filter
Definition: avfilter.h:353
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition: log.h:197
int y
y position to start drawing text
Definition: vf_drawtext.c:154
const char * arg
Definition: jacosubdec.c:66
void ff_draw_color(FFDrawContext *draw, FFDrawColor *color, const uint8_t rgba[4])
Prepare a color.
Definition: drawutils.c:231
static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
Definition: vf_drawtext.c:1114
uint8_t vsub_max
Definition: drawutils.h:57
static av_always_inline av_const double round(double x)
Definition: libm.h:444
FFDrawColor fontcolor
foreground color
Definition: vf_drawtext.c:172
AVExpr * a_pexpr
Definition: vf_drawtext.c:187
#define FFMAX(a, b)
Definition: common.h:94
#define fail()
Definition: checkasm.h:117
char * av_get_token(const char **buf, const char *term)
Unescape the given string until a non escaped terminating char, and return the token corresponding to...
Definition: avstring.c:149
static const char *const fun2_names[]
Definition: vf_drawtext.c:94
static struct tm * gmtime_r(const time_t *clock, struct tm *result)
Definition: time_internal.h:26
int reload
reload text file for each frame
Definition: vf_drawtext.c:194
AVBPrint expanded_fontcolor
used to contain the expanded fontcolor spec
Definition: vf_drawtext.c:148
var_name
Definition: aeval.c:46
FFDrawContext dc
Definition: vf_drawtext.c:171
#define FFDIFFSIGN(x, y)
Comparator.
Definition: common.h:92
static const struct ft_error ft_errors[]
enum AVPictureType pict_type
Picture type of the frame.
Definition: frame.h:309
#define NAN
Definition: mathematics.h:64
#define FF_DRAW_PROCESS_ALPHA
Process alpha pixel component.
Definition: drawutils.h:74
#define AV_TIME_BASE
Internal time base represented as integer.
Definition: avutil.h:254
#define FFMIN(a, b)
Definition: common.h:96
static struct tm * localtime_r(const time_t *clock, struct tm *result)
Definition: time_internal.h:37
#define width
int64_t basetime
base pts time in the real world for display
Definition: vf_drawtext.c:184
char * fontsize_expr
expression for fontsize
Definition: vf_drawtext.c:159
AVFormatContext * ctx
Definition: movenc.c:48
int max_glyph_h
max glyph height
Definition: vf_drawtext.c:156
AVRational tc_rate
frame rate for timecode
Definition: vf_drawtext.c:191
#define FFABS(a)
Absolute value, Note, INT_MIN / INT64_MIN result in undefined behavior as they are not representable ...
Definition: common.h:72
#define s(width, name)
Definition: cbs_vp9.c:257
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition: bprint.h:185
int dummy
Definition: motion.c:64
static const AVFilterPad inputs[]
Definition: af_acontrast.c:193
static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:988
double(* eval_func2)(void *, double a, double b)
Definition: vf_drawtext.c:103
static void error(const char *err)
static const AVFilterPad outputs[]
Definition: af_acontrast.c:203
#define FF_ARRAY_ELEMS(a)
AVTimecode tc
timecode context
Definition: vf_drawtext.c:192
static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
Definition: vf_drawtext.c:1222
void ff_blend_mask(FFDrawContext *draw, FFDrawColor *color, uint8_t *dst[], int dst_linesize[], int dst_w, int dst_h, const uint8_t *mask, int mask_linesize, int mask_w, int mask_h, int l2depth, unsigned endianness, int x0, int y0)
Blend an alpha mask with an uniform color.
Definition: drawutils.c:622
#define AV_LOG_INFO
Standard information.
Definition: log.h:187
char * av_strdup(const char *s)
Duplicate a string.
Definition: mem.c:251
misc drawing utilities
void av_expr_free(AVExpr *e)
Free a parsed expression previously created with av_expr_parse().
Definition: eval.c:334
Timecode helpers header.
int linesize[AV_NUM_DATA_POINTERS]
For video, size in bytes of each picture line.
Definition: frame.h:257
static const int16_t alpha[]
Definition: ilbcdata.h:55
static int load_font(AVFilterContext *ctx)
Definition: vf_drawtext.c:548
static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
Definition: vf_drawtext.c:863
timecode wraps after 24 hours
Definition: timecode.h:37
int borderw
border width
Definition: vf_drawtext.c:158
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition: lfg.h:47
#define llrint(x)
Definition: libm.h:394
uint8_t hsub_max
Definition: drawutils.h:56
Describe the class of an AVClass context structure.
Definition: log.h:67
Filter definition.
Definition: avfilter.h:144
int tabsize
tab size
Definition: vf_drawtext.c:168
int index
Definition: gxfenc.c:89
static int func_strftime(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:972
Rational number (pair of numerator and denominator).
Definition: rational.h:58
void ff_blend_rectangle(FFDrawContext *draw, FFDrawColor *color, uint8_t *dst[], int dst_linesize[], int dst_w, int dst_h, int x0, int y0, int w, int h)
Blend a rectangle with an uniform color.
Definition: drawutils.c:445
#define isnan(x)
Definition: libm.h:340
struct AVTreeNode * glyphs
rendered glyphs, stored using the UTF-32 char code
Definition: vf_drawtext.c:180
size_t av_strlcatf(char *dst, size_t size, const char *fmt,...)
Definition: avstring.c:101
static int is_newline(uint32_t c)
Definition: vf_drawtext.c:592
const char * name
Filter name.
Definition: avfilter.h:148
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition: lfg.c:32
int ff_draw_init(FFDrawContext *draw, enum AVPixelFormat format, unsigned flags)
Init a draw context.
Definition: drawutils.c:178
static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
Definition: vf_drawtext.c:1154
misc parsing utilities
AVFilterLink ** outputs
array of pointers to output links
Definition: avfilter.h:350
int tag
opaque argument to func
Definition: vf_drawtext.c:1071
short int draw_box
draw box around text - true or false
Definition: vf_drawtext.c:165
static int config_input(AVFilterLink *inlink)
Definition: vf_drawtext.c:822
static int64_t pts
#define flags(name, subs,...)
Definition: cbs_av1.c:596
AVDictionary * metadata
Definition: vf_drawtext.c:199
uint8_t * data[AV_NUM_DATA_POINTERS]
pointer to the picture/channel planes.
Definition: frame.h:240
void av_bprint_strftime(AVBPrint *buf, const char *fmt, const struct tm *tm)
Append a formatted date and time to a print buffer.
Definition: bprint.c:176
char * av_timecode_make_string(const AVTimecode *tc, char *buf, int framenum)
Load timecode string in buf.
Definition: timecode.c:84
AVFILTER_DEFINE_CLASS(drawtext)
void av_bprint_clear(AVBPrint *buf)
Reset the string to "" but keep internal allocated data.
Definition: bprint.c:227
static void update_alpha(DrawTextContext *s)
Definition: vf_drawtext.c:1229
static const char *const var_names[]
Definition: vf_drawtext.c:73
int use_kerning
font kerning is used - true/false
Definition: vf_drawtext.c:167
int
common internal and external API header
static double c[64]
static int query_formats(AVFilterContext *ctx)
Definition: vf_drawtext.c:781
FT_Library library
freetype font library handle
Definition: vf_drawtext.c:177
#define AVERROR_UNKNOWN
Unknown error, typically from an external library.
Definition: error.h:71
static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
Definition: vf_drawtext.c:1464
static const AVFilterPad avfilter_vf_drawtext_outputs[]
Definition: vf_drawtext.c:1513
AVFilter ff_vf_drawtext
Definition: vf_drawtext.c:1521
static av_always_inline int diff(const uint32_t a, const uint32_t b)
#define av_free(p)
char * value
Definition: dict.h:87
int len
double av_expr_eval(AVExpr *e, const double *const_values, void *opaque)
Evaluate a previously parsed expression.
Definition: eval.c:734
#define FT_ERRMSG(e)
int reinit
tells if the filter is being reinited
Definition: vf_drawtext.c:140
FFDrawColor shadowcolor
shadow color
Definition: vf_drawtext.c:173
static av_cold int update_fontsize(AVFilterContext *ctx)
Definition: vf_drawtext.c:412
#define OFFSET(x)
Definition: vf_drawtext.c:202
void * av_tree_insert(AVTreeNode **tp, void *key, int(*cmp)(const void *key, const void *b), AVTreeNode **next)
Insert or remove an element.
Definition: tree.c:59
int line_spacing
lines spacing in pixels
Definition: vf_drawtext.c:164
An instance of a filter.
Definition: avfilter.h:338
int max_glyph_w
max glyph width
Definition: vf_drawtext.c:155
static const eval_func2 fun2[]
Definition: vf_drawtext.c:105
int height
Definition: frame.h:284
static int func_pts(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:890
FILE * out
Definition: movenc.c:54
unsigned int default_fontsize
default font size to use
Definition: vf_drawtext.c:162
static int process_command(AVFilterContext *ctx, const char *cmd, const char *args, char *res, int res_len, int flags)
Definition: af_afftdn.c:1373
#define av_freep(p)
int fix_bounds
do we let it go out of frame bounds - t/f
Definition: vf_drawtext.c:169
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
Definition: random_seed.c:120
#define av_malloc_array(a, b)
char * textfile
file with text to be drawn
Definition: vf_drawtext.c:152
internal API functions
static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
Load glyphs corresponding to the UTF-32 codepoint code.
Definition: vf_drawtext.c:310
static int load_textfile(AVFilterContext *ctx)
Definition: vf_drawtext.c:565
static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv)
Definition: vf_drawtext.c:1087
int ft_load_flags
flags used for loading fonts, see FT_LOAD_*
Definition: vf_drawtext.c:149
int exp_mode
expansion mode to use for the text
Definition: vf_drawtext.c:139
uint32_t flags
flags such as drop frame, +24 hours support, ...
Definition: timecode.h:43
void av_tree_enumerate(AVTreeNode *t, void *opaque, int(*cmp)(void *opaque, void *elem), int(*enu)(void *opaque, void *elem))
Apply enu(opaque, &elem) to all the elements in the tree in a given range.
Definition: tree.c:155
float min
#define AVERROR_EXTERNAL
Generic error in an external library.
Definition: error.h:57
size_t nb_positions
number of elements of positions array
Definition: vf_drawtext.c:151
FFDrawColor bordercolor
border color
Definition: vf_drawtext.c:174
#define FFMAX3(a, b, c)
Definition: common.h:95
#define AV_NOPTS_VALUE
Undefined timestamp value.
Definition: avutil.h:248
static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
Definition: vf_drawtext.c:378
void * elem
Definition: tree.c:28
#define AV_TIMECODE_STR_SIZE
Definition: timecode.h:33
simple arithmetic expression evaluator
uint8_t rgba[4]
Definition: drawutils.h:63
const char * name
Definition: opengl_enc.c:103
static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp, char *fct, unsigned argc, char **argv, int tag)
Definition: vf_drawtext.c:1008
void av_bprint_chars(AVBPrint *buf, char c, unsigned n)
Append char c n times to a print buffer.
Definition: bprint.c:140
static uint8_t tmp[11]
Definition: aes_ctr.c:26