You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1499 lines
50KB

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