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 
41 #if CONFIG_LIBFONTCONFIG
42 #include <fontconfig/fontconfig.h>
43 #endif
44 
45 #include "libavutil/avstring.h"
46 #include "libavutil/bprint.h"
47 #include "libavutil/common.h"
48 #include "libavutil/file.h"
49 #include "libavutil/eval.h"
50 #include "libavutil/opt.h"
51 #include "libavutil/random_seed.h"
52 #include "libavutil/parseutils.h"
53 #include "libavutil/timecode.h"
54 #include "libavutil/tree.h"
55 #include "libavutil/lfg.h"
56 #include "avfilter.h"
57 #include "drawutils.h"
58 #include "formats.h"
59 #include "internal.h"
60 #include "video.h"
61 
62 #if CONFIG_LIBFRIBIDI
63 #include <fribidi.h>
64 #endif
65 
66 #include <ft2build.h>
67 #include FT_FREETYPE_H
68 #include FT_GLYPH_H
69 #include FT_STROKER_H
70 
71 static const char *const var_names[] = {
72  "dar",
73  "hsub", "vsub",
74  "line_h", "lh", ///< line height, same as max_glyph_h
75  "main_h", "h", "H", ///< height of the input video
76  "main_w", "w", "W", ///< width of the input video
77  "max_glyph_a", "ascent", ///< max glyph ascent
78  "max_glyph_d", "descent", ///< min glyph descent
79  "max_glyph_h", ///< max glyph height
80  "max_glyph_w", ///< max glyph width
81  "n", ///< number of frame
82  "sar",
83  "t", ///< timestamp expressed in seconds
84  "text_h", "th", ///< height of the rendered text
85  "text_w", "tw", ///< width of the rendered text
86  "x",
87  "y",
88  "pict_type",
89  NULL
90 };
91 
92 static const char *const fun2_names[] = {
93  "rand"
94 };
95 
96 static double drand(void *opaque, double min, double max)
97 {
98  return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
99 }
100 
101 typedef double (*eval_func2)(void *, double a, double b);
102 
103 static const eval_func2 fun2[] = {
104  drand,
105  NULL
106 };
107 
108 enum var_name {
127 };
128 
133 };
134 
135 typedef struct DrawTextContext {
136  const AVClass *class;
137  enum expansion_mode exp_mode; ///< expansion mode to use for the text
138  int reinit; ///< tells if the filter is being reinited
139 #if CONFIG_LIBFONTCONFIG
140  uint8_t *font; ///< font to be used
141 #endif
142  uint8_t *fontfile; ///< font to be used
143  uint8_t *text; ///< text to be drawn
144  AVBPrint expanded_text; ///< used to contain the expanded text
145  int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
146  FT_Vector *positions; ///< positions for each element in the text
147  size_t nb_positions; ///< number of elements of positions array
148  char *textfile; ///< file with text to be drawn
149  int x; ///< x position to start drawing text
150  int y; ///< y position to start drawing text
151  int max_glyph_w; ///< max glyph width
152  int max_glyph_h; ///< max glyph height
154  int borderw; ///< border width
155  unsigned int fontsize; ///< font size to use
156 
157  short int draw_box; ///< draw box around text - true or false
158  int use_kerning; ///< font kerning is used - true/false
159  int tabsize; ///< tab size
160  int fix_bounds; ///< do we let it go out of frame bounds - t/f
161 
163  FFDrawColor fontcolor; ///< foreground color
164  FFDrawColor shadowcolor; ///< shadow color
165  FFDrawColor bordercolor; ///< border color
166  FFDrawColor boxcolor; ///< background color
167 
168  FT_Library library; ///< freetype font library handle
169  FT_Face face; ///< freetype font face handle
170  FT_Stroker stroker; ///< freetype stroker handle
171  struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
172  char *x_expr; ///< expression for x position
173  char *y_expr; ///< expression for y position
174  AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
175  int64_t basetime; ///< base pts time in the real world for display
177 #if FF_API_DRAWTEXT_OLD_TIMELINE
178  char *draw_expr; ///< expression for draw
179  AVExpr *draw_pexpr; ///< parsed expression for draw
180  int draw; ///< set to zero to prevent drawing
181 #endif
182  AVLFG prng; ///< random
183  char *tc_opt_string; ///< specified timecode option string
184  AVRational tc_rate; ///< frame rate for timecode
185  AVTimecode tc; ///< timecode context
186  int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
187  int reload; ///< reload text file for each frame
188  int start_number; ///< starting frame number for n/frame_num var
189 #if CONFIG_LIBFRIBIDI
190  int text_shaping; ///< 1 to shape the text before drawing it
191 #endif
194 
195 #define OFFSET(x) offsetof(DrawTextContext, x)
196 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
197 
198 static const AVOption drawtext_options[]= {
199  {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
200  {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
201  {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
202  {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
203  {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
204  {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
205  {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
206  {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
207  {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
208  {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
209  {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
210  {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
211  {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
212  {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
213  {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
214  {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
215 #if FF_API_DRAWTEXT_OLD_TIMELINE
216  {"draw", "if false do not draw (deprecated)", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
217 #endif
218 #if CONFIG_LIBFONTCONFIG
219  { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
220 #endif
221 
222  {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
223  {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
224  {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
225  {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
226 
227  {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
228  {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
229  {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
230  {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
231  {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
232  {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
233  {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
234  {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
235 
236 #if CONFIG_LIBFRIBIDI
237  {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
238 #endif
239 
240  /* FT_LOAD_* flags */
241  { "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" },
242  { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
243  { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
244  { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
245  { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
246  { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
247  { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
248  { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
249  { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
250  { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
251  { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
252  { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
253  { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
254  { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
255  { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
256  { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
257  { NULL }
258 };
259 
261 
262 #undef __FTERRORS_H__
263 #define FT_ERROR_START_LIST {
264 #define FT_ERRORDEF(e, v, s) { (e), (s) },
265 #define FT_ERROR_END_LIST { 0, NULL } };
266 
267 struct ft_error
268 {
269  int err;
270  const char *err_msg;
271 } static ft_errors[] =
272 #include FT_ERRORS_H
273 
274 #define FT_ERRMSG(e) ft_errors[e].err_msg
275 
276 typedef struct Glyph {
277  FT_Glyph glyph;
278  FT_Glyph border_glyph;
279  uint32_t code;
280  FT_Bitmap bitmap; ///< array holding bitmaps of font
281  FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
282  FT_BBox bbox;
283  int advance;
284  int bitmap_left;
285  int bitmap_top;
286 } Glyph;
287 
288 static int glyph_cmp(void *key, const void *b)
289 {
290  const Glyph *a = key, *bb = b;
291  int64_t diff = (int64_t)a->code - (int64_t)bb->code;
292  return diff > 0 ? 1 : diff < 0 ? -1 : 0;
293 }
294 
295 /**
296  * Load glyphs corresponding to the UTF-32 codepoint code.
297  */
298 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
299 {
300  DrawTextContext *s = ctx->priv;
301  FT_BitmapGlyph bitmapglyph;
302  Glyph *glyph;
303  struct AVTreeNode *node = NULL;
304  int ret;
305 
306  /* load glyph into s->face->glyph */
307  if (FT_Load_Char(s->face, code, s->ft_load_flags))
308  return AVERROR(EINVAL);
309 
310  glyph = av_mallocz(sizeof(*glyph));
311  if (!glyph) {
312  ret = AVERROR(ENOMEM);
313  goto error;
314  }
315  glyph->code = code;
316 
317  if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
318  ret = AVERROR(EINVAL);
319  goto error;
320  }
321  if (s->borderw) {
322  glyph->border_glyph = glyph->glyph;
323  if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
324  FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
325  ret = AVERROR_EXTERNAL;
326  goto error;
327  }
328  bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
329  glyph->border_bitmap = bitmapglyph->bitmap;
330  }
331  if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
332  ret = AVERROR_EXTERNAL;
333  goto error;
334  }
335  bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
336 
337  glyph->bitmap = bitmapglyph->bitmap;
338  glyph->bitmap_left = bitmapglyph->left;
339  glyph->bitmap_top = bitmapglyph->top;
340  glyph->advance = s->face->glyph->advance.x >> 6;
341 
342  /* measure text height to calculate text_height (or the maximum text height) */
343  FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
344 
345  /* cache the newly created glyph */
346  if (!(node = av_tree_node_alloc())) {
347  ret = AVERROR(ENOMEM);
348  goto error;
349  }
350  av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
351 
352  if (glyph_ptr)
353  *glyph_ptr = glyph;
354  return 0;
355 
356 error:
357  if (glyph)
358  av_freep(&glyph->glyph);
359 
360  av_freep(&glyph);
361  av_freep(&node);
362  return ret;
363 }
364 
365 static int load_font_file(AVFilterContext *ctx, const char *path, int index)
366 {
367  DrawTextContext *s = ctx->priv;
368  int err;
369 
370  err = FT_New_Face(s->library, path, index, &s->face);
371  if (err) {
372  av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
373  s->fontfile, FT_ERRMSG(err));
374  return AVERROR(EINVAL);
375  }
376  return 0;
377 }
378 
379 #if CONFIG_LIBFONTCONFIG
380 static int load_font_fontconfig(AVFilterContext *ctx)
381 {
382  DrawTextContext *s = ctx->priv;
383  FcConfig *fontconfig;
384  FcPattern *pat, *best;
385  FcResult result = FcResultMatch;
386  FcChar8 *filename;
387  int index;
388  double size;
389  int err = AVERROR(ENOENT);
390 
391  fontconfig = FcInitLoadConfigAndFonts();
392  if (!fontconfig) {
393  av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
394  return AVERROR_UNKNOWN;
395  }
396  pat = FcNameParse(s->fontfile ? s->fontfile :
397  (uint8_t *)(intptr_t)"default");
398  if (!pat) {
399  av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
400  return AVERROR(EINVAL);
401  }
402 
403  FcPatternAddString(pat, FC_FAMILY, s->font);
404  if (s->fontsize)
405  FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
406 
407  FcDefaultSubstitute(pat);
408 
409  if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
410  av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
411  FcPatternDestroy(pat);
412  return AVERROR(ENOMEM);
413  }
414 
415  best = FcFontMatch(fontconfig, pat, &result);
416  FcPatternDestroy(pat);
417 
418  if (!best || result != FcResultMatch) {
419  av_log(ctx, AV_LOG_ERROR,
420  "Cannot find a valid font for the family %s\n",
421  s->font);
422  goto fail;
423  }
424 
425  if (
426  FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
427  FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
428  av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
429  return AVERROR(EINVAL);
430  }
431 
432  if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
433  av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
434  s->font);
435  goto fail;
436  }
437 
438  av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
439  if (!s->fontsize)
440  s->fontsize = size + 0.5;
441 
442  err = load_font_file(ctx, filename, index);
443  if (err)
444  return err;
445  FcConfigDestroy(fontconfig);
446 fail:
447  FcPatternDestroy(best);
448  return err;
449 }
450 #endif
451 
452 static int load_font(AVFilterContext *ctx)
453 {
454  DrawTextContext *s = ctx->priv;
455  int err;
456 
457  /* load the face, and set up the encoding, which is by default UTF-8 */
458  err = load_font_file(ctx, s->fontfile, 0);
459  if (!err)
460  return 0;
461 #if CONFIG_LIBFONTCONFIG
462  err = load_font_fontconfig(ctx);
463  if (!err)
464  return 0;
465 #endif
466  return err;
467 }
468 
470 {
471  DrawTextContext *s = ctx->priv;
472  int err;
473  uint8_t *textbuf;
474  uint8_t *tmp;
475  size_t textbuf_size;
476 
477  if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
478  av_log(ctx, AV_LOG_ERROR,
479  "The text file '%s' could not be read or is empty\n",
480  s->textfile);
481  return err;
482  }
483 
484  if (!(tmp = av_realloc(s->text, textbuf_size + 1))) {
485  av_file_unmap(textbuf, textbuf_size);
486  return AVERROR(ENOMEM);
487  }
488  s->text = tmp;
489  memcpy(s->text, textbuf, textbuf_size);
490  s->text[textbuf_size] = 0;
491  av_file_unmap(textbuf, textbuf_size);
492 
493  return 0;
494 }
495 
496 static inline int is_newline(uint32_t c)
497 {
498  return c == '\n' || c == '\r' || c == '\f' || c == '\v';
499 }
500 
501 #if CONFIG_LIBFRIBIDI
502 static int shape_text(AVFilterContext *ctx)
503 {
504  DrawTextContext *s = ctx->priv;
505  uint8_t *tmp;
506  int ret = AVERROR(ENOMEM);
507  static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
508  FRIBIDI_FLAGS_ARABIC;
509  FriBidiChar *unicodestr = NULL;
510  FriBidiStrIndex len;
511  FriBidiParType direction = FRIBIDI_PAR_LTR;
512  FriBidiStrIndex line_start = 0;
513  FriBidiStrIndex line_end = 0;
514  FriBidiLevel *embedding_levels = NULL;
515  FriBidiArabicProp *ar_props = NULL;
516  FriBidiCharType *bidi_types = NULL;
517  FriBidiStrIndex i,j;
518 
519  len = strlen(s->text);
520  if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
521  goto out;
522  }
523  len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
524  s->text, len, unicodestr);
525 
526  bidi_types = av_malloc_array(len, sizeof(*bidi_types));
527  if (!bidi_types) {
528  goto out;
529  }
530 
531  fribidi_get_bidi_types(unicodestr, len, bidi_types);
532 
533  embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
534  if (!embedding_levels) {
535  goto out;
536  }
537 
538  if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
539  embedding_levels)) {
540  goto out;
541  }
542 
543  ar_props = av_malloc_array(len, sizeof(*ar_props));
544  if (!ar_props) {
545  goto out;
546  }
547 
548  fribidi_get_joining_types(unicodestr, len, ar_props);
549  fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
550  fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
551 
552  for (line_end = 0, line_start = 0; line_end < len; line_end++) {
553  if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
554  if (!fribidi_reorder_line(flags, bidi_types,
555  line_end - line_start + 1, line_start,
556  direction, embedding_levels, unicodestr,
557  NULL)) {
558  goto out;
559  }
560  line_start = line_end + 1;
561  }
562  }
563 
564  /* Remove zero-width fill chars put in by libfribidi */
565  for (i = 0, j = 0; i < len; i++)
566  if (unicodestr[i] != FRIBIDI_CHAR_FILL)
567  unicodestr[j++] = unicodestr[i];
568  len = j;
569 
570  if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
571  /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
572  goto out;
573  }
574 
575  s->text = tmp;
576  len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
577  unicodestr, len, s->text);
578  ret = 0;
579 
580 out:
581  av_free(unicodestr);
582  av_free(embedding_levels);
583  av_free(ar_props);
584  av_free(bidi_types);
585  return ret;
586 }
587 #endif
588 
589 static av_cold int init(AVFilterContext *ctx)
590 {
591  int err;
592  DrawTextContext *s = ctx->priv;
593  Glyph *glyph;
594 
595 #if FF_API_DRAWTEXT_OLD_TIMELINE
596  if (s->draw_expr)
597  av_log(ctx, AV_LOG_WARNING, "'draw' option is deprecated and will be removed soon, "
598  "you are encouraged to use the generic timeline support through the 'enable' option\n");
599 #endif
600 
601  if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
602  av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
603  return AVERROR(EINVAL);
604  }
605 
606  if (s->textfile) {
607  if (s->text) {
608  av_log(ctx, AV_LOG_ERROR,
609  "Both text and text file provided. Please provide only one\n");
610  return AVERROR(EINVAL);
611  }
612  if ((err = load_textfile(ctx)) < 0)
613  return err;
614  }
615 
616 #if CONFIG_LIBFRIBIDI
617  if (s->text_shaping)
618  if ((err = shape_text(ctx)) < 0)
619  return err;
620 #endif
621 
622  if (s->reload && !s->textfile)
623  av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
624 
625  if (s->tc_opt_string) {
626  int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
627  s->tc_opt_string, ctx);
628  if (ret < 0)
629  return ret;
630  if (s->tc24hmax)
632  if (!s->text)
633  s->text = av_strdup("");
634  }
635 
636  if (!s->text) {
637  av_log(ctx, AV_LOG_ERROR,
638  "Either text, a valid file or a timecode must be provided\n");
639  return AVERROR(EINVAL);
640  }
641 
642  if ((err = FT_Init_FreeType(&(s->library)))) {
643  av_log(ctx, AV_LOG_ERROR,
644  "Could not load FreeType: %s\n", FT_ERRMSG(err));
645  return AVERROR(EINVAL);
646  }
647 
648  err = load_font(ctx);
649  if (err)
650  return err;
651  if (!s->fontsize)
652  s->fontsize = 16;
653  if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
654  av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
655  s->fontsize, FT_ERRMSG(err));
656  return AVERROR(EINVAL);
657  }
658 
659  if (s->borderw) {
660  if (FT_Stroker_New(s->library, &s->stroker)) {
661  av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
662  return AVERROR_EXTERNAL;
663  }
664  FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
665  FT_STROKER_LINEJOIN_ROUND, 0);
666  }
667 
668  s->use_kerning = FT_HAS_KERNING(s->face);
669 
670  /* load the fallback glyph with code 0 */
671  load_glyph(ctx, NULL, 0);
672 
673  /* set the tabsize in pixels */
674  if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
675  av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
676  return err;
677  }
678  s->tabsize *= glyph->advance;
679 
680  if (s->exp_mode == EXP_STRFTIME &&
681  (strchr(s->text, '%') || strchr(s->text, '\\')))
682  av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
683 
685 
686  return 0;
687 }
688 
690 {
692  return 0;
693 }
694 
695 static int glyph_enu_free(void *opaque, void *elem)
696 {
697  Glyph *glyph = elem;
698 
699  FT_Done_Glyph(glyph->glyph);
700  FT_Done_Glyph(glyph->border_glyph);
701  av_free(elem);
702  return 0;
703 }
704 
705 static av_cold void uninit(AVFilterContext *ctx)
706 {
707  DrawTextContext *s = ctx->priv;
708 
709  av_expr_free(s->x_pexpr);
710  av_expr_free(s->y_pexpr);
711 #if FF_API_DRAWTEXT_OLD_TIMELINE
713  s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
714 #endif
715  av_freep(&s->positions);
716  s->nb_positions = 0;
717 
718 
719  av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
721  s->glyphs = NULL;
722 
723  FT_Done_Face(s->face);
724  FT_Stroker_Done(s->stroker);
725  FT_Done_FreeType(s->library);
726 
728 }
729 
730 static int config_input(AVFilterLink *inlink)
731 {
732  AVFilterContext *ctx = inlink->dst;
733  DrawTextContext *s = ctx->priv;
734  int ret;
735 
736  ff_draw_init(&s->dc, inlink->format, 0);
737  ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
740  ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
741 
742  s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
743  s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
745  s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
746  s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
747  s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
748  s->var_values[VAR_X] = NAN;
749  s->var_values[VAR_Y] = NAN;
750  s->var_values[VAR_T] = NAN;
751 
753 
754  av_expr_free(s->x_pexpr);
755  av_expr_free(s->y_pexpr);
756 #if FF_API_DRAWTEXT_OLD_TIMELINE
758  s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
759 #else
760  s->x_pexpr = s->y_pexpr = NULL;
761 #endif
762 
763  if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
764  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
765  (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
766  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
767 
768  return AVERROR(EINVAL);
769 #if FF_API_DRAWTEXT_OLD_TIMELINE
770  if (s->draw_expr &&
772  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
773  return ret;
774 #endif
775 
776  return 0;
777 }
778 
779 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
780 {
781  DrawTextContext *s = ctx->priv;
782 
783  if (!strcmp(cmd, "reinit")) {
784  int ret;
785  uninit(ctx);
786  s->reinit = 1;
787  if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
788  return ret;
789  if ((ret = init(ctx)) < 0)
790  return ret;
791  return config_input(ctx->inputs[0]);
792  }
793 
794  return AVERROR(ENOSYS);
795 }
796 
798  char *fct, unsigned argc, char **argv, int tag)
799 {
800  DrawTextContext *s = ctx->priv;
801 
803  return 0;
804 }
805 
806 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
807  char *fct, unsigned argc, char **argv, int tag)
808 {
809  DrawTextContext *s = ctx->priv;
810  const char *fmt;
811  double pts = s->var_values[VAR_T];
812  int ret;
813 
814  fmt = argc >= 1 ? argv[0] : "flt";
815  if (argc >= 2) {
816  int64_t delta;
817  if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
818  av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
819  return ret;
820  }
821  pts += (double)delta / AV_TIME_BASE;
822  }
823  if (!strcmp(fmt, "flt")) {
824  av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
825  } else if (!strcmp(fmt, "hms")) {
826  if (isnan(pts)) {
827  av_bprintf(bp, " ??:??:??.???");
828  } else {
829  int64_t ms = round(pts * 1000);
830  char sign = ' ';
831  if (ms < 0) {
832  sign = '-';
833  ms = -ms;
834  }
835  av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
836  (int)(ms / (60 * 60 * 1000)),
837  (int)(ms / (60 * 1000)) % 60,
838  (int)(ms / 1000) % 60,
839  (int)ms % 1000);
840  }
841  } else {
842  av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
843  return AVERROR(EINVAL);
844  }
845  return 0;
846 }
847 
849  char *fct, unsigned argc, char **argv, int tag)
850 {
851  DrawTextContext *s = ctx->priv;
852 
853  av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
854  return 0;
855 }
856 
858  char *fct, unsigned argc, char **argv, int tag)
859 {
860  DrawTextContext *s = ctx->priv;
861  AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
862 
863  if (e && e->value)
864  av_bprintf(bp, "%s", e->value);
865  return 0;
866 }
867 
868 #if !HAVE_LOCALTIME_R
869 static void localtime_r(const time_t *t, struct tm *tm)
870 {
871  *tm = *localtime(t);
872 }
873 #endif
874 
876  char *fct, unsigned argc, char **argv, int tag)
877 {
878  const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
879  time_t now;
880  struct tm tm;
881 
882  time(&now);
883  if (tag == 'L')
884  localtime_r(&now, &tm);
885  else
886  tm = *gmtime(&now);
887  av_bprint_strftime(bp, fmt, &tm);
888  return 0;
889 }
890 
892  char *fct, unsigned argc, char **argv, int tag)
893 {
894  DrawTextContext *s = ctx->priv;
895  double res;
896  int ret;
897 
898  ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
899  NULL, NULL, fun2_names, fun2,
900  &s->prng, 0, ctx);
901  if (ret < 0)
902  av_log(ctx, AV_LOG_ERROR,
903  "Expression '%s' for the expr text expansion function is not valid\n",
904  argv[0]);
905  else
906  av_bprintf(bp, "%f", res);
907 
908  return ret;
909 }
910 
911 static const struct drawtext_function {
912  const char *name;
913  unsigned argc_min, argc_max;
914  int tag; /**< opaque argument to func */
915  int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
916 } functions[] = {
917  { "expr", 1, 1, 0, func_eval_expr },
918  { "e", 1, 1, 0, func_eval_expr },
919  { "pict_type", 0, 0, 0, func_pict_type },
920  { "pts", 0, 2, 0, func_pts },
921  { "gmtime", 0, 1, 'G', func_strftime },
922  { "localtime", 0, 1, 'L', func_strftime },
923  { "frame_num", 0, 0, 0, func_frame_num },
924  { "n", 0, 0, 0, func_frame_num },
925  { "metadata", 1, 1, 0, func_metadata },
926 };
927 
928 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
929  unsigned argc, char **argv)
930 {
931  unsigned i;
932 
933  for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
934  if (strcmp(fct, functions[i].name))
935  continue;
936  if (argc < functions[i].argc_min) {
937  av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
938  fct, functions[i].argc_min);
939  return AVERROR(EINVAL);
940  }
941  if (argc > functions[i].argc_max) {
942  av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
943  fct, functions[i].argc_max);
944  return AVERROR(EINVAL);
945  }
946  break;
947  }
948  if (i >= FF_ARRAY_ELEMS(functions)) {
949  av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
950  return AVERROR(EINVAL);
951  }
952  return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
953 }
954 
955 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
956 {
957  const char *text = *rtext;
958  char *argv[16] = { NULL };
959  unsigned argc = 0, i;
960  int ret;
961 
962  if (*text != '{') {
963  av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
964  return AVERROR(EINVAL);
965  }
966  text++;
967  while (1) {
968  if (!(argv[argc++] = av_get_token(&text, ":}"))) {
969  ret = AVERROR(ENOMEM);
970  goto end;
971  }
972  if (!*text) {
973  av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
974  ret = AVERROR(EINVAL);
975  goto end;
976  }
977  if (argc == FF_ARRAY_ELEMS(argv))
978  av_freep(&argv[--argc]); /* error will be caught later */
979  if (*text == '}')
980  break;
981  text++;
982  }
983 
984  if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
985  goto end;
986  ret = 0;
987  *rtext = (char *)text + 1;
988 
989 end:
990  for (i = 0; i < argc; i++)
991  av_freep(&argv[i]);
992  return ret;
993 }
994 
995 static int expand_text(AVFilterContext *ctx)
996 {
997  DrawTextContext *s = ctx->priv;
998  char *text = s->text;
999  AVBPrint *bp = &s->expanded_text;
1000  int ret;
1001 
1002  av_bprint_clear(bp);
1003  while (*text) {
1004  if (*text == '\\' && text[1]) {
1005  av_bprint_chars(bp, text[1], 1);
1006  text += 2;
1007  } else if (*text == '%') {
1008  text++;
1009  if ((ret = expand_function(ctx, bp, &text)) < 0)
1010  return ret;
1011  } else {
1012  av_bprint_chars(bp, *text, 1);
1013  text++;
1014  }
1015  }
1016  if (!av_bprint_is_complete(bp))
1017  return AVERROR(ENOMEM);
1018  return 0;
1019 }
1020 
1022  int width, int height,
1023  FFDrawColor *color, int x, int y, int borderw)
1024 {
1025  char *text = s->expanded_text.str;
1026  uint32_t code = 0;
1027  int i, x1, y1;
1028  uint8_t *p;
1029  Glyph *glyph = NULL;
1030 
1031  for (i = 0, p = text; *p; i++) {
1032  FT_Bitmap bitmap;
1033  Glyph dummy = { 0 };
1034  GET_UTF8(code, *p++, continue;);
1035 
1036  /* skip new line chars, just go to new line */
1037  if (code == '\n' || code == '\r' || code == '\t')
1038  continue;
1039 
1040  dummy.code = code;
1041  glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
1042 
1043  bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
1044 
1045  if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
1046  glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
1047  return AVERROR(EINVAL);
1048 
1049  x1 = s->positions[i].x+s->x+x - borderw;
1050  y1 = s->positions[i].y+s->y+y - borderw;
1051 
1052  ff_blend_mask(&s->dc, color,
1053  frame->data, frame->linesize, width, height,
1054  bitmap.buffer, bitmap.pitch,
1055  bitmap.width, bitmap.rows,
1056  bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
1057  0, x1, y1);
1058  }
1059 
1060  return 0;
1061 }
1062 
1064  int width, int height)
1065 {
1066  DrawTextContext *s = ctx->priv;
1067  AVFilterLink *inlink = ctx->inputs[0];
1068 
1069  uint32_t code = 0, prev_code = 0;
1070  int x = 0, y = 0, i = 0, ret;
1071  int max_text_line_w = 0, len;
1072  int box_w, box_h;
1073  char *text;
1074  uint8_t *p;
1075  int y_min = 32000, y_max = -32000;
1076  int x_min = 32000, x_max = -32000;
1077  FT_Vector delta;
1078  Glyph *glyph = NULL, *prev_glyph = NULL;
1079  Glyph dummy = { 0 };
1080 
1081  time_t now = time(0);
1082  struct tm ltime;
1083  AVBPrint *bp = &s->expanded_text;
1084 
1085  av_bprint_clear(bp);
1086 
1087  if(s->basetime != AV_NOPTS_VALUE)
1088  now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
1089 
1090  switch (s->exp_mode) {
1091  case EXP_NONE:
1092  av_bprintf(bp, "%s", s->text);
1093  break;
1094  case EXP_NORMAL:
1095  if ((ret = expand_text(ctx)) < 0)
1096  return ret;
1097  break;
1098  case EXP_STRFTIME:
1099  localtime_r(&now, &ltime);
1100  av_bprint_strftime(bp, s->text, &ltime);
1101  break;
1102  }
1103 
1104  if (s->tc_opt_string) {
1105  char tcbuf[AV_TIMECODE_STR_SIZE];
1106  av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
1107  av_bprint_clear(bp);
1108  av_bprintf(bp, "%s%s", s->text, tcbuf);
1109  }
1110 
1111  if (!av_bprint_is_complete(bp))
1112  return AVERROR(ENOMEM);
1113  text = s->expanded_text.str;
1114  if ((len = s->expanded_text.len) > s->nb_positions) {
1115  if (!(s->positions =
1116  av_realloc(s->positions, len*sizeof(*s->positions))))
1117  return AVERROR(ENOMEM);
1118  s->nb_positions = len;
1119  }
1120 
1121  x = 0;
1122  y = 0;
1123 
1124  /* load and cache glyphs */
1125  for (i = 0, p = text; *p; i++) {
1126  GET_UTF8(code, *p++, continue;);
1127 
1128  /* get glyph */
1129  dummy.code = code;
1130  glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1131  if (!glyph) {
1132  load_glyph(ctx, &glyph, code);
1133  }
1134 
1135  y_min = FFMIN(glyph->bbox.yMin, y_min);
1136  y_max = FFMAX(glyph->bbox.yMax, y_max);
1137  x_min = FFMIN(glyph->bbox.xMin, x_min);
1138  x_max = FFMAX(glyph->bbox.xMax, x_max);
1139  }
1140  s->max_glyph_h = y_max - y_min;
1141  s->max_glyph_w = x_max - x_min;
1142 
1143  /* compute and save position for each glyph */
1144  glyph = NULL;
1145  for (i = 0, p = text; *p; i++) {
1146  GET_UTF8(code, *p++, continue;);
1147 
1148  /* skip the \n in the sequence \r\n */
1149  if (prev_code == '\r' && code == '\n')
1150  continue;
1151 
1152  prev_code = code;
1153  if (is_newline(code)) {
1154 
1155  max_text_line_w = FFMAX(max_text_line_w, x);
1156  y += s->max_glyph_h;
1157  x = 0;
1158  continue;
1159  }
1160 
1161  /* get glyph */
1162  prev_glyph = glyph;
1163  dummy.code = code;
1164  glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
1165 
1166  /* kerning */
1167  if (s->use_kerning && prev_glyph && glyph->code) {
1168  FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
1169  ft_kerning_default, &delta);
1170  x += delta.x >> 6;
1171  }
1172 
1173  /* save position */
1174  s->positions[i].x = x + glyph->bitmap_left;
1175  s->positions[i].y = y - glyph->bitmap_top + y_max;
1176  if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
1177  else x += glyph->advance;
1178  }
1179 
1180  max_text_line_w = FFMAX(x, max_text_line_w);
1181 
1182  s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
1184 
1187  s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
1189 
1191 
1192  s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1193  s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
1194  s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
1195 #if FF_API_DRAWTEXT_OLD_TIMELINE
1196  if (s->draw_pexpr){
1197  s->draw = av_expr_eval(s->draw_pexpr, s->var_values, &s->prng);
1198 
1199  if(!s->draw)
1200  return 0;
1201  }
1202  if (ctx->is_disabled)
1203  return 0;
1204 #endif
1205 
1206  box_w = FFMIN(width - 1 , max_text_line_w);
1207  box_h = FFMIN(height - 1, y + s->max_glyph_h);
1208 
1209  /* draw box */
1210  if (s->draw_box)
1211  ff_blend_rectangle(&s->dc, &s->boxcolor,
1212  frame->data, frame->linesize, width, height,
1213  s->x, s->y, box_w, box_h);
1214 
1215  if (s->shadowx || s->shadowy) {
1216  if ((ret = draw_glyphs(s, frame, width, height,
1217  &s->shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
1218  return ret;
1219  }
1220 
1221  if (s->borderw) {
1222  if ((ret = draw_glyphs(s, frame, width, height,
1223  &s->bordercolor, 0, 0, s->borderw)) < 0)
1224  return ret;
1225  }
1226  if ((ret = draw_glyphs(s, frame, width, height,
1227  &s->fontcolor, 0, 0, 0)) < 0)
1228  return ret;
1229 
1230  return 0;
1231 }
1232 
1234 {
1235  AVFilterContext *ctx = inlink->dst;
1236  AVFilterLink *outlink = ctx->outputs[0];
1237  DrawTextContext *s = ctx->priv;
1238  int ret;
1239 
1240  if (s->reload) {
1241  if ((ret = load_textfile(ctx)) < 0)
1242  return ret;
1243 #if CONFIG_LIBFRIBIDI
1244  if (s->text_shaping)
1245  if ((ret = shape_text(ctx)) < 0)
1246  return ret;
1247 #endif
1248  }
1249 
1250  s->var_values[VAR_N] = inlink->frame_count+s->start_number;
1251  s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
1252  NAN : frame->pts * av_q2d(inlink->time_base);
1253 
1254  s->var_values[VAR_PICT_TYPE] = frame->pict_type;
1255  s->metadata = av_frame_get_metadata(frame);
1256 
1257  draw_text(ctx, frame, frame->width, frame->height);
1258 
1259  av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
1260  (int)s->var_values[VAR_N], s->var_values[VAR_T],
1261  (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
1262  s->x, s->y);
1263 
1264  return ff_filter_frame(outlink, frame);
1265 }
1266 
1268  {
1269  .name = "default",
1270  .type = AVMEDIA_TYPE_VIDEO,
1271  .filter_frame = filter_frame,
1272  .config_props = config_input,
1273  .needs_writable = 1,
1274  },
1275  { NULL }
1276 };
1277 
1279  {
1280  .name = "default",
1281  .type = AVMEDIA_TYPE_VIDEO,
1282  },
1283  { NULL }
1284 };
1285 
1287  .name = "drawtext",
1288  .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1289  .priv_size = sizeof(DrawTextContext),
1290  .priv_class = &drawtext_class,
1291  .init = init,
1292  .uninit = uninit,
1294  .inputs = avfilter_vf_drawtext_inputs,
1295  .outputs = avfilter_vf_drawtext_outputs,
1299 #else
1301 #endif
1302 };