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.

1381 lines
47KB

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