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.

1577 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}, CHAR_MIN, CHAR_MAX, FLAGS},
  193. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  194. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  195. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  196. {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, CHAR_MIN, CHAR_MAX, FLAGS},
  197. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  198. {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  199. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, 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}, CHAR_MIN, CHAR_MAX , FLAGS},
  204. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  205. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, 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}, CHAR_MIN, CHAR_MAX, 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 int load_textfile(AVFilterContext *ctx)
  495. {
  496. DrawTextContext *s = ctx->priv;
  497. int err;
  498. uint8_t *textbuf;
  499. uint8_t *tmp;
  500. size_t textbuf_size;
  501. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  502. av_log(ctx, AV_LOG_ERROR,
  503. "The text file '%s' could not be read or is empty\n",
  504. s->textfile);
  505. return err;
  506. }
  507. if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
  508. av_file_unmap(textbuf, textbuf_size);
  509. return AVERROR(ENOMEM);
  510. }
  511. s->text = tmp;
  512. memcpy(s->text, textbuf, textbuf_size);
  513. s->text[textbuf_size] = 0;
  514. av_file_unmap(textbuf, textbuf_size);
  515. return 0;
  516. }
  517. static inline int is_newline(uint32_t c)
  518. {
  519. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  520. }
  521. #if CONFIG_LIBFRIBIDI
  522. static int shape_text(AVFilterContext *ctx)
  523. {
  524. DrawTextContext *s = ctx->priv;
  525. uint8_t *tmp;
  526. int ret = AVERROR(ENOMEM);
  527. static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
  528. FRIBIDI_FLAGS_ARABIC;
  529. FriBidiChar *unicodestr = NULL;
  530. FriBidiStrIndex len;
  531. FriBidiParType direction = FRIBIDI_PAR_LTR;
  532. FriBidiStrIndex line_start = 0;
  533. FriBidiStrIndex line_end = 0;
  534. FriBidiLevel *embedding_levels = NULL;
  535. FriBidiArabicProp *ar_props = NULL;
  536. FriBidiCharType *bidi_types = NULL;
  537. FriBidiStrIndex i,j;
  538. len = strlen(s->text);
  539. if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
  540. goto out;
  541. }
  542. len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
  543. s->text, len, unicodestr);
  544. bidi_types = av_malloc_array(len, sizeof(*bidi_types));
  545. if (!bidi_types) {
  546. goto out;
  547. }
  548. fribidi_get_bidi_types(unicodestr, len, bidi_types);
  549. embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
  550. if (!embedding_levels) {
  551. goto out;
  552. }
  553. if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
  554. embedding_levels)) {
  555. goto out;
  556. }
  557. ar_props = av_malloc_array(len, sizeof(*ar_props));
  558. if (!ar_props) {
  559. goto out;
  560. }
  561. fribidi_get_joining_types(unicodestr, len, ar_props);
  562. fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
  563. fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
  564. for (line_end = 0, line_start = 0; line_end < len; line_end++) {
  565. if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
  566. if (!fribidi_reorder_line(flags, bidi_types,
  567. line_end - line_start + 1, line_start,
  568. direction, embedding_levels, unicodestr,
  569. NULL)) {
  570. goto out;
  571. }
  572. line_start = line_end + 1;
  573. }
  574. }
  575. /* Remove zero-width fill chars put in by libfribidi */
  576. for (i = 0, j = 0; i < len; i++)
  577. if (unicodestr[i] != FRIBIDI_CHAR_FILL)
  578. unicodestr[j++] = unicodestr[i];
  579. len = j;
  580. if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
  581. /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
  582. goto out;
  583. }
  584. s->text = tmp;
  585. len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
  586. unicodestr, len, s->text);
  587. ret = 0;
  588. out:
  589. av_free(unicodestr);
  590. av_free(embedding_levels);
  591. av_free(ar_props);
  592. av_free(bidi_types);
  593. return ret;
  594. }
  595. #endif
  596. static av_cold int init(AVFilterContext *ctx)
  597. {
  598. int err;
  599. DrawTextContext *s = ctx->priv;
  600. Glyph *glyph;
  601. av_expr_free(s->fontsize_pexpr);
  602. s->fontsize_pexpr = NULL;
  603. s->fontsize = 0;
  604. s->default_fontsize = 16;
  605. if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
  606. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  607. return AVERROR(EINVAL);
  608. }
  609. if (s->textfile) {
  610. if (s->text) {
  611. av_log(ctx, AV_LOG_ERROR,
  612. "Both text and text file provided. Please provide only one\n");
  613. return AVERROR(EINVAL);
  614. }
  615. if ((err = load_textfile(ctx)) < 0)
  616. return err;
  617. }
  618. if (s->reload && !s->textfile)
  619. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  620. if (s->tc_opt_string) {
  621. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  622. s->tc_opt_string, ctx);
  623. if (ret < 0)
  624. return ret;
  625. if (s->tc24hmax)
  626. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  627. if (!s->text)
  628. s->text = av_strdup("");
  629. }
  630. if (!s->text) {
  631. av_log(ctx, AV_LOG_ERROR,
  632. "Either text, a valid file or a timecode must be provided\n");
  633. return AVERROR(EINVAL);
  634. }
  635. #if CONFIG_LIBFRIBIDI
  636. if (s->text_shaping)
  637. if ((err = shape_text(ctx)) < 0)
  638. return err;
  639. #endif
  640. if ((err = FT_Init_FreeType(&(s->library)))) {
  641. av_log(ctx, AV_LOG_ERROR,
  642. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  643. return AVERROR(EINVAL);
  644. }
  645. if ((err = load_font(ctx)) < 0)
  646. return err;
  647. if ((err = update_fontsize(ctx)) < 0)
  648. return err;
  649. if (s->borderw) {
  650. if (FT_Stroker_New(s->library, &s->stroker)) {
  651. av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
  652. return AVERROR_EXTERNAL;
  653. }
  654. FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
  655. FT_STROKER_LINEJOIN_ROUND, 0);
  656. }
  657. s->use_kerning = FT_HAS_KERNING(s->face);
  658. /* load the fallback glyph with code 0 */
  659. load_glyph(ctx, NULL, 0);
  660. /* set the tabsize in pixels */
  661. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  662. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  663. return err;
  664. }
  665. s->tabsize *= glyph->advance;
  666. if (s->exp_mode == EXP_STRFTIME &&
  667. (strchr(s->text, '%') || strchr(s->text, '\\')))
  668. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  669. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  670. av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
  671. return 0;
  672. }
  673. static int query_formats(AVFilterContext *ctx)
  674. {
  675. return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  676. }
  677. static int glyph_enu_free(void *opaque, void *elem)
  678. {
  679. Glyph *glyph = elem;
  680. FT_Done_Glyph(glyph->glyph);
  681. FT_Done_Glyph(glyph->border_glyph);
  682. av_free(elem);
  683. return 0;
  684. }
  685. static av_cold void uninit(AVFilterContext *ctx)
  686. {
  687. DrawTextContext *s = ctx->priv;
  688. av_expr_free(s->x_pexpr);
  689. av_expr_free(s->y_pexpr);
  690. av_expr_free(s->a_pexpr);
  691. av_expr_free(s->fontsize_pexpr);
  692. s->x_pexpr = s->y_pexpr = s->a_pexpr = s->fontsize_pexpr = NULL;
  693. av_freep(&s->positions);
  694. s->nb_positions = 0;
  695. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  696. av_tree_destroy(s->glyphs);
  697. s->glyphs = NULL;
  698. FT_Done_Face(s->face);
  699. FT_Stroker_Done(s->stroker);
  700. FT_Done_FreeType(s->library);
  701. av_bprint_finalize(&s->expanded_text, NULL);
  702. av_bprint_finalize(&s->expanded_fontcolor, NULL);
  703. }
  704. static int config_input(AVFilterLink *inlink)
  705. {
  706. AVFilterContext *ctx = inlink->dst;
  707. DrawTextContext *s = ctx->priv;
  708. char *expr;
  709. int ret;
  710. ff_draw_init(&s->dc, inlink->format, FF_DRAW_PROCESS_ALPHA);
  711. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  712. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  713. ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
  714. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  715. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  716. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  717. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  718. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  719. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  720. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  721. s->var_values[VAR_X] = NAN;
  722. s->var_values[VAR_Y] = NAN;
  723. s->var_values[VAR_T] = NAN;
  724. av_lfg_init(&s->prng, av_get_random_seed());
  725. av_expr_free(s->x_pexpr);
  726. av_expr_free(s->y_pexpr);
  727. av_expr_free(s->a_pexpr);
  728. s->x_pexpr = s->y_pexpr = s->a_pexpr = NULL;
  729. if ((ret = av_expr_parse(&s->x_pexpr, expr = s->x_expr, var_names,
  730. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  731. (ret = av_expr_parse(&s->y_pexpr, expr = s->y_expr, var_names,
  732. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  733. (ret = av_expr_parse(&s->a_pexpr, expr = s->a_expr, var_names,
  734. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0) {
  735. av_log(ctx, AV_LOG_ERROR, "Failed to parse expression: %s \n", expr);
  736. return AVERROR(EINVAL);
  737. }
  738. return 0;
  739. }
  740. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  741. {
  742. DrawTextContext *old = ctx->priv;
  743. DrawTextContext *new = NULL;
  744. int ret;
  745. if (!strcmp(cmd, "reinit")) {
  746. new = av_mallocz(sizeof(DrawTextContext));
  747. if (!new)
  748. return AVERROR(ENOMEM);
  749. new->class = &drawtext_class;
  750. ret = av_opt_copy(new, old);
  751. if (ret < 0)
  752. goto fail;
  753. ctx->priv = new;
  754. ret = av_set_options_string(ctx, arg, "=", ":");
  755. if (ret < 0) {
  756. ctx->priv = old;
  757. goto fail;
  758. }
  759. ret = init(ctx);
  760. if (ret < 0) {
  761. uninit(ctx);
  762. ctx->priv = old;
  763. goto fail;
  764. }
  765. new->reinit = 1;
  766. ctx->priv = old;
  767. uninit(ctx);
  768. av_freep(&old);
  769. ctx->priv = new;
  770. return config_input(ctx->inputs[0]);
  771. } else
  772. return AVERROR(ENOSYS);
  773. fail:
  774. av_log(ctx, AV_LOG_ERROR, "Failed to process command. Continuing with existing parameters.\n");
  775. av_freep(&new);
  776. return ret;
  777. }
  778. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  779. char *fct, unsigned argc, char **argv, int tag)
  780. {
  781. DrawTextContext *s = ctx->priv;
  782. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  783. return 0;
  784. }
  785. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  786. char *fct, unsigned argc, char **argv, int tag)
  787. {
  788. DrawTextContext *s = ctx->priv;
  789. const char *fmt;
  790. double pts = s->var_values[VAR_T];
  791. int ret;
  792. fmt = argc >= 1 ? argv[0] : "flt";
  793. if (argc >= 2) {
  794. int64_t delta;
  795. if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
  796. av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
  797. return ret;
  798. }
  799. pts += (double)delta / AV_TIME_BASE;
  800. }
  801. if (!strcmp(fmt, "flt")) {
  802. av_bprintf(bp, "%.6f", pts);
  803. } else if (!strcmp(fmt, "hms")) {
  804. if (isnan(pts)) {
  805. av_bprintf(bp, " ??:??:??.???");
  806. } else {
  807. int64_t ms = llrint(pts * 1000);
  808. char sign = ' ';
  809. if (ms < 0) {
  810. sign = '-';
  811. ms = -ms;
  812. }
  813. if (argc >= 3) {
  814. if (!strcmp(argv[2], "24HH")) {
  815. ms %= 24 * 60 * 60 * 1000;
  816. } else {
  817. av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s'\n", argv[2]);
  818. return AVERROR(EINVAL);
  819. }
  820. }
  821. av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
  822. (int)(ms / (60 * 60 * 1000)),
  823. (int)(ms / (60 * 1000)) % 60,
  824. (int)(ms / 1000) % 60,
  825. (int)(ms % 1000));
  826. }
  827. } else if (!strcmp(fmt, "localtime") ||
  828. !strcmp(fmt, "gmtime")) {
  829. struct tm tm;
  830. time_t ms = (time_t)pts;
  831. const char *timefmt = argc >= 3 ? argv[2] : "%Y-%m-%d %H:%M:%S";
  832. if (!strcmp(fmt, "localtime"))
  833. localtime_r(&ms, &tm);
  834. else
  835. gmtime_r(&ms, &tm);
  836. av_bprint_strftime(bp, timefmt, &tm);
  837. } else {
  838. av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
  839. return AVERROR(EINVAL);
  840. }
  841. return 0;
  842. }
  843. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  844. char *fct, unsigned argc, char **argv, int tag)
  845. {
  846. DrawTextContext *s = ctx->priv;
  847. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  848. return 0;
  849. }
  850. static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
  851. char *fct, unsigned argc, char **argv, int tag)
  852. {
  853. DrawTextContext *s = ctx->priv;
  854. AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
  855. if (e && e->value)
  856. av_bprintf(bp, "%s", e->value);
  857. else if (argc >= 2)
  858. av_bprintf(bp, "%s", argv[1]);
  859. return 0;
  860. }
  861. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  862. char *fct, unsigned argc, char **argv, int tag)
  863. {
  864. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  865. time_t now;
  866. struct tm tm;
  867. time(&now);
  868. if (tag == 'L')
  869. localtime_r(&now, &tm);
  870. else
  871. tm = *gmtime_r(&now, &tm);
  872. av_bprint_strftime(bp, fmt, &tm);
  873. return 0;
  874. }
  875. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  876. char *fct, unsigned argc, char **argv, int tag)
  877. {
  878. DrawTextContext *s = ctx->priv;
  879. double res;
  880. int ret;
  881. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  882. NULL, NULL, fun2_names, fun2,
  883. &s->prng, 0, ctx);
  884. if (ret < 0)
  885. av_log(ctx, AV_LOG_ERROR,
  886. "Expression '%s' for the expr text expansion function is not valid\n",
  887. argv[0]);
  888. else
  889. av_bprintf(bp, "%f", res);
  890. return ret;
  891. }
  892. static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
  893. char *fct, unsigned argc, char **argv, int tag)
  894. {
  895. DrawTextContext *s = ctx->priv;
  896. double res;
  897. int intval;
  898. int ret;
  899. unsigned int positions = 0;
  900. char fmt_str[30] = "%";
  901. /*
  902. * argv[0] expression to be converted to `int`
  903. * argv[1] format: 'x', 'X', 'd' or 'u'
  904. * argv[2] positions printed (optional)
  905. */
  906. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  907. NULL, NULL, fun2_names, fun2,
  908. &s->prng, 0, ctx);
  909. if (ret < 0) {
  910. av_log(ctx, AV_LOG_ERROR,
  911. "Expression '%s' for the expr text expansion function is not valid\n",
  912. argv[0]);
  913. return ret;
  914. }
  915. if (!strchr("xXdu", argv[1][0])) {
  916. av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
  917. " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
  918. return AVERROR(EINVAL);
  919. }
  920. if (argc == 3) {
  921. ret = sscanf(argv[2], "%u", &positions);
  922. if (ret != 1) {
  923. av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
  924. " to print: '%s'\n", argv[2]);
  925. return AVERROR(EINVAL);
  926. }
  927. }
  928. feclearexcept(FE_ALL_EXCEPT);
  929. intval = res;
  930. if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
  931. av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
  932. return AVERROR(EINVAL);
  933. }
  934. if (argc == 3)
  935. av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
  936. av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
  937. av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
  938. res, argv[0], fmt_str);
  939. av_bprintf(bp, fmt_str, intval);
  940. return 0;
  941. }
  942. static const struct drawtext_function {
  943. const char *name;
  944. unsigned argc_min, argc_max;
  945. int tag; /**< opaque argument to func */
  946. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  947. } functions[] = {
  948. { "expr", 1, 1, 0, func_eval_expr },
  949. { "e", 1, 1, 0, func_eval_expr },
  950. { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
  951. { "eif", 2, 3, 0, func_eval_expr_int_format },
  952. { "pict_type", 0, 0, 0, func_pict_type },
  953. { "pts", 0, 3, 0, func_pts },
  954. { "gmtime", 0, 1, 'G', func_strftime },
  955. { "localtime", 0, 1, 'L', func_strftime },
  956. { "frame_num", 0, 0, 0, func_frame_num },
  957. { "n", 0, 0, 0, func_frame_num },
  958. { "metadata", 1, 2, 0, func_metadata },
  959. };
  960. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  961. unsigned argc, char **argv)
  962. {
  963. unsigned i;
  964. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  965. if (strcmp(fct, functions[i].name))
  966. continue;
  967. if (argc < functions[i].argc_min) {
  968. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  969. fct, functions[i].argc_min);
  970. return AVERROR(EINVAL);
  971. }
  972. if (argc > functions[i].argc_max) {
  973. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  974. fct, functions[i].argc_max);
  975. return AVERROR(EINVAL);
  976. }
  977. break;
  978. }
  979. if (i >= FF_ARRAY_ELEMS(functions)) {
  980. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  981. return AVERROR(EINVAL);
  982. }
  983. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  984. }
  985. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  986. {
  987. const char *text = *rtext;
  988. char *argv[16] = { NULL };
  989. unsigned argc = 0, i;
  990. int ret;
  991. if (*text != '{') {
  992. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  993. return AVERROR(EINVAL);
  994. }
  995. text++;
  996. while (1) {
  997. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  998. ret = AVERROR(ENOMEM);
  999. goto end;
  1000. }
  1001. if (!*text) {
  1002. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  1003. ret = AVERROR(EINVAL);
  1004. goto end;
  1005. }
  1006. if (argc == FF_ARRAY_ELEMS(argv))
  1007. av_freep(&argv[--argc]); /* error will be caught later */
  1008. if (*text == '}')
  1009. break;
  1010. text++;
  1011. }
  1012. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  1013. goto end;
  1014. ret = 0;
  1015. *rtext = (char *)text + 1;
  1016. end:
  1017. for (i = 0; i < argc; i++)
  1018. av_freep(&argv[i]);
  1019. return ret;
  1020. }
  1021. static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
  1022. {
  1023. int ret;
  1024. av_bprint_clear(bp);
  1025. while (*text) {
  1026. if (*text == '\\' && text[1]) {
  1027. av_bprint_chars(bp, text[1], 1);
  1028. text += 2;
  1029. } else if (*text == '%') {
  1030. text++;
  1031. if ((ret = expand_function(ctx, bp, &text)) < 0)
  1032. return ret;
  1033. } else {
  1034. av_bprint_chars(bp, *text, 1);
  1035. text++;
  1036. }
  1037. }
  1038. if (!av_bprint_is_complete(bp))
  1039. return AVERROR(ENOMEM);
  1040. return 0;
  1041. }
  1042. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  1043. int width, int height,
  1044. FFDrawColor *color,
  1045. int x, int y, int borderw)
  1046. {
  1047. char *text = s->expanded_text.str;
  1048. uint32_t code = 0;
  1049. int i, x1, y1;
  1050. uint8_t *p;
  1051. Glyph *glyph = NULL;
  1052. for (i = 0, p = text; *p; i++) {
  1053. FT_Bitmap bitmap;
  1054. Glyph dummy = { 0 };
  1055. GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_invalid;);
  1056. continue_on_invalid:
  1057. /* skip new line chars, just go to new line */
  1058. if (code == '\n' || code == '\r' || code == '\t')
  1059. continue;
  1060. dummy.code = code;
  1061. dummy.fontsize = s->fontsize;
  1062. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1063. bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
  1064. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  1065. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  1066. return AVERROR(EINVAL);
  1067. x1 = s->positions[i].x+s->x+x - borderw;
  1068. y1 = s->positions[i].y+s->y+y - borderw;
  1069. ff_blend_mask(&s->dc, color,
  1070. frame->data, frame->linesize, width, height,
  1071. bitmap.buffer, bitmap.pitch,
  1072. bitmap.width, bitmap.rows,
  1073. bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  1074. 0, x1, y1);
  1075. }
  1076. return 0;
  1077. }
  1078. static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
  1079. {
  1080. *color = incolor;
  1081. color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
  1082. ff_draw_color(&s->dc, color, color->rgba);
  1083. }
  1084. static void update_alpha(DrawTextContext *s)
  1085. {
  1086. double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
  1087. if (isnan(alpha))
  1088. return;
  1089. if (alpha >= 1.0)
  1090. s->alpha = 255;
  1091. else if (alpha <= 0)
  1092. s->alpha = 0;
  1093. else
  1094. s->alpha = 256 * alpha;
  1095. }
  1096. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  1097. int width, int height)
  1098. {
  1099. DrawTextContext *s = ctx->priv;
  1100. AVFilterLink *inlink = ctx->inputs[0];
  1101. uint32_t code = 0, prev_code = 0;
  1102. int x = 0, y = 0, i = 0, ret;
  1103. int max_text_line_w = 0, len;
  1104. int box_w, box_h;
  1105. char *text;
  1106. uint8_t *p;
  1107. int y_min = 32000, y_max = -32000;
  1108. int x_min = 32000, x_max = -32000;
  1109. FT_Vector delta;
  1110. Glyph *glyph = NULL, *prev_glyph = NULL;
  1111. Glyph dummy = { 0 };
  1112. time_t now = time(0);
  1113. struct tm ltime;
  1114. AVBPrint *bp = &s->expanded_text;
  1115. FFDrawColor fontcolor;
  1116. FFDrawColor shadowcolor;
  1117. FFDrawColor bordercolor;
  1118. FFDrawColor boxcolor;
  1119. av_bprint_clear(bp);
  1120. if(s->basetime != AV_NOPTS_VALUE)
  1121. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  1122. switch (s->exp_mode) {
  1123. case EXP_NONE:
  1124. av_bprintf(bp, "%s", s->text);
  1125. break;
  1126. case EXP_NORMAL:
  1127. if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
  1128. return ret;
  1129. break;
  1130. case EXP_STRFTIME:
  1131. localtime_r(&now, &ltime);
  1132. av_bprint_strftime(bp, s->text, &ltime);
  1133. break;
  1134. }
  1135. if (s->tc_opt_string) {
  1136. char tcbuf[AV_TIMECODE_STR_SIZE];
  1137. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count_out);
  1138. av_bprint_clear(bp);
  1139. av_bprintf(bp, "%s%s", s->text, tcbuf);
  1140. }
  1141. if (!av_bprint_is_complete(bp))
  1142. return AVERROR(ENOMEM);
  1143. text = s->expanded_text.str;
  1144. if ((len = s->expanded_text.len) > s->nb_positions) {
  1145. if (!(s->positions =
  1146. av_realloc(s->positions, len*sizeof(*s->positions))))
  1147. return AVERROR(ENOMEM);
  1148. s->nb_positions = len;
  1149. }
  1150. if (s->fontcolor_expr[0]) {
  1151. /* If expression is set, evaluate and replace the static value */
  1152. av_bprint_clear(&s->expanded_fontcolor);
  1153. if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
  1154. return ret;
  1155. if (!av_bprint_is_complete(&s->expanded_fontcolor))
  1156. return AVERROR(ENOMEM);
  1157. av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
  1158. ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
  1159. if (ret)
  1160. return ret;
  1161. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  1162. }
  1163. x = 0;
  1164. y = 0;
  1165. if ((ret = update_fontsize(ctx)) < 0)
  1166. return ret;
  1167. /* load and cache glyphs */
  1168. for (i = 0, p = text; *p; i++) {
  1169. GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_invalid;);
  1170. continue_on_invalid:
  1171. /* get glyph */
  1172. dummy.code = code;
  1173. dummy.fontsize = s->fontsize;
  1174. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1175. if (!glyph) {
  1176. ret = load_glyph(ctx, &glyph, code);
  1177. if (ret < 0)
  1178. return ret;
  1179. }
  1180. y_min = FFMIN(glyph->bbox.yMin, y_min);
  1181. y_max = FFMAX(glyph->bbox.yMax, y_max);
  1182. x_min = FFMIN(glyph->bbox.xMin, x_min);
  1183. x_max = FFMAX(glyph->bbox.xMax, x_max);
  1184. }
  1185. s->max_glyph_h = y_max - y_min;
  1186. s->max_glyph_w = x_max - x_min;
  1187. /* compute and save position for each glyph */
  1188. glyph = NULL;
  1189. for (i = 0, p = text; *p; i++) {
  1190. GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_invalid2;);
  1191. continue_on_invalid2:
  1192. /* skip the \n in the sequence \r\n */
  1193. if (prev_code == '\r' && code == '\n')
  1194. continue;
  1195. prev_code = code;
  1196. if (is_newline(code)) {
  1197. max_text_line_w = FFMAX(max_text_line_w, x);
  1198. y += s->max_glyph_h + s->line_spacing;
  1199. x = 0;
  1200. continue;
  1201. }
  1202. /* get glyph */
  1203. prev_glyph = glyph;
  1204. dummy.code = code;
  1205. dummy.fontsize = s->fontsize;
  1206. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1207. /* kerning */
  1208. if (s->use_kerning && prev_glyph && glyph->code) {
  1209. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  1210. ft_kerning_default, &delta);
  1211. x += delta.x >> 6;
  1212. }
  1213. /* save position */
  1214. s->positions[i].x = x + glyph->bitmap_left;
  1215. s->positions[i].y = y - glyph->bitmap_top + y_max;
  1216. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  1217. else x += glyph->advance;
  1218. }
  1219. max_text_line_w = FFMAX(x, max_text_line_w);
  1220. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  1221. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  1222. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  1223. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  1224. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  1225. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  1226. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  1227. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1228. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  1229. /* It is necessary if x is expressed from y */
  1230. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1231. update_alpha(s);
  1232. update_color_with_alpha(s, &fontcolor , s->fontcolor );
  1233. update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
  1234. update_color_with_alpha(s, &bordercolor, s->bordercolor);
  1235. update_color_with_alpha(s, &boxcolor , s->boxcolor );
  1236. box_w = max_text_line_w;
  1237. box_h = y + s->max_glyph_h;
  1238. if (s->fix_bounds) {
  1239. /* calculate footprint of text effects */
  1240. int boxoffset = s->draw_box ? FFMAX(s->boxborderw, 0) : 0;
  1241. int borderoffset = s->borderw ? FFMAX(s->borderw, 0) : 0;
  1242. int offsetleft = FFMAX3(boxoffset, borderoffset,
  1243. (s->shadowx < 0 ? FFABS(s->shadowx) : 0));
  1244. int offsettop = FFMAX3(boxoffset, borderoffset,
  1245. (s->shadowy < 0 ? FFABS(s->shadowy) : 0));
  1246. int offsetright = FFMAX3(boxoffset, borderoffset,
  1247. (s->shadowx > 0 ? s->shadowx : 0));
  1248. int offsetbottom = FFMAX3(boxoffset, borderoffset,
  1249. (s->shadowy > 0 ? s->shadowy : 0));
  1250. if (s->x - offsetleft < 0) s->x = offsetleft;
  1251. if (s->y - offsettop < 0) s->y = offsettop;
  1252. if (s->x + box_w + offsetright > width)
  1253. s->x = FFMAX(width - box_w - offsetright, 0);
  1254. if (s->y + box_h + offsetbottom > height)
  1255. s->y = FFMAX(height - box_h - offsetbottom, 0);
  1256. }
  1257. /* draw box */
  1258. if (s->draw_box)
  1259. ff_blend_rectangle(&s->dc, &boxcolor,
  1260. frame->data, frame->linesize, width, height,
  1261. s->x - s->boxborderw, s->y - s->boxborderw,
  1262. box_w + s->boxborderw * 2, box_h + s->boxborderw * 2);
  1263. if (s->shadowx || s->shadowy) {
  1264. if ((ret = draw_glyphs(s, frame, width, height,
  1265. &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
  1266. return ret;
  1267. }
  1268. if (s->borderw) {
  1269. if ((ret = draw_glyphs(s, frame, width, height,
  1270. &bordercolor, 0, 0, s->borderw)) < 0)
  1271. return ret;
  1272. }
  1273. if ((ret = draw_glyphs(s, frame, width, height,
  1274. &fontcolor, 0, 0, 0)) < 0)
  1275. return ret;
  1276. return 0;
  1277. }
  1278. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  1279. {
  1280. AVFilterContext *ctx = inlink->dst;
  1281. AVFilterLink *outlink = ctx->outputs[0];
  1282. DrawTextContext *s = ctx->priv;
  1283. int ret;
  1284. if (s->reload) {
  1285. if ((ret = load_textfile(ctx)) < 0) {
  1286. av_frame_free(&frame);
  1287. return ret;
  1288. }
  1289. #if CONFIG_LIBFRIBIDI
  1290. if (s->text_shaping)
  1291. if ((ret = shape_text(ctx)) < 0) {
  1292. av_frame_free(&frame);
  1293. return ret;
  1294. }
  1295. #endif
  1296. }
  1297. s->var_values[VAR_N] = inlink->frame_count_out + s->start_number;
  1298. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  1299. NAN : frame->pts * av_q2d(inlink->time_base);
  1300. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  1301. s->var_values[VAR_PKT_POS] = frame->pkt_pos;
  1302. s->var_values[VAR_PKT_DURATION] = frame->pkt_duration * av_q2d(inlink->time_base);
  1303. s->var_values[VAR_PKT_SIZE] = frame->pkt_size;
  1304. s->metadata = frame->metadata;
  1305. draw_text(ctx, frame, frame->width, frame->height);
  1306. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  1307. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  1308. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  1309. s->x, s->y);
  1310. return ff_filter_frame(outlink, frame);
  1311. }
  1312. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  1313. {
  1314. .name = "default",
  1315. .type = AVMEDIA_TYPE_VIDEO,
  1316. .filter_frame = filter_frame,
  1317. .config_props = config_input,
  1318. .needs_writable = 1,
  1319. },
  1320. { NULL }
  1321. };
  1322. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  1323. {
  1324. .name = "default",
  1325. .type = AVMEDIA_TYPE_VIDEO,
  1326. },
  1327. { NULL }
  1328. };
  1329. AVFilter ff_vf_drawtext = {
  1330. .name = "drawtext",
  1331. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  1332. .priv_size = sizeof(DrawTextContext),
  1333. .priv_class = &drawtext_class,
  1334. .init = init,
  1335. .uninit = uninit,
  1336. .query_formats = query_formats,
  1337. .inputs = avfilter_vf_drawtext_inputs,
  1338. .outputs = avfilter_vf_drawtext_outputs,
  1339. .process_command = command,
  1340. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
  1341. };