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.

1041 lines
37KB

  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 <sys/time.h>
  28. #include <time.h>
  29. #include "config.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/bprint.h"
  32. #include "libavutil/common.h"
  33. #include "libavutil/file.h"
  34. #include "libavutil/eval.h"
  35. #include "libavutil/opt.h"
  36. #include "libavutil/random_seed.h"
  37. #include "libavutil/parseutils.h"
  38. #include "libavutil/timecode.h"
  39. #include "libavutil/tree.h"
  40. #include "libavutil/lfg.h"
  41. #include "avfilter.h"
  42. #include "drawutils.h"
  43. #include "formats.h"
  44. #include "internal.h"
  45. #include "video.h"
  46. #include <ft2build.h>
  47. #include <freetype/config/ftheader.h>
  48. #include FT_FREETYPE_H
  49. #include FT_GLYPH_H
  50. #if CONFIG_FONTCONFIG
  51. #include <fontconfig/fontconfig.h>
  52. #endif
  53. static const char *const var_names[] = {
  54. "dar",
  55. "hsub", "vsub",
  56. "line_h", "lh", ///< line height, same as max_glyph_h
  57. "main_h", "h", "H", ///< height of the input video
  58. "main_w", "w", "W", ///< width of the input video
  59. "max_glyph_a", "ascent", ///< max glyph ascent
  60. "max_glyph_d", "descent", ///< min glyph descent
  61. "max_glyph_h", ///< max glyph height
  62. "max_glyph_w", ///< max glyph width
  63. "n", ///< number of frame
  64. "sar",
  65. "t", ///< timestamp expressed in seconds
  66. "text_h", "th", ///< height of the rendered text
  67. "text_w", "tw", ///< width of the rendered text
  68. "x",
  69. "y",
  70. NULL
  71. };
  72. static const char *const fun2_names[] = {
  73. "rand"
  74. };
  75. static double drand(void *opaque, double min, double max)
  76. {
  77. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  78. }
  79. typedef double (*eval_func2)(void *, double a, double b);
  80. static const eval_func2 fun2[] = {
  81. drand,
  82. NULL
  83. };
  84. enum var_name {
  85. VAR_DAR,
  86. VAR_HSUB, VAR_VSUB,
  87. VAR_LINE_H, VAR_LH,
  88. VAR_MAIN_H, VAR_h, VAR_H,
  89. VAR_MAIN_W, VAR_w, VAR_W,
  90. VAR_MAX_GLYPH_A, VAR_ASCENT,
  91. VAR_MAX_GLYPH_D, VAR_DESCENT,
  92. VAR_MAX_GLYPH_H,
  93. VAR_MAX_GLYPH_W,
  94. VAR_N,
  95. VAR_SAR,
  96. VAR_T,
  97. VAR_TEXT_H, VAR_TH,
  98. VAR_TEXT_W, VAR_TW,
  99. VAR_X,
  100. VAR_Y,
  101. VAR_VARS_NB
  102. };
  103. enum expansion_mode {
  104. EXP_NONE,
  105. EXP_NORMAL,
  106. EXP_STRFTIME,
  107. };
  108. typedef struct {
  109. const AVClass *class;
  110. enum expansion_mode exp_mode; ///< expansion mode to use for the text
  111. int reinit; ///< tells if the filter is being reinited
  112. uint8_t *fontfile; ///< font to be used
  113. uint8_t *text; ///< text to be drawn
  114. AVBPrint expanded_text; ///< used to contain the expanded text
  115. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  116. FT_Vector *positions; ///< positions for each element in the text
  117. size_t nb_positions; ///< number of elements of positions array
  118. char *textfile; ///< file with text to be drawn
  119. int x; ///< x position to start drawing text
  120. int y; ///< y position to start drawing text
  121. int max_glyph_w; ///< max glyph width
  122. int max_glyph_h; ///< max glyph height
  123. int shadowx, shadowy;
  124. unsigned int fontsize; ///< font size to use
  125. char *fontcolor_string; ///< font color as string
  126. char *boxcolor_string; ///< box color as string
  127. char *shadowcolor_string; ///< shadow color as string
  128. short int draw_box; ///< draw box around text - true or false
  129. int use_kerning; ///< font kerning is used - true/false
  130. int tabsize; ///< tab size
  131. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  132. FFDrawContext dc;
  133. FFDrawColor fontcolor; ///< foreground color
  134. FFDrawColor shadowcolor; ///< shadow color
  135. FFDrawColor boxcolor; ///< background color
  136. FT_Library library; ///< freetype font library handle
  137. FT_Face face; ///< freetype font face handle
  138. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  139. char *x_expr; ///< expression for x position
  140. char *y_expr; ///< expression for y position
  141. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  142. int64_t basetime; ///< base pts time in the real world for display
  143. double var_values[VAR_VARS_NB];
  144. char *draw_expr; ///< expression for draw
  145. AVExpr *draw_pexpr; ///< parsed expression for draw
  146. int draw; ///< set to zero to prevent drawing
  147. AVLFG prng; ///< random
  148. char *tc_opt_string; ///< specified timecode option string
  149. AVRational tc_rate; ///< frame rate for timecode
  150. AVTimecode tc; ///< timecode context
  151. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  152. int frame_id;
  153. int reload; ///< reload text file for each frame
  154. } DrawTextContext;
  155. #define OFFSET(x) offsetof(DrawTextContext, x)
  156. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  157. static const AVOption drawtext_options[]= {
  158. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  159. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  160. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  161. {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  162. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  163. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  164. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  165. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  166. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  167. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  168. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  169. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  170. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  171. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  172. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
  173. {"expansion","set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  174. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  175. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  176. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  177. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  178. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  179. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  180. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  181. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  182. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  183. {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  184. /* FT_LOAD_* flags */
  185. {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.i64=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, FLAGS, "ft_load_flags"},
  186. {"default", "set default", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  187. {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  188. {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  189. {"render", "set render", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_RENDER}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  190. {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  191. {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  192. {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  193. {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  194. {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  195. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  196. {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  197. {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  198. {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  199. {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  200. {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  201. {NULL},
  202. };
  203. AVFILTER_DEFINE_CLASS(drawtext);
  204. #undef __FTERRORS_H__
  205. #define FT_ERROR_START_LIST {
  206. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  207. #define FT_ERROR_END_LIST { 0, NULL } };
  208. struct ft_error
  209. {
  210. int err;
  211. const char *err_msg;
  212. } static ft_errors[] =
  213. #include FT_ERRORS_H
  214. #define FT_ERRMSG(e) ft_errors[e].err_msg
  215. typedef struct {
  216. FT_Glyph *glyph;
  217. uint32_t code;
  218. FT_Bitmap bitmap; ///< array holding bitmaps of font
  219. FT_BBox bbox;
  220. int advance;
  221. int bitmap_left;
  222. int bitmap_top;
  223. } Glyph;
  224. static int glyph_cmp(void *key, const void *b)
  225. {
  226. const Glyph *a = key, *bb = b;
  227. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  228. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  229. }
  230. /**
  231. * Load glyphs corresponding to the UTF-32 codepoint code.
  232. */
  233. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  234. {
  235. DrawTextContext *dtext = ctx->priv;
  236. Glyph *glyph;
  237. struct AVTreeNode *node = NULL;
  238. int ret;
  239. /* load glyph into dtext->face->glyph */
  240. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  241. return AVERROR(EINVAL);
  242. /* save glyph */
  243. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  244. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  245. ret = AVERROR(ENOMEM);
  246. goto error;
  247. }
  248. glyph->code = code;
  249. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  250. ret = AVERROR(EINVAL);
  251. goto error;
  252. }
  253. glyph->bitmap = dtext->face->glyph->bitmap;
  254. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  255. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  256. glyph->advance = dtext->face->glyph->advance.x >> 6;
  257. /* measure text height to calculate text_height (or the maximum text height) */
  258. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  259. /* cache the newly created glyph */
  260. if (!(node = av_tree_node_alloc())) {
  261. ret = AVERROR(ENOMEM);
  262. goto error;
  263. }
  264. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  265. if (glyph_ptr)
  266. *glyph_ptr = glyph;
  267. return 0;
  268. error:
  269. if (glyph)
  270. av_freep(&glyph->glyph);
  271. av_freep(&glyph);
  272. av_freep(&node);
  273. return ret;
  274. }
  275. static int load_font_file(AVFilterContext *ctx, const char *path, int index,
  276. const char **error)
  277. {
  278. DrawTextContext *dtext = ctx->priv;
  279. int err;
  280. err = FT_New_Face(dtext->library, path, index, &dtext->face);
  281. if (err) {
  282. *error = FT_ERRMSG(err);
  283. return AVERROR(EINVAL);
  284. }
  285. return 0;
  286. }
  287. #if CONFIG_FONTCONFIG
  288. static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
  289. {
  290. DrawTextContext *dtext = ctx->priv;
  291. FcConfig *fontconfig;
  292. FcPattern *pattern, *fpat;
  293. FcResult result = FcResultMatch;
  294. FcChar8 *filename;
  295. int err, index;
  296. double size;
  297. fontconfig = FcInitLoadConfigAndFonts();
  298. if (!fontconfig) {
  299. *error = "impossible to init fontconfig\n";
  300. return AVERROR(EINVAL);
  301. }
  302. pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
  303. (uint8_t *)(intptr_t)"default");
  304. if (!pattern) {
  305. *error = "could not parse fontconfig pattern";
  306. return AVERROR(EINVAL);
  307. }
  308. if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
  309. *error = "could not substitue fontconfig options"; /* very unlikely */
  310. return AVERROR(EINVAL);
  311. }
  312. FcDefaultSubstitute(pattern);
  313. fpat = FcFontMatch(fontconfig, pattern, &result);
  314. if (!fpat || result != FcResultMatch) {
  315. *error = "impossible to find a matching font";
  316. return AVERROR(EINVAL);
  317. }
  318. if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
  319. FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
  320. FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
  321. *error = "impossible to find font information";
  322. return AVERROR(EINVAL);
  323. }
  324. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  325. if (!dtext->fontsize)
  326. dtext->fontsize = size + 0.5;
  327. err = load_font_file(ctx, filename, index, error);
  328. if (err)
  329. return err;
  330. FcPatternDestroy(fpat);
  331. FcPatternDestroy(pattern);
  332. FcConfigDestroy(fontconfig);
  333. return 0;
  334. }
  335. #endif
  336. static int load_font(AVFilterContext *ctx)
  337. {
  338. DrawTextContext *dtext = ctx->priv;
  339. int err;
  340. const char *error = "unknown error\n";
  341. /* load the face, and set up the encoding, which is by default UTF-8 */
  342. err = load_font_file(ctx, dtext->fontfile, 0, &error);
  343. if (!err)
  344. return 0;
  345. #if CONFIG_FONTCONFIG
  346. err = load_font_fontconfig(ctx, &error);
  347. if (!err)
  348. return 0;
  349. #endif
  350. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  351. dtext->fontfile, error);
  352. return err;
  353. }
  354. static int load_textfile(AVFilterContext *ctx)
  355. {
  356. DrawTextContext *dtext = ctx->priv;
  357. int err;
  358. uint8_t *textbuf;
  359. size_t textbuf_size;
  360. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  361. av_log(ctx, AV_LOG_ERROR,
  362. "The text file '%s' could not be read or is empty\n",
  363. dtext->textfile);
  364. return err;
  365. }
  366. if (!(dtext->text = av_realloc(dtext->text, textbuf_size + 1)))
  367. return AVERROR(ENOMEM);
  368. memcpy(dtext->text, textbuf, textbuf_size);
  369. dtext->text[textbuf_size] = 0;
  370. av_file_unmap(textbuf, textbuf_size);
  371. return 0;
  372. }
  373. static av_cold int init(AVFilterContext *ctx, const char *args)
  374. {
  375. int err;
  376. DrawTextContext *dtext = ctx->priv;
  377. Glyph *glyph;
  378. dtext->class = &drawtext_class;
  379. av_opt_set_defaults(dtext);
  380. if ((err = av_set_options_string(dtext, args, "=", ":")) < 0)
  381. return err;
  382. if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
  383. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  384. return AVERROR(EINVAL);
  385. }
  386. if (dtext->textfile) {
  387. if (dtext->text) {
  388. av_log(ctx, AV_LOG_ERROR,
  389. "Both text and text file provided. Please provide only one\n");
  390. return AVERROR(EINVAL);
  391. }
  392. if ((err = load_textfile(ctx)) < 0)
  393. return err;
  394. }
  395. if (dtext->reload && !dtext->textfile)
  396. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  397. if (dtext->tc_opt_string) {
  398. int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
  399. dtext->tc_opt_string, ctx);
  400. if (ret < 0)
  401. return ret;
  402. if (dtext->tc24hmax)
  403. dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  404. if (!dtext->text)
  405. dtext->text = av_strdup("");
  406. }
  407. if (!dtext->text) {
  408. av_log(ctx, AV_LOG_ERROR,
  409. "Either text, a valid file or a timecode must be provided\n");
  410. return AVERROR(EINVAL);
  411. }
  412. if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
  413. av_log(ctx, AV_LOG_ERROR,
  414. "Invalid font color '%s'\n", dtext->fontcolor_string);
  415. return err;
  416. }
  417. if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
  418. av_log(ctx, AV_LOG_ERROR,
  419. "Invalid box color '%s'\n", dtext->boxcolor_string);
  420. return err;
  421. }
  422. if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
  423. av_log(ctx, AV_LOG_ERROR,
  424. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  425. return err;
  426. }
  427. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  428. av_log(ctx, AV_LOG_ERROR,
  429. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  430. return AVERROR(EINVAL);
  431. }
  432. err = load_font(ctx);
  433. if (err)
  434. return err;
  435. if (!dtext->fontsize)
  436. dtext->fontsize = 16;
  437. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  438. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  439. dtext->fontsize, FT_ERRMSG(err));
  440. return AVERROR(EINVAL);
  441. }
  442. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  443. /* load the fallback glyph with code 0 */
  444. load_glyph(ctx, NULL, 0);
  445. /* set the tabsize in pixels */
  446. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  447. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  448. return err;
  449. }
  450. dtext->tabsize *= glyph->advance;
  451. if (dtext->exp_mode == EXP_STRFTIME &&
  452. (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
  453. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  454. av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  455. return 0;
  456. }
  457. static int query_formats(AVFilterContext *ctx)
  458. {
  459. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  460. return 0;
  461. }
  462. static int glyph_enu_free(void *opaque, void *elem)
  463. {
  464. Glyph *glyph = elem;
  465. FT_Done_Glyph(*glyph->glyph);
  466. av_freep(&glyph->glyph);
  467. av_free(elem);
  468. return 0;
  469. }
  470. static av_cold void uninit(AVFilterContext *ctx)
  471. {
  472. DrawTextContext *dtext = ctx->priv;
  473. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  474. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  475. av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
  476. av_opt_free(dtext);
  477. av_freep(&dtext->positions);
  478. dtext->nb_positions = 0;
  479. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  480. av_tree_destroy(dtext->glyphs);
  481. dtext->glyphs = NULL;
  482. FT_Done_Face(dtext->face);
  483. FT_Done_FreeType(dtext->library);
  484. av_bprint_finalize(&dtext->expanded_text, NULL);
  485. }
  486. static inline int is_newline(uint32_t c)
  487. {
  488. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  489. }
  490. static int config_input(AVFilterLink *inlink)
  491. {
  492. AVFilterContext *ctx = inlink->dst;
  493. DrawTextContext *dtext = ctx->priv;
  494. int ret;
  495. ff_draw_init(&dtext->dc, inlink->format, 0);
  496. ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
  497. ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
  498. ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
  499. dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
  500. dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
  501. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  502. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  503. dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
  504. dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
  505. dtext->var_values[VAR_X] = NAN;
  506. dtext->var_values[VAR_Y] = NAN;
  507. if (!dtext->reinit)
  508. dtext->var_values[VAR_N] = 0;
  509. dtext->var_values[VAR_T] = NAN;
  510. av_lfg_init(&dtext->prng, av_get_random_seed());
  511. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  512. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  513. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  514. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  515. (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
  516. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  517. return AVERROR(EINVAL);
  518. return 0;
  519. }
  520. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  521. {
  522. DrawTextContext *dtext = ctx->priv;
  523. if (!strcmp(cmd, "reinit")) {
  524. int ret;
  525. uninit(ctx);
  526. dtext->reinit = 1;
  527. if ((ret = init(ctx, arg)) < 0)
  528. return ret;
  529. return config_input(ctx->inputs[0]);
  530. }
  531. return AVERROR(ENOSYS);
  532. }
  533. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  534. char *fct, unsigned argc, char **argv, int tag)
  535. {
  536. DrawTextContext *dtext = ctx->priv;
  537. av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
  538. return 0;
  539. }
  540. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  541. char *fct, unsigned argc, char **argv, int tag)
  542. {
  543. DrawTextContext *dtext = ctx->priv;
  544. av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
  545. return 0;
  546. }
  547. #if !HAVE_LOCALTIME_R
  548. static void localtime_r(const time_t *t, struct tm *tm)
  549. {
  550. *tm = *localtime(t);
  551. }
  552. #endif
  553. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  554. char *fct, unsigned argc, char **argv, int tag)
  555. {
  556. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  557. time_t now;
  558. struct tm tm;
  559. time(&now);
  560. if (tag == 'L')
  561. localtime_r(&now, &tm);
  562. else
  563. tm = *gmtime(&now);
  564. av_bprint_strftime(bp, fmt, &tm);
  565. return 0;
  566. }
  567. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  568. char *fct, unsigned argc, char **argv, int tag)
  569. {
  570. DrawTextContext *dtext = ctx->priv;
  571. double res;
  572. int ret;
  573. ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
  574. NULL, NULL, fun2_names, fun2,
  575. &dtext->prng, 0, ctx);
  576. if (ret < 0)
  577. av_log(ctx, AV_LOG_ERROR,
  578. "Expression '%s' for the expr text expansion function is not valid\n",
  579. argv[0]);
  580. else
  581. av_bprintf(bp, "%f", res);
  582. return ret;
  583. }
  584. static const struct drawtext_function {
  585. const char *name;
  586. unsigned argc_min, argc_max;
  587. int tag; /** opaque argument to func */
  588. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  589. } functions[] = {
  590. { "expr", 1, 1, 0, func_eval_expr },
  591. { "e", 1, 1, 0, func_eval_expr },
  592. { "pts", 0, 0, 0, func_pts },
  593. { "gmtime", 0, 1, 'G', func_strftime },
  594. { "localtime", 0, 1, 'L', func_strftime },
  595. { "frame_num", 0, 0, 0, func_frame_num },
  596. { "n", 0, 0, 0, func_frame_num },
  597. };
  598. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  599. unsigned argc, char **argv)
  600. {
  601. unsigned i;
  602. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  603. if (strcmp(fct, functions[i].name))
  604. continue;
  605. if (argc < functions[i].argc_min) {
  606. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  607. fct, functions[i].argc_min);
  608. return AVERROR(EINVAL);
  609. }
  610. if (argc > functions[i].argc_max) {
  611. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  612. fct, functions[i].argc_max);
  613. return AVERROR(EINVAL);
  614. }
  615. break;
  616. }
  617. if (i >= FF_ARRAY_ELEMS(functions)) {
  618. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  619. return AVERROR(EINVAL);
  620. }
  621. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  622. }
  623. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  624. {
  625. const char *text = *rtext;
  626. char *argv[16] = { NULL };
  627. unsigned argc = 0, i;
  628. int ret;
  629. if (*text != '{') {
  630. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  631. return AVERROR(EINVAL);
  632. }
  633. text++;
  634. while (1) {
  635. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  636. ret = AVERROR(ENOMEM);
  637. goto end;
  638. }
  639. if (!*text) {
  640. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  641. ret = AVERROR(EINVAL);
  642. goto end;
  643. }
  644. if (argc == FF_ARRAY_ELEMS(argv))
  645. av_freep(&argv[--argc]); /* error will be caught later */
  646. if (*text == '}')
  647. break;
  648. text++;
  649. }
  650. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  651. goto end;
  652. ret = 0;
  653. *rtext = (char *)text + 1;
  654. end:
  655. for (i = 0; i < argc; i++)
  656. av_freep(&argv[i]);
  657. return ret;
  658. }
  659. static int expand_text(AVFilterContext *ctx)
  660. {
  661. DrawTextContext *dtext = ctx->priv;
  662. char *text = dtext->text;
  663. AVBPrint *bp = &dtext->expanded_text;
  664. int ret;
  665. av_bprint_clear(bp);
  666. while (*text) {
  667. if (*text == '\\' && text[1]) {
  668. av_bprint_chars(bp, text[1], 1);
  669. text += 2;
  670. } else if (*text == '%') {
  671. text++;
  672. if ((ret = expand_function(ctx, bp, &text)) < 0)
  673. return ret;
  674. } else {
  675. av_bprint_chars(bp, *text, 1);
  676. text++;
  677. }
  678. }
  679. if (!av_bprint_is_complete(bp))
  680. return AVERROR(ENOMEM);
  681. return 0;
  682. }
  683. static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
  684. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  685. {
  686. char *text = dtext->expanded_text.str;
  687. uint32_t code = 0;
  688. int i, x1, y1;
  689. uint8_t *p;
  690. Glyph *glyph = NULL;
  691. for (i = 0, p = text; *p; i++) {
  692. Glyph dummy = { 0 };
  693. GET_UTF8(code, *p++, continue;);
  694. /* skip new line chars, just go to new line */
  695. if (code == '\n' || code == '\r' || code == '\t')
  696. continue;
  697. dummy.code = code;
  698. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  699. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  700. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  701. return AVERROR(EINVAL);
  702. x1 = dtext->positions[i].x+dtext->x+x;
  703. y1 = dtext->positions[i].y+dtext->y+y;
  704. ff_blend_mask(&dtext->dc, color,
  705. picref->data, picref->linesize, width, height,
  706. glyph->bitmap.buffer, glyph->bitmap.pitch,
  707. glyph->bitmap.width, glyph->bitmap.rows,
  708. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  709. 0, x1, y1);
  710. }
  711. return 0;
  712. }
  713. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  714. int width, int height)
  715. {
  716. DrawTextContext *dtext = ctx->priv;
  717. uint32_t code = 0, prev_code = 0;
  718. int x = 0, y = 0, i = 0, ret;
  719. int max_text_line_w = 0, len;
  720. int box_w, box_h;
  721. char *text = dtext->text;
  722. uint8_t *p;
  723. int y_min = 32000, y_max = -32000;
  724. int x_min = 32000, x_max = -32000;
  725. FT_Vector delta;
  726. Glyph *glyph = NULL, *prev_glyph = NULL;
  727. Glyph dummy = { 0 };
  728. time_t now = time(0);
  729. struct tm ltime;
  730. AVBPrint *bp = &dtext->expanded_text;
  731. av_bprint_clear(bp);
  732. if(dtext->basetime != AV_NOPTS_VALUE)
  733. now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  734. switch (dtext->exp_mode) {
  735. case EXP_NONE:
  736. av_bprintf(bp, "%s", dtext->text);
  737. break;
  738. case EXP_NORMAL:
  739. if ((ret = expand_text(ctx)) < 0)
  740. return ret;
  741. break;
  742. case EXP_STRFTIME:
  743. localtime_r(&now, &ltime);
  744. av_bprint_strftime(bp, dtext->text, &ltime);
  745. break;
  746. }
  747. if (dtext->tc_opt_string) {
  748. char tcbuf[AV_TIMECODE_STR_SIZE];
  749. av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
  750. av_bprint_clear(bp);
  751. av_bprintf(bp, "%s%s", dtext->text, tcbuf);
  752. }
  753. if (!av_bprint_is_complete(bp))
  754. return AVERROR(ENOMEM);
  755. text = dtext->expanded_text.str;
  756. if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
  757. if (!(dtext->positions =
  758. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  759. return AVERROR(ENOMEM);
  760. dtext->nb_positions = len;
  761. }
  762. x = 0;
  763. y = 0;
  764. /* load and cache glyphs */
  765. for (i = 0, p = text; *p; i++) {
  766. GET_UTF8(code, *p++, continue;);
  767. /* get glyph */
  768. dummy.code = code;
  769. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  770. if (!glyph) {
  771. load_glyph(ctx, &glyph, code);
  772. }
  773. y_min = FFMIN(glyph->bbox.yMin, y_min);
  774. y_max = FFMAX(glyph->bbox.yMax, y_max);
  775. x_min = FFMIN(glyph->bbox.xMin, x_min);
  776. x_max = FFMAX(glyph->bbox.xMax, x_max);
  777. }
  778. dtext->max_glyph_h = y_max - y_min;
  779. dtext->max_glyph_w = x_max - x_min;
  780. /* compute and save position for each glyph */
  781. glyph = NULL;
  782. for (i = 0, p = text; *p; i++) {
  783. GET_UTF8(code, *p++, continue;);
  784. /* skip the \n in the sequence \r\n */
  785. if (prev_code == '\r' && code == '\n')
  786. continue;
  787. prev_code = code;
  788. if (is_newline(code)) {
  789. max_text_line_w = FFMAX(max_text_line_w, x);
  790. y += dtext->max_glyph_h;
  791. x = 0;
  792. continue;
  793. }
  794. /* get glyph */
  795. prev_glyph = glyph;
  796. dummy.code = code;
  797. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  798. /* kerning */
  799. if (dtext->use_kerning && prev_glyph && glyph->code) {
  800. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  801. ft_kerning_default, &delta);
  802. x += delta.x >> 6;
  803. }
  804. /* save position */
  805. dtext->positions[i].x = x + glyph->bitmap_left;
  806. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  807. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  808. else x += glyph->advance;
  809. }
  810. max_text_line_w = FFMAX(x, max_text_line_w);
  811. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  812. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  813. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  814. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  815. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  816. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  817. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  818. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  819. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  820. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  821. dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
  822. if(!dtext->draw)
  823. return 0;
  824. box_w = FFMIN(width - 1 , max_text_line_w);
  825. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  826. /* draw box */
  827. if (dtext->draw_box)
  828. ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
  829. picref->data, picref->linesize, width, height,
  830. dtext->x, dtext->y, box_w, box_h);
  831. if (dtext->shadowx || dtext->shadowy) {
  832. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,
  833. &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  834. return ret;
  835. }
  836. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,
  837. &dtext->fontcolor, 0, 0)) < 0)
  838. return ret;
  839. return 0;
  840. }
  841. static int filter_frame(AVFilterLink *inlink, AVFilterBufferRef *frame)
  842. {
  843. AVFilterContext *ctx = inlink->dst;
  844. AVFilterLink *outlink = ctx->outputs[0];
  845. DrawTextContext *dtext = ctx->priv;
  846. int ret;
  847. if (dtext->reload)
  848. if ((ret = load_textfile(ctx)) < 0)
  849. return ret;
  850. dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  851. NAN : frame->pts * av_q2d(inlink->time_base);
  852. draw_text(ctx, frame, frame->video->w, frame->video->h);
  853. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  854. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  855. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  856. dtext->x, dtext->y);
  857. dtext->var_values[VAR_N] += 1.0;
  858. return ff_filter_frame(outlink, frame);
  859. }
  860. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  861. {
  862. .name = "default",
  863. .type = AVMEDIA_TYPE_VIDEO,
  864. .get_video_buffer = ff_null_get_video_buffer,
  865. .filter_frame = filter_frame,
  866. .config_props = config_input,
  867. .min_perms = AV_PERM_WRITE |
  868. AV_PERM_READ,
  869. },
  870. { NULL }
  871. };
  872. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  873. {
  874. .name = "default",
  875. .type = AVMEDIA_TYPE_VIDEO,
  876. },
  877. { NULL }
  878. };
  879. AVFilter avfilter_vf_drawtext = {
  880. .name = "drawtext",
  881. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  882. .priv_size = sizeof(DrawTextContext),
  883. .init = init,
  884. .uninit = uninit,
  885. .query_formats = query_formats,
  886. .inputs = avfilter_vf_drawtext_inputs,
  887. .outputs = avfilter_vf_drawtext_outputs,
  888. .process_command = command,
  889. .priv_class = &drawtext_class,
  890. };