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.

1581 lines
53KB

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