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.

1034 lines
36KB

  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", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  187. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  188. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  189. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  190. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  191. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  192. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  193. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  194. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  195. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  196. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  197. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  198. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  199. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  200. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "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)
  374. {
  375. int err;
  376. DrawTextContext *dtext = ctx->priv;
  377. Glyph *glyph;
  378. if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
  379. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  380. return AVERROR(EINVAL);
  381. }
  382. if (dtext->textfile) {
  383. if (dtext->text) {
  384. av_log(ctx, AV_LOG_ERROR,
  385. "Both text and text file provided. Please provide only one\n");
  386. return AVERROR(EINVAL);
  387. }
  388. if ((err = load_textfile(ctx)) < 0)
  389. return err;
  390. }
  391. if (dtext->reload && !dtext->textfile)
  392. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  393. if (dtext->tc_opt_string) {
  394. int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
  395. dtext->tc_opt_string, ctx);
  396. if (ret < 0)
  397. return ret;
  398. if (dtext->tc24hmax)
  399. dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  400. if (!dtext->text)
  401. dtext->text = av_strdup("");
  402. }
  403. if (!dtext->text) {
  404. av_log(ctx, AV_LOG_ERROR,
  405. "Either text, a valid file or a timecode must be provided\n");
  406. return AVERROR(EINVAL);
  407. }
  408. if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
  409. av_log(ctx, AV_LOG_ERROR,
  410. "Invalid font color '%s'\n", dtext->fontcolor_string);
  411. return err;
  412. }
  413. if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
  414. av_log(ctx, AV_LOG_ERROR,
  415. "Invalid box color '%s'\n", dtext->boxcolor_string);
  416. return err;
  417. }
  418. if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
  419. av_log(ctx, AV_LOG_ERROR,
  420. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  421. return err;
  422. }
  423. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  424. av_log(ctx, AV_LOG_ERROR,
  425. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  426. return AVERROR(EINVAL);
  427. }
  428. err = load_font(ctx);
  429. if (err)
  430. return err;
  431. if (!dtext->fontsize)
  432. dtext->fontsize = 16;
  433. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  434. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  435. dtext->fontsize, FT_ERRMSG(err));
  436. return AVERROR(EINVAL);
  437. }
  438. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  439. /* load the fallback glyph with code 0 */
  440. load_glyph(ctx, NULL, 0);
  441. /* set the tabsize in pixels */
  442. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  443. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  444. return err;
  445. }
  446. dtext->tabsize *= glyph->advance;
  447. if (dtext->exp_mode == EXP_STRFTIME &&
  448. (strchr(dtext->text, '%') || strchr(dtext->text, '\\')))
  449. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  450. av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  451. return 0;
  452. }
  453. static int query_formats(AVFilterContext *ctx)
  454. {
  455. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  456. return 0;
  457. }
  458. static int glyph_enu_free(void *opaque, void *elem)
  459. {
  460. Glyph *glyph = elem;
  461. FT_Done_Glyph(*glyph->glyph);
  462. av_freep(&glyph->glyph);
  463. av_free(elem);
  464. return 0;
  465. }
  466. static av_cold void uninit(AVFilterContext *ctx)
  467. {
  468. DrawTextContext *dtext = ctx->priv;
  469. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  470. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  471. av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
  472. av_freep(&dtext->positions);
  473. dtext->nb_positions = 0;
  474. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  475. av_tree_destroy(dtext->glyphs);
  476. dtext->glyphs = NULL;
  477. FT_Done_Face(dtext->face);
  478. FT_Done_FreeType(dtext->library);
  479. av_bprint_finalize(&dtext->expanded_text, NULL);
  480. }
  481. static inline int is_newline(uint32_t c)
  482. {
  483. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  484. }
  485. static int config_input(AVFilterLink *inlink)
  486. {
  487. AVFilterContext *ctx = inlink->dst;
  488. DrawTextContext *dtext = ctx->priv;
  489. int ret;
  490. ff_draw_init(&dtext->dc, inlink->format, 0);
  491. ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
  492. ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
  493. ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
  494. dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
  495. dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
  496. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  497. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  498. dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
  499. dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
  500. dtext->var_values[VAR_X] = NAN;
  501. dtext->var_values[VAR_Y] = NAN;
  502. if (!dtext->reinit)
  503. dtext->var_values[VAR_N] = 0;
  504. dtext->var_values[VAR_T] = NAN;
  505. av_lfg_init(&dtext->prng, av_get_random_seed());
  506. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  507. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  508. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  509. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  510. (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
  511. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  512. return AVERROR(EINVAL);
  513. return 0;
  514. }
  515. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  516. {
  517. DrawTextContext *dtext = ctx->priv;
  518. if (!strcmp(cmd, "reinit")) {
  519. int ret;
  520. uninit(ctx);
  521. dtext->reinit = 1;
  522. if ((ret = init(ctx)) < 0)
  523. return ret;
  524. return config_input(ctx->inputs[0]);
  525. }
  526. return AVERROR(ENOSYS);
  527. }
  528. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  529. char *fct, unsigned argc, char **argv, int tag)
  530. {
  531. DrawTextContext *dtext = ctx->priv;
  532. av_bprintf(bp, "%.6f", dtext->var_values[VAR_T]);
  533. return 0;
  534. }
  535. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  536. char *fct, unsigned argc, char **argv, int tag)
  537. {
  538. DrawTextContext *dtext = ctx->priv;
  539. av_bprintf(bp, "%d", (int)dtext->var_values[VAR_N]);
  540. return 0;
  541. }
  542. #if !HAVE_LOCALTIME_R
  543. static void localtime_r(const time_t *t, struct tm *tm)
  544. {
  545. *tm = *localtime(t);
  546. }
  547. #endif
  548. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  549. char *fct, unsigned argc, char **argv, int tag)
  550. {
  551. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  552. time_t now;
  553. struct tm tm;
  554. time(&now);
  555. if (tag == 'L')
  556. localtime_r(&now, &tm);
  557. else
  558. tm = *gmtime(&now);
  559. av_bprint_strftime(bp, fmt, &tm);
  560. return 0;
  561. }
  562. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  563. char *fct, unsigned argc, char **argv, int tag)
  564. {
  565. DrawTextContext *dtext = ctx->priv;
  566. double res;
  567. int ret;
  568. ret = av_expr_parse_and_eval(&res, argv[0], var_names, dtext->var_values,
  569. NULL, NULL, fun2_names, fun2,
  570. &dtext->prng, 0, ctx);
  571. if (ret < 0)
  572. av_log(ctx, AV_LOG_ERROR,
  573. "Expression '%s' for the expr text expansion function is not valid\n",
  574. argv[0]);
  575. else
  576. av_bprintf(bp, "%f", res);
  577. return ret;
  578. }
  579. static const struct drawtext_function {
  580. const char *name;
  581. unsigned argc_min, argc_max;
  582. int tag; /** opaque argument to func */
  583. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  584. } functions[] = {
  585. { "expr", 1, 1, 0, func_eval_expr },
  586. { "e", 1, 1, 0, func_eval_expr },
  587. { "pts", 0, 0, 0, func_pts },
  588. { "gmtime", 0, 1, 'G', func_strftime },
  589. { "localtime", 0, 1, 'L', func_strftime },
  590. { "frame_num", 0, 0, 0, func_frame_num },
  591. { "n", 0, 0, 0, func_frame_num },
  592. };
  593. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  594. unsigned argc, char **argv)
  595. {
  596. unsigned i;
  597. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  598. if (strcmp(fct, functions[i].name))
  599. continue;
  600. if (argc < functions[i].argc_min) {
  601. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  602. fct, functions[i].argc_min);
  603. return AVERROR(EINVAL);
  604. }
  605. if (argc > functions[i].argc_max) {
  606. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  607. fct, functions[i].argc_max);
  608. return AVERROR(EINVAL);
  609. }
  610. break;
  611. }
  612. if (i >= FF_ARRAY_ELEMS(functions)) {
  613. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  614. return AVERROR(EINVAL);
  615. }
  616. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  617. }
  618. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  619. {
  620. const char *text = *rtext;
  621. char *argv[16] = { NULL };
  622. unsigned argc = 0, i;
  623. int ret;
  624. if (*text != '{') {
  625. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  626. return AVERROR(EINVAL);
  627. }
  628. text++;
  629. while (1) {
  630. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  631. ret = AVERROR(ENOMEM);
  632. goto end;
  633. }
  634. if (!*text) {
  635. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  636. ret = AVERROR(EINVAL);
  637. goto end;
  638. }
  639. if (argc == FF_ARRAY_ELEMS(argv))
  640. av_freep(&argv[--argc]); /* error will be caught later */
  641. if (*text == '}')
  642. break;
  643. text++;
  644. }
  645. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  646. goto end;
  647. ret = 0;
  648. *rtext = (char *)text + 1;
  649. end:
  650. for (i = 0; i < argc; i++)
  651. av_freep(&argv[i]);
  652. return ret;
  653. }
  654. static int expand_text(AVFilterContext *ctx)
  655. {
  656. DrawTextContext *dtext = ctx->priv;
  657. char *text = dtext->text;
  658. AVBPrint *bp = &dtext->expanded_text;
  659. int ret;
  660. av_bprint_clear(bp);
  661. while (*text) {
  662. if (*text == '\\' && text[1]) {
  663. av_bprint_chars(bp, text[1], 1);
  664. text += 2;
  665. } else if (*text == '%') {
  666. text++;
  667. if ((ret = expand_function(ctx, bp, &text)) < 0)
  668. return ret;
  669. } else {
  670. av_bprint_chars(bp, *text, 1);
  671. text++;
  672. }
  673. }
  674. if (!av_bprint_is_complete(bp))
  675. return AVERROR(ENOMEM);
  676. return 0;
  677. }
  678. static int draw_glyphs(DrawTextContext *dtext, AVFrame *frame,
  679. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  680. {
  681. char *text = dtext->expanded_text.str;
  682. uint32_t code = 0;
  683. int i, x1, y1;
  684. uint8_t *p;
  685. Glyph *glyph = NULL;
  686. for (i = 0, p = text; *p; i++) {
  687. Glyph dummy = { 0 };
  688. GET_UTF8(code, *p++, continue;);
  689. /* skip new line chars, just go to new line */
  690. if (code == '\n' || code == '\r' || code == '\t')
  691. continue;
  692. dummy.code = code;
  693. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  694. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  695. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  696. return AVERROR(EINVAL);
  697. x1 = dtext->positions[i].x+dtext->x+x;
  698. y1 = dtext->positions[i].y+dtext->y+y;
  699. ff_blend_mask(&dtext->dc, color,
  700. frame->data, frame->linesize, width, height,
  701. glyph->bitmap.buffer, glyph->bitmap.pitch,
  702. glyph->bitmap.width, glyph->bitmap.rows,
  703. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  704. 0, x1, y1);
  705. }
  706. return 0;
  707. }
  708. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  709. int width, int height)
  710. {
  711. DrawTextContext *dtext = ctx->priv;
  712. uint32_t code = 0, prev_code = 0;
  713. int x = 0, y = 0, i = 0, ret;
  714. int max_text_line_w = 0, len;
  715. int box_w, box_h;
  716. char *text = dtext->text;
  717. uint8_t *p;
  718. int y_min = 32000, y_max = -32000;
  719. int x_min = 32000, x_max = -32000;
  720. FT_Vector delta;
  721. Glyph *glyph = NULL, *prev_glyph = NULL;
  722. Glyph dummy = { 0 };
  723. time_t now = time(0);
  724. struct tm ltime;
  725. AVBPrint *bp = &dtext->expanded_text;
  726. av_bprint_clear(bp);
  727. if(dtext->basetime != AV_NOPTS_VALUE)
  728. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  729. switch (dtext->exp_mode) {
  730. case EXP_NONE:
  731. av_bprintf(bp, "%s", dtext->text);
  732. break;
  733. case EXP_NORMAL:
  734. if ((ret = expand_text(ctx)) < 0)
  735. return ret;
  736. break;
  737. case EXP_STRFTIME:
  738. localtime_r(&now, &ltime);
  739. av_bprint_strftime(bp, dtext->text, &ltime);
  740. break;
  741. }
  742. if (dtext->tc_opt_string) {
  743. char tcbuf[AV_TIMECODE_STR_SIZE];
  744. av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
  745. av_bprint_clear(bp);
  746. av_bprintf(bp, "%s%s", dtext->text, tcbuf);
  747. }
  748. if (!av_bprint_is_complete(bp))
  749. return AVERROR(ENOMEM);
  750. text = dtext->expanded_text.str;
  751. if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
  752. if (!(dtext->positions =
  753. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  754. return AVERROR(ENOMEM);
  755. dtext->nb_positions = len;
  756. }
  757. x = 0;
  758. y = 0;
  759. /* load and cache glyphs */
  760. for (i = 0, p = text; *p; i++) {
  761. GET_UTF8(code, *p++, continue;);
  762. /* get glyph */
  763. dummy.code = code;
  764. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  765. if (!glyph) {
  766. load_glyph(ctx, &glyph, code);
  767. }
  768. y_min = FFMIN(glyph->bbox.yMin, y_min);
  769. y_max = FFMAX(glyph->bbox.yMax, y_max);
  770. x_min = FFMIN(glyph->bbox.xMin, x_min);
  771. x_max = FFMAX(glyph->bbox.xMax, x_max);
  772. }
  773. dtext->max_glyph_h = y_max - y_min;
  774. dtext->max_glyph_w = x_max - x_min;
  775. /* compute and save position for each glyph */
  776. glyph = NULL;
  777. for (i = 0, p = text; *p; i++) {
  778. GET_UTF8(code, *p++, continue;);
  779. /* skip the \n in the sequence \r\n */
  780. if (prev_code == '\r' && code == '\n')
  781. continue;
  782. prev_code = code;
  783. if (is_newline(code)) {
  784. max_text_line_w = FFMAX(max_text_line_w, x);
  785. y += dtext->max_glyph_h;
  786. x = 0;
  787. continue;
  788. }
  789. /* get glyph */
  790. prev_glyph = glyph;
  791. dummy.code = code;
  792. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  793. /* kerning */
  794. if (dtext->use_kerning && prev_glyph && glyph->code) {
  795. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  796. ft_kerning_default, &delta);
  797. x += delta.x >> 6;
  798. }
  799. /* save position */
  800. dtext->positions[i].x = x + glyph->bitmap_left;
  801. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  802. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  803. else x += glyph->advance;
  804. }
  805. max_text_line_w = FFMAX(x, max_text_line_w);
  806. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  807. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  808. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  809. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  810. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  811. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  812. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  813. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  814. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  815. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  816. dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
  817. if(!dtext->draw)
  818. return 0;
  819. box_w = FFMIN(width - 1 , max_text_line_w);
  820. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  821. /* draw box */
  822. if (dtext->draw_box)
  823. ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
  824. frame->data, frame->linesize, width, height,
  825. dtext->x, dtext->y, box_w, box_h);
  826. if (dtext->shadowx || dtext->shadowy) {
  827. if ((ret = draw_glyphs(dtext, frame, width, height, dtext->shadowcolor.rgba,
  828. &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  829. return ret;
  830. }
  831. if ((ret = draw_glyphs(dtext, frame, width, height, dtext->fontcolor.rgba,
  832. &dtext->fontcolor, 0, 0)) < 0)
  833. return ret;
  834. return 0;
  835. }
  836. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  837. {
  838. AVFilterContext *ctx = inlink->dst;
  839. AVFilterLink *outlink = ctx->outputs[0];
  840. DrawTextContext *dtext = ctx->priv;
  841. int ret;
  842. if (dtext->reload)
  843. if ((ret = load_textfile(ctx)) < 0)
  844. return ret;
  845. dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  846. NAN : frame->pts * av_q2d(inlink->time_base);
  847. draw_text(ctx, frame, frame->width, frame->height);
  848. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  849. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  850. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  851. dtext->x, dtext->y);
  852. dtext->var_values[VAR_N] += 1.0;
  853. return ff_filter_frame(outlink, frame);
  854. }
  855. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  856. {
  857. .name = "default",
  858. .type = AVMEDIA_TYPE_VIDEO,
  859. .get_video_buffer = ff_null_get_video_buffer,
  860. .filter_frame = filter_frame,
  861. .config_props = config_input,
  862. .needs_writable = 1,
  863. },
  864. { NULL }
  865. };
  866. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  867. {
  868. .name = "default",
  869. .type = AVMEDIA_TYPE_VIDEO,
  870. },
  871. { NULL }
  872. };
  873. AVFilter avfilter_vf_drawtext = {
  874. .name = "drawtext",
  875. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  876. .priv_size = sizeof(DrawTextContext),
  877. .priv_class = &drawtext_class,
  878. .init = init,
  879. .uninit = uninit,
  880. .query_formats = query_formats,
  881. .inputs = avfilter_vf_drawtext_inputs,
  882. .outputs = avfilter_vf_drawtext_outputs,
  883. .process_command = command,
  884. };