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.

1002 lines
35KB

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