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.

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