FFmpeg  1.2.12
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 
29 #include <sys/time.h>
30 #include <time.h>
31 
32 #include "config.h"
33 #include "libavutil/avstring.h"
34 #include "libavutil/bprint.h"
35 #include "libavutil/common.h"
36 #include "libavutil/file.h"
37 #include "libavutil/eval.h"
38 #include "libavutil/opt.h"
39 #include "libavutil/random_seed.h"
40 #include "libavutil/parseutils.h"
41 #include "libavutil/timecode.h"
42 #include "libavutil/tree.h"
43 #include "libavutil/lfg.h"
44 #include "avfilter.h"
45 #include "drawutils.h"
46 #include "formats.h"
47 #include "internal.h"
48 #include "video.h"
49 
50 #include <ft2build.h>
51 #include FT_FREETYPE_H
52 #include FT_GLYPH_H
53 #if CONFIG_FONTCONFIG
54 #include <fontconfig/fontconfig.h>
55 #endif
56 
57 static const char *const var_names[] = {
58  "dar",
59  "hsub", "vsub",
60  "line_h", "lh",
61  "main_h", "h", "H",
62  "main_w", "w", "W",
63  "max_glyph_a", "ascent",
64  "max_glyph_d", "descent",
65  "max_glyph_h",
66  "max_glyph_w",
67  "n",
68  "sar",
69  "t",
70  "text_h", "th",
71  "text_w", "tw",
72  "x",
73  "y",
74  NULL
75 };
76 
77 static const char *const fun2_names[] = {
78  "rand"
79 };
80 
81 static double drand(void *opaque, double min, double max)
82 {
83  return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
84 }
85 
86 typedef double (*eval_func2)(void *, double a, double b);
87 
88 static const eval_func2 fun2[] = {
89  drand,
90  NULL
91 };
92 
93 enum var_name {
111 };
112 
117 };
118 
119 typedef struct {
120  const AVClass *class;
122  int reinit;
127  FT_Vector *positions;
128  size_t nb_positions;
129  char *textfile;
130  int x;
131  int y;
134  int shadowx, shadowy;
135  unsigned int fontsize;
139 
140  short int draw_box;
142  int tabsize;
144 
149 
150  FT_Library library;
151  FT_Face face;
152  struct AVTreeNode *glyphs;
153  char *x_expr;
154  char *y_expr;
155  AVExpr *x_pexpr, *y_pexpr;
156  int64_t basetime;
157  double var_values[VAR_VARS_NB];
158  char *draw_expr;
160  int draw;
165  int tc24hmax;
166  int frame_id;
167  int reload;
169 
170 #define OFFSET(x) offsetof(DrawTextContext, x)
171 #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
172 
173 static const AVOption drawtext_options[]= {
174 {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
175 {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
176 {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
177 {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
178 {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
179 {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
180 {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
181 {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
182 {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
183 {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
184 {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
185 {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
186 {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
187 {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
188 {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
189 
190 {"expansion","set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
191 {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
192 {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
193 {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
194 
195 {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
196 {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
197 {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
198 {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
199 {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
200 {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
201 {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
202 
203 /* FT_LOAD_* flags */
204 {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.i64=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, FLAGS, "ft_load_flags"},
205 {"default", "set default", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
206 {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
207 {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
208 {"render", "set render", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_RENDER}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
209 {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
210 {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
211 {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
212 {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
213 {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
214 {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
215 {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
216 {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
217 {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
218 {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
219 {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
220 {NULL},
221 };
222 
224 
225 #undef __FTERRORS_H__
226 #define FT_ERROR_START_LIST {
227 #define FT_ERRORDEF(e, v, s) { (e), (s) },
228 #define FT_ERROR_END_LIST { 0, NULL } };
229 
230 struct ft_error
231 {
232  int err;
233  const char *err_msg;
234 } static ft_errors[] =
235 #include FT_ERRORS_H
236 
237 #define FT_ERRMSG(e) ft_errors[e].err_msg
238 
239 typedef struct {
240  FT_Glyph *glyph;
241  uint32_t code;
242  FT_Bitmap bitmap;
243  FT_BBox bbox;
244  int advance;
245  int bitmap_left;
246  int bitmap_top;
247 } Glyph;
248 
249 static int glyph_cmp(void *key, const void *b)
250 {
251  const Glyph *a = key, *bb = b;
252  int64_t diff = (int64_t)a->code - (int64_t)bb->code;
253  return diff > 0 ? 1 : diff < 0 ? -1 : 0;
254 }
255 
259 static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
260 {
261  DrawTextContext *dtext = ctx->priv;
262  Glyph *glyph;
263  struct AVTreeNode *node = NULL;
264  int ret;
265 
266  /* load glyph into dtext->face->glyph */
267  if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
268  return AVERROR(EINVAL);
269 
270  /* save glyph */
271  if (!(glyph = av_mallocz(sizeof(*glyph))) ||
272  !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
273  ret = AVERROR(ENOMEM);
274  goto error;
275  }
276  glyph->code = code;
277 
278  if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
279  ret = AVERROR(EINVAL);
280  goto error;
281  }
282 
283  glyph->bitmap = dtext->face->glyph->bitmap;
284  glyph->bitmap_left = dtext->face->glyph->bitmap_left;
285  glyph->bitmap_top = dtext->face->glyph->bitmap_top;
286  glyph->advance = dtext->face->glyph->advance.x >> 6;
287 
288  /* measure text height to calculate text_height (or the maximum text height) */
289  FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
290 
291  /* cache the newly created glyph */
292  if (!(node = av_tree_node_alloc())) {
293  ret = AVERROR(ENOMEM);
294  goto error;
295  }
296  av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
297 
298  if (glyph_ptr)
299  *glyph_ptr = glyph;
300  return 0;
301 
302 error:
303  if (glyph)
304  av_freep(&glyph->glyph);
305  av_freep(&glyph);
306  av_freep(&node);
307  return ret;
308 }
309 
310 static int load_font_file(AVFilterContext *ctx, const char *path, int index,
311  const char **error)
312 {
313  DrawTextContext *dtext = ctx->priv;
314  int err;
315 
316  err = FT_New_Face(dtext->library, path, index, &dtext->face);
317  if (err) {
318  *error = FT_ERRMSG(err);
319  return AVERROR(EINVAL);
320  }
321  return 0;
322 }
323 
324 #if CONFIG_FONTCONFIG
325 static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
326 {
327  DrawTextContext *dtext = ctx->priv;
328  FcConfig *fontconfig;
329  FcPattern *pattern, *fpat;
330  FcResult result = FcResultMatch;
331  FcChar8 *filename;
332  int err, index;
333  double size;
334 
335  fontconfig = FcInitLoadConfigAndFonts();
336  if (!fontconfig) {
337  *error = "impossible to init fontconfig\n";
338  return AVERROR(EINVAL);
339  }
340  pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
341  (uint8_t *)(intptr_t)"default");
342  if (!pattern) {
343  *error = "could not parse fontconfig pattern";
344  return AVERROR(EINVAL);
345  }
346  if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
347  *error = "could not substitue fontconfig options"; /* very unlikely */
348  return AVERROR(EINVAL);
349  }
350  FcDefaultSubstitute(pattern);
351  fpat = FcFontMatch(fontconfig, pattern, &result);
352  if (!fpat || result != FcResultMatch) {
353  *error = "impossible to find a matching font";
354  return AVERROR(EINVAL);
355  }
356  if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
357  FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
358  FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
359  *error = "impossible to find font information";
360  return AVERROR(EINVAL);
361  }
362  av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
363  if (!dtext->fontsize)
364  dtext->fontsize = size + 0.5;
365  err = load_font_file(ctx, filename, index, error);
366  if (err)
367  return err;
368  FcPatternDestroy(fpat);
369  FcPatternDestroy(pattern);
370  FcConfigDestroy(fontconfig);
371  return 0;
372 }
373 #endif
374 
375 static int load_font(AVFilterContext *ctx)
376 {
377  DrawTextContext *dtext = ctx->priv;
378  int err;
379  const char *error = "unknown error\n";
380 
381  /* load the face, and set up the encoding, which is by default UTF-8 */
382  err = load_font_file(ctx, dtext->fontfile, 0, &error);
383  if (!err)
384  return 0;
385 #if CONFIG_FONTCONFIG
386  err = load_font_fontconfig(ctx, &error);
387  if (!err)
388  return 0;
389 #endif
390  av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
391  dtext->fontfile, error);
392  return err;
393 }
394 
396 {
397  DrawTextContext *dtext = ctx->priv;
398  int err;
399  uint8_t *textbuf;
400  size_t textbuf_size;
401 
402  if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
403  av_log(ctx, AV_LOG_ERROR,
404  "The text file '%s' could not be read or is empty\n",
405  dtext->textfile);
406  return err;
407  }
408 
409  if (!(dtext->text = av_realloc(dtext->text, textbuf_size + 1)))
410  return AVERROR(ENOMEM);
411  memcpy(dtext->text, textbuf, textbuf_size);
412  dtext->text[textbuf_size] = 0;
413  av_file_unmap(textbuf, textbuf_size);
414 
415  return 0;
416 }
417 
418 static av_cold int init(AVFilterContext *ctx, const char *args)
419 {
420  int err;
421  DrawTextContext *dtext = ctx->priv;
422  Glyph *glyph;
423 
424  dtext->class = &drawtext_class;
425  av_opt_set_defaults(dtext);
426 
427  if ((err = av_set_options_string(dtext, args, "=", ":")) < 0)
428  return err;
429 
430  if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
431  av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
432  return AVERROR(EINVAL);
433  }
434 
435  if (dtext->textfile) {
436  if (dtext->text) {
437  av_log(ctx, AV_LOG_ERROR,
438  "Both text and text file provided. Please provide only one\n");
439  return AVERROR(EINVAL);
440  }
441  if ((err = load_textfile(ctx)) < 0)
442  return err;
443  }
444 
445  if (dtext->reload && !dtext->textfile)
446  av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
447 
448  if (dtext->tc_opt_string) {
449  int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
450  dtext->tc_opt_string, ctx);
451  if (ret < 0)
452  return ret;
453  if (dtext->tc24hmax)
455  if (!dtext->text)
456  dtext->text = av_strdup("");
457  }
458 
459  if (!dtext->text) {
460  av_log(ctx, AV_LOG_ERROR,
461  "Either text, a valid file or a timecode must be provided\n");
462  return AVERROR(EINVAL);
463  }
464 
465  if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
466  av_log(ctx, AV_LOG_ERROR,
467  "Invalid font color '%s'\n", dtext->fontcolor_string);
468  return err;
469  }
470 
471  if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
472  av_log(ctx, AV_LOG_ERROR,
473  "Invalid box color '%s'\n", dtext->boxcolor_string);
474  return err;
475  }
476 
477  if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
478  av_log(ctx, AV_LOG_ERROR,
479  "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
480  return err;
481  }
482 
483  if ((err = FT_Init_FreeType(&(dtext->library)))) {
484  av_log(ctx, AV_LOG_ERROR,
485  "Could not load FreeType: %s\n", FT_ERRMSG(err));
486  return AVERROR(EINVAL);
487  }
488 
489  err = load_font(ctx);
490  if (err)
491  return err;
492  if (!dtext->fontsize)
493  dtext->fontsize = 16;
494  if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
495  av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
496  dtext->fontsize, FT_ERRMSG(err));
497  return AVERROR(EINVAL);
498  }
499 
500  dtext->use_kerning = FT_HAS_KERNING(dtext->face);
501 
502  /* load the fallback glyph with code 0 */
503  load_glyph(ctx, NULL, 0);
504 
505  /* set the tabsize in pixels */
506  if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
507  av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
508  return err;
509  }
510  dtext->tabsize *= glyph->advance;
511 
512  if (dtext->exp_mode == EXP_STRFTIME &&
513  (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
514  av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
515 
517 
518  return 0;
519 }
520 
522 {
524  return 0;
525 }
526 
527 static int glyph_enu_free(void *opaque, void *elem)
528 {
529  Glyph *glyph = elem;
530 
531  FT_Done_Glyph(*glyph->glyph);
532  av_freep(&glyph->glyph);
533  av_free(elem);
534  return 0;
535 }
536 
537 static av_cold void uninit(AVFilterContext *ctx)
538 {
539  DrawTextContext *dtext = ctx->priv;
540 
541  av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
542  av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
543  av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
544  av_opt_free(dtext);
545 
546  av_freep(&dtext->positions);
547  dtext->nb_positions = 0;
548 
550  av_tree_destroy(dtext->glyphs);
551  dtext->glyphs = NULL;
552 
553  FT_Done_Face(dtext->face);
554  FT_Done_FreeType(dtext->library);
555 
557 }
558 
559 static inline int is_newline(uint32_t c)
560 {
561  return c == '\n' || c == '\r' || c == '\f' || c == '\v';
562 }
563 
564 static int config_input(AVFilterLink *inlink)
565 {
566  AVFilterContext *ctx = inlink->dst;
567  DrawTextContext *dtext = ctx->priv;
568  int ret;
569 
570  ff_draw_init(&dtext->dc, inlink->format, 0);
571  ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
572  ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
573  ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
574 
575  dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
576  dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
577  dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
578  dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
579  dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
580  dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
581  dtext->var_values[VAR_X] = NAN;
582  dtext->var_values[VAR_Y] = NAN;
583  if (!dtext->reinit)
584  dtext->var_values[VAR_N] = 0;
585  dtext->var_values[VAR_T] = NAN;
586 
587  av_lfg_init(&dtext->prng, av_get_random_seed());
588 
589  if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
590  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
591  (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
592  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
593  (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
594  NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
595 
596  return AVERROR(EINVAL);
597 
598  return 0;
599 }
600 
601 static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
602 {
603  DrawTextContext *dtext = ctx->priv;
604 
605  if (!strcmp(cmd, "reinit")) {
606  int ret;
607  uninit(ctx);
608  dtext->reinit = 1;
609  if ((ret = init(ctx, arg)) < 0)
610  return ret;
611  return config_input(ctx->inputs[0]);
612  }
613 
614  return AVERROR(ENOSYS);
615 }
616 
617 static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
618  char *fct, unsigned argc, char **argv, int tag)
619 {
620  DrawTextContext *dtext = ctx->priv;
621 
622  av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
623  return 0;
624 }
625 
627  char *fct, unsigned argc, char **argv, int tag)
628 {
629  DrawTextContext *dtext = ctx->priv;
630 
631  av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
632  return 0;
633 }
634 
635 #if !HAVE_LOCALTIME_R
636 static void localtime_r(const time_t *t, struct tm *tm)
637 {
638  *tm = *localtime(t);
639 }
640 #endif
641 
643  char *fct, unsigned argc, char **argv, int tag)
644 {
645  const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
646  time_t now;
647  struct tm tm;
648 
649  time(&now);
650  if (tag == 'L')
651  localtime_r(&now, &tm);
652  else
653  tm = *gmtime(&now);
654  av_bprint_strftime(bp, fmt, &tm);
655  return 0;
656 }
657 
659  char *fct, unsigned argc, char **argv, int tag)
660 {
661  DrawTextContext *dtext = ctx->priv;
662  double res;
663  int ret;
664 
665  ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
667  &dtext->prng, 0, ctx);
668  if (ret < 0)
669  av_log(ctx, AV_LOG_ERROR,
670  "Expression '%s' for the expr text expansion function is not valid\n",
671  argv[0]);
672  else
673  av_bprintf(bp, "%f", res);
674 
675  return ret;
676 }
677 
678 static const struct drawtext_function {
679  const char *name;
680  unsigned argc_min, argc_max;
681  int tag;
682  int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
683 } functions[] = {
684  { "expr", 1, 1, 0, func_eval_expr },
685  { "e", 1, 1, 0, func_eval_expr },
686  { "pts", 0, 0, 0, func_pts },
687  { "gmtime", 0, 1, 'G', func_strftime },
688  { "localtime", 0, 1, 'L', func_strftime },
689  { "frame_num", 0, 0, 0, func_frame_num },
690  { "n", 0, 0, 0, func_frame_num },
691 };
692 
693 static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
694  unsigned argc, char **argv)
695 {
696  unsigned i;
697 
698  for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
699  if (strcmp(fct, functions[i].name))
700  continue;
701  if (argc < functions[i].argc_min) {
702  av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
703  fct, functions[i].argc_min);
704  return AVERROR(EINVAL);
705  }
706  if (argc > functions[i].argc_max) {
707  av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
708  fct, functions[i].argc_max);
709  return AVERROR(EINVAL);
710  }
711  break;
712  }
713  if (i >= FF_ARRAY_ELEMS(functions)) {
714  av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
715  return AVERROR(EINVAL);
716  }
717  return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
718 }
719 
720 static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
721 {
722  const char *text = *rtext;
723  char *argv[16] = { NULL };
724  unsigned argc = 0, i;
725  int ret;
726 
727  if (*text != '{') {
728  av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
729  return AVERROR(EINVAL);
730  }
731  text++;
732  while (1) {
733  if (!(argv[argc++] = av_get_token(&text, ":}"))) {
734  ret = AVERROR(ENOMEM);
735  goto end;
736  }
737  if (!*text) {
738  av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
739  ret = AVERROR(EINVAL);
740  goto end;
741  }
742  if (argc == FF_ARRAY_ELEMS(argv))
743  av_freep(&argv[--argc]); /* error will be caught later */
744  if (*text == '}')
745  break;
746  text++;
747  }
748 
749  if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
750  goto end;
751  ret = 0;
752  *rtext = (char *)text + 1;
753 
754 end:
755  for (i = 0; i < argc; i++)
756  av_freep(&argv[i]);
757  return ret;
758 }
759 
760 static int expand_text(AVFilterContext *ctx)
761 {
762  DrawTextContext *dtext = ctx->priv;
763  char *text = dtext->text;
764  AVBPrint *bp = &dtext->expanded_text;
765  int ret;
766 
767  av_bprint_clear(bp);
768  while (*text) {
769  if (*text == '\\' && text[1]) {
770  av_bprint_chars(bp, text[1], 1);
771  text += 2;
772  } else if (*text == '%') {
773  text++;
774  if ((ret = expand_function(ctx, bp, &text)) < 0)
775  return ret;
776  } else {
777  av_bprint_chars(bp, *text, 1);
778  text++;
779  }
780  }
781  if (!av_bprint_is_complete(bp))
782  return AVERROR(ENOMEM);
783  return 0;
784 }
785 
786 static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
787  int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
788 {
789  char *text = dtext->expanded_text.str;
790  uint32_t code = 0;
791  int i, x1, y1;
792  uint8_t *p;
793  Glyph *glyph = NULL;
794 
795  for (i = 0, p = text; *p; i++) {
796  Glyph dummy = { 0 };
797  GET_UTF8(code, *p++, continue;);
798 
799  /* skip new line chars, just go to new line */
800  if (code == '\n' || code == '\r' || code == '\t')
801  continue;
802 
803  dummy.code = code;
804  glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
805 
806  if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
807  glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
808  return AVERROR(EINVAL);
809 
810  x1 = dtext->positions[i].x+dtext->x+x;
811  y1 = dtext->positions[i].y+dtext->y+y;
812 
813  ff_blend_mask(&dtext->dc, color,
814  picref->data, picref->linesize, width, height,
815  glyph->bitmap.buffer, glyph->bitmap.pitch,
816  glyph->bitmap.width, glyph->bitmap.rows,
817  glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
818  0, x1, y1);
819  }
820 
821  return 0;
822 }
823 
824 static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
825  int width, int height)
826 {
827  DrawTextContext *dtext = ctx->priv;
828  uint32_t code = 0, prev_code = 0;
829  int x = 0, y = 0, i = 0, ret;
830  int max_text_line_w = 0, len;
831  int box_w, box_h;
832  char *text = dtext->text;
833  uint8_t *p;
834  int y_min = 32000, y_max = -32000;
835  int x_min = 32000, x_max = -32000;
836  FT_Vector delta;
837  Glyph *glyph = NULL, *prev_glyph = NULL;
838  Glyph dummy = { 0 };
839 
840  time_t now = time(0);
841  struct tm ltime;
842  AVBPrint *bp = &dtext->expanded_text;
843 
844  av_bprint_clear(bp);
845 
846  if(dtext->basetime != AV_NOPTS_VALUE)
847  now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
848 
849  switch (dtext->exp_mode) {
850  case EXP_NONE:
851  av_bprintf(bp, "%s", dtext->text);
852  break;
853  case EXP_NORMAL:
854  if ((ret = expand_text(ctx)) < 0)
855  return ret;
856  break;
857  case EXP_STRFTIME:
858  localtime_r(&now, &ltime);
859  av_bprint_strftime(bp, dtext->text, &ltime);
860  break;
861  }
862 
863  if (dtext->tc_opt_string) {
864  char tcbuf[AV_TIMECODE_STR_SIZE];
865  av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
866  av_bprint_clear(bp);
867  av_bprintf(bp, "%s%s", dtext->text, tcbuf);
868  }
869 
870  if (!av_bprint_is_complete(bp))
871  return AVERROR(ENOMEM);
872  text = dtext->expanded_text.str;
873  if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
874  if (!(dtext->positions =
875  av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
876  return AVERROR(ENOMEM);
877  dtext->nb_positions = len;
878  }
879 
880  x = 0;
881  y = 0;
882 
883  /* load and cache glyphs */
884  for (i = 0, p = text; *p; i++) {
885  GET_UTF8(code, *p++, continue;);
886 
887  /* get glyph */
888  dummy.code = code;
889  glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
890  if (!glyph) {
891  load_glyph(ctx, &glyph, code);
892  }
893 
894  y_min = FFMIN(glyph->bbox.yMin, y_min);
895  y_max = FFMAX(glyph->bbox.yMax, y_max);
896  x_min = FFMIN(glyph->bbox.xMin, x_min);
897  x_max = FFMAX(glyph->bbox.xMax, x_max);
898  }
899  dtext->max_glyph_h = y_max - y_min;
900  dtext->max_glyph_w = x_max - x_min;
901 
902  /* compute and save position for each glyph */
903  glyph = NULL;
904  for (i = 0, p = text; *p; i++) {
905  GET_UTF8(code, *p++, continue;);
906 
907  /* skip the \n in the sequence \r\n */
908  if (prev_code == '\r' && code == '\n')
909  continue;
910 
911  prev_code = code;
912  if (is_newline(code)) {
913  max_text_line_w = FFMAX(max_text_line_w, x);
914  y += dtext->max_glyph_h;
915  x = 0;
916  continue;
917  }
918 
919  /* get glyph */
920  prev_glyph = glyph;
921  dummy.code = code;
922  glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
923 
924  /* kerning */
925  if (dtext->use_kerning && prev_glyph && glyph->code) {
926  FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
927  ft_kerning_default, &delta);
928  x += delta.x >> 6;
929  }
930 
931  /* save position */
932  dtext->positions[i].x = x + glyph->bitmap_left;
933  dtext->positions[i].y = y - glyph->bitmap_top + y_max;
934  if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
935  else x += glyph->advance;
936  }
937 
938  max_text_line_w = FFMAX(x, max_text_line_w);
939 
940  dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
941  dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
942 
943  dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
944  dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
945  dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
946  dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
947 
948  dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
949 
950  dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
951  dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
952  dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
953  dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
954 
955  if(!dtext->draw)
956  return 0;
957 
958  box_w = FFMIN(width - 1 , max_text_line_w);
959  box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
960 
961  /* draw box */
962  if (dtext->draw_box)
963  ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
964  picref->data, picref->linesize, width, height,
965  dtext->x, dtext->y, box_w, box_h);
966 
967  if (dtext->shadowx || dtext->shadowy) {
968  if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,
969  &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
970  return ret;
971  }
972 
973  if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,
974  &dtext->fontcolor, 0, 0)) < 0)
975  return ret;
976 
977  return 0;
978 }
979 
981 {
982  AVFilterContext *ctx = inlink->dst;
983  AVFilterLink *outlink = ctx->outputs[0];
984  DrawTextContext *dtext = ctx->priv;
985  int ret;
986 
987  if (dtext->reload)
988  if ((ret = load_textfile(ctx)) < 0)
989  return ret;
990 
991  dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
992  NAN : frame->pts * av_q2d(inlink->time_base);
993 
994  draw_text(ctx, frame, frame->video->w, frame->video->h);
995 
996  av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
997  (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
998  (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
999  dtext->x, dtext->y);
1000 
1001  dtext->var_values[VAR_N] += 1.0;
1002 
1003  return ff_filter_frame(outlink, frame);
1004 }
1005 
1007  {
1008  .name = "default",
1009  .type = AVMEDIA_TYPE_VIDEO,
1010  .get_video_buffer = ff_null_get_video_buffer,
1011  .filter_frame = filter_frame,
1012  .config_props = config_input,
1013  .min_perms = AV_PERM_WRITE |
1014  AV_PERM_READ,
1015  },
1016  { NULL }
1017 };
1018 
1020  {
1021  .name = "default",
1022  .type = AVMEDIA_TYPE_VIDEO,
1023  },
1024  { NULL }
1025 };
1026 
1028  .name = "drawtext",
1029  .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
1030  .priv_size = sizeof(DrawTextContext),
1031  .init = init,
1032  .uninit = uninit,
1034 
1035  .inputs = avfilter_vf_drawtext_inputs,
1036  .outputs = avfilter_vf_drawtext_outputs,
1038  .priv_class = &drawtext_class,
1039 };