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.

1400 lines
48KB

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