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.

1032 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. #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. "pict_type",
  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_PICT_TYPE,
  103. VAR_VARS_NB
  104. };
  105. enum expansion_mode {
  106. EXP_NONE,
  107. EXP_NORMAL,
  108. EXP_STRFTIME,
  109. };
  110. typedef struct {
  111. const AVClass *class;
  112. enum expansion_mode exp_mode; ///< expansion mode to use for the text
  113. int reinit; ///< tells if the filter is being reinited
  114. uint8_t *fontfile; ///< font to be used
  115. uint8_t *text; ///< text to be drawn
  116. AVBPrint expanded_text; ///< used to contain the expanded text
  117. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  118. FT_Vector *positions; ///< positions for each element in the text
  119. size_t nb_positions; ///< number of elements of positions array
  120. char *textfile; ///< file with text to be drawn
  121. int x; ///< x position to start drawing text
  122. int y; ///< y position to start drawing text
  123. int max_glyph_w; ///< max glyph width
  124. int max_glyph_h; ///< max glyph height
  125. int shadowx, shadowy;
  126. unsigned int fontsize; ///< font size to use
  127. short int draw_box; ///< draw box around text - true or false
  128. int use_kerning; ///< font kerning is used - true/false
  129. int tabsize; ///< tab size
  130. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  131. FFDrawContext dc;
  132. FFDrawColor fontcolor; ///< foreground color
  133. FFDrawColor shadowcolor; ///< shadow color
  134. FFDrawColor boxcolor; ///< background color
  135. FT_Library library; ///< freetype font library handle
  136. FT_Face face; ///< freetype font face handle
  137. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  138. char *x_expr; ///< expression for x position
  139. char *y_expr; ///< expression for y position
  140. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  141. int64_t basetime; ///< base pts time in the real world for display
  142. double var_values[VAR_VARS_NB];
  143. char *draw_expr; ///< expression for draw
  144. AVExpr *draw_pexpr; ///< parsed expression for draw
  145. int draw; ///< set to zero to prevent drawing
  146. AVLFG prng; ///< random
  147. char *tc_opt_string; ///< specified timecode option string
  148. AVRational tc_rate; ///< frame rate for timecode
  149. AVTimecode tc; ///< timecode context
  150. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  151. int reload; ///< reload text file for each frame
  152. int start_number; ///< starting frame number for n/frame_num var
  153. } DrawTextContext;
  154. #define OFFSET(x) offsetof(DrawTextContext, x)
  155. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  156. static const AVOption drawtext_options[]= {
  157. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  158. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  159. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  160. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  161. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  162. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  163. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  164. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  165. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  166. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  167. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  168. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  169. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  170. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  171. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
  172. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  173. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  174. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  175. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  176. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  177. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  178. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  179. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  180. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  181. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, 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. {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, 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 *s = ctx->priv;
  236. Glyph *glyph;
  237. struct AVTreeNode *node = NULL;
  238. int ret;
  239. /* load glyph into s->face->glyph */
  240. if (FT_Load_Char(s->face, code, s->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(s->face->glyph, glyph->glyph)) {
  250. ret = AVERROR(EINVAL);
  251. goto error;
  252. }
  253. glyph->bitmap = s->face->glyph->bitmap;
  254. glyph->bitmap_left = s->face->glyph->bitmap_left;
  255. glyph->bitmap_top = s->face->glyph->bitmap_top;
  256. glyph->advance = s->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(&s->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 *s = ctx->priv;
  279. int err;
  280. err = FT_New_Face(s->library, path, index, &s->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 *s = 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(s->fontfile ? s->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 (!s->fontsize)
  326. s->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 *s = 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, s->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. s->fontfile, error);
  352. return err;
  353. }
  354. static int load_textfile(AVFilterContext *ctx)
  355. {
  356. DrawTextContext *s = ctx->priv;
  357. int err;
  358. uint8_t *textbuf;
  359. size_t textbuf_size;
  360. if ((err = av_file_map(s->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. s->textfile);
  364. return err;
  365. }
  366. if (!(s->text = av_realloc(s->text, textbuf_size + 1)))
  367. return AVERROR(ENOMEM);
  368. memcpy(s->text, textbuf, textbuf_size);
  369. s->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 *s = ctx->priv;
  377. Glyph *glyph;
  378. if (!s->fontfile && !CONFIG_FONTCONFIG) {
  379. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  380. return AVERROR(EINVAL);
  381. }
  382. if (s->textfile) {
  383. if (s->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 (s->reload && !s->textfile)
  392. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  393. if (s->tc_opt_string) {
  394. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  395. s->tc_opt_string, ctx);
  396. if (ret < 0)
  397. return ret;
  398. if (s->tc24hmax)
  399. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  400. if (!s->text)
  401. s->text = av_strdup("");
  402. }
  403. if (!s->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 = FT_Init_FreeType(&(s->library)))) {
  409. av_log(ctx, AV_LOG_ERROR,
  410. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  411. return AVERROR(EINVAL);
  412. }
  413. err = load_font(ctx);
  414. if (err)
  415. return err;
  416. if (!s->fontsize)
  417. s->fontsize = 16;
  418. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  419. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  420. s->fontsize, FT_ERRMSG(err));
  421. return AVERROR(EINVAL);
  422. }
  423. s->use_kerning = FT_HAS_KERNING(s->face);
  424. /* load the fallback glyph with code 0 */
  425. load_glyph(ctx, NULL, 0);
  426. /* set the tabsize in pixels */
  427. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  428. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  429. return err;
  430. }
  431. s->tabsize *= glyph->advance;
  432. if (s->exp_mode == EXP_STRFTIME &&
  433. (strchr(s->text, '%') || strchr(s->text, '\\')))
  434. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  435. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  436. return 0;
  437. }
  438. static int query_formats(AVFilterContext *ctx)
  439. {
  440. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  441. return 0;
  442. }
  443. static int glyph_enu_free(void *opaque, void *elem)
  444. {
  445. Glyph *glyph = elem;
  446. FT_Done_Glyph(*glyph->glyph);
  447. av_freep(&glyph->glyph);
  448. av_free(elem);
  449. return 0;
  450. }
  451. static av_cold void uninit(AVFilterContext *ctx)
  452. {
  453. DrawTextContext *s = ctx->priv;
  454. av_expr_free(s->x_pexpr);
  455. av_expr_free(s->y_pexpr);
  456. av_expr_free(s->draw_pexpr);
  457. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  458. av_freep(&s->positions);
  459. s->nb_positions = 0;
  460. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  461. av_tree_destroy(s->glyphs);
  462. s->glyphs = NULL;
  463. FT_Done_Face(s->face);
  464. FT_Done_FreeType(s->library);
  465. av_bprint_finalize(&s->expanded_text, NULL);
  466. }
  467. static inline int is_newline(uint32_t c)
  468. {
  469. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  470. }
  471. static int config_input(AVFilterLink *inlink)
  472. {
  473. AVFilterContext *ctx = inlink->dst;
  474. DrawTextContext *s = ctx->priv;
  475. int ret;
  476. ff_draw_init(&s->dc, inlink->format, 0);
  477. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  478. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  479. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  480. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  481. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  482. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  483. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  484. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  485. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  486. s->var_values[VAR_X] = NAN;
  487. s->var_values[VAR_Y] = NAN;
  488. s->var_values[VAR_T] = NAN;
  489. av_lfg_init(&s->prng, av_get_random_seed());
  490. av_expr_free(s->x_pexpr);
  491. av_expr_free(s->y_pexpr);
  492. av_expr_free(s->draw_pexpr);
  493. s->x_pexpr = s->y_pexpr = s->draw_pexpr = NULL;
  494. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  495. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  496. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  497. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  498. (ret = av_expr_parse(&s->draw_pexpr, s->draw_expr, var_names,
  499. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  500. return AVERROR(EINVAL);
  501. return 0;
  502. }
  503. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  504. {
  505. DrawTextContext *s = ctx->priv;
  506. if (!strcmp(cmd, "reinit")) {
  507. int ret;
  508. uninit(ctx);
  509. s->reinit = 1;
  510. if ((ret = init(ctx)) < 0)
  511. return ret;
  512. return config_input(ctx->inputs[0]);
  513. }
  514. return AVERROR(ENOSYS);
  515. }
  516. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  517. char *fct, unsigned argc, char **argv, int tag)
  518. {
  519. DrawTextContext *s = ctx->priv;
  520. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  521. return 0;
  522. }
  523. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  524. char *fct, unsigned argc, char **argv, int tag)
  525. {
  526. DrawTextContext *s = ctx->priv;
  527. av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
  528. return 0;
  529. }
  530. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  531. char *fct, unsigned argc, char **argv, int tag)
  532. {
  533. DrawTextContext *s = ctx->priv;
  534. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  535. return 0;
  536. }
  537. #if !HAVE_LOCALTIME_R
  538. static void localtime_r(const time_t *t, struct tm *tm)
  539. {
  540. *tm = *localtime(t);
  541. }
  542. #endif
  543. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  544. char *fct, unsigned argc, char **argv, int tag)
  545. {
  546. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  547. time_t now;
  548. struct tm tm;
  549. time(&now);
  550. if (tag == 'L')
  551. localtime_r(&now, &tm);
  552. else
  553. tm = *gmtime(&now);
  554. av_bprint_strftime(bp, fmt, &tm);
  555. return 0;
  556. }
  557. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  558. char *fct, unsigned argc, char **argv, int tag)
  559. {
  560. DrawTextContext *s = ctx->priv;
  561. double res;
  562. int ret;
  563. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  564. NULL, NULL, fun2_names, fun2,
  565. &s->prng, 0, ctx);
  566. if (ret < 0)
  567. av_log(ctx, AV_LOG_ERROR,
  568. "Expression '%s' for the expr text expansion function is not valid\n",
  569. argv[0]);
  570. else
  571. av_bprintf(bp, "%f", res);
  572. return ret;
  573. }
  574. static const struct drawtext_function {
  575. const char *name;
  576. unsigned argc_min, argc_max;
  577. int tag; /**< opaque argument to func */
  578. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  579. } functions[] = {
  580. { "expr", 1, 1, 0, func_eval_expr },
  581. { "e", 1, 1, 0, func_eval_expr },
  582. { "pict_type", 0, 0, 0, func_pict_type },
  583. { "pts", 0, 0, 0, func_pts },
  584. { "gmtime", 0, 1, 'G', func_strftime },
  585. { "localtime", 0, 1, 'L', func_strftime },
  586. { "frame_num", 0, 0, 0, func_frame_num },
  587. { "n", 0, 0, 0, func_frame_num },
  588. };
  589. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  590. unsigned argc, char **argv)
  591. {
  592. unsigned i;
  593. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  594. if (strcmp(fct, functions[i].name))
  595. continue;
  596. if (argc < functions[i].argc_min) {
  597. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  598. fct, functions[i].argc_min);
  599. return AVERROR(EINVAL);
  600. }
  601. if (argc > functions[i].argc_max) {
  602. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  603. fct, functions[i].argc_max);
  604. return AVERROR(EINVAL);
  605. }
  606. break;
  607. }
  608. if (i >= FF_ARRAY_ELEMS(functions)) {
  609. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  610. return AVERROR(EINVAL);
  611. }
  612. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  613. }
  614. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  615. {
  616. const char *text = *rtext;
  617. char *argv[16] = { NULL };
  618. unsigned argc = 0, i;
  619. int ret;
  620. if (*text != '{') {
  621. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  622. return AVERROR(EINVAL);
  623. }
  624. text++;
  625. while (1) {
  626. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  627. ret = AVERROR(ENOMEM);
  628. goto end;
  629. }
  630. if (!*text) {
  631. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  632. ret = AVERROR(EINVAL);
  633. goto end;
  634. }
  635. if (argc == FF_ARRAY_ELEMS(argv))
  636. av_freep(&argv[--argc]); /* error will be caught later */
  637. if (*text == '}')
  638. break;
  639. text++;
  640. }
  641. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  642. goto end;
  643. ret = 0;
  644. *rtext = (char *)text + 1;
  645. end:
  646. for (i = 0; i < argc; i++)
  647. av_freep(&argv[i]);
  648. return ret;
  649. }
  650. static int expand_text(AVFilterContext *ctx)
  651. {
  652. DrawTextContext *s = ctx->priv;
  653. char *text = s->text;
  654. AVBPrint *bp = &s->expanded_text;
  655. int ret;
  656. av_bprint_clear(bp);
  657. while (*text) {
  658. if (*text == '\\' && text[1]) {
  659. av_bprint_chars(bp, text[1], 1);
  660. text += 2;
  661. } else if (*text == '%') {
  662. text++;
  663. if ((ret = expand_function(ctx, bp, &text)) < 0)
  664. return ret;
  665. } else {
  666. av_bprint_chars(bp, *text, 1);
  667. text++;
  668. }
  669. }
  670. if (!av_bprint_is_complete(bp))
  671. return AVERROR(ENOMEM);
  672. return 0;
  673. }
  674. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  675. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  676. {
  677. char *text = s->expanded_text.str;
  678. uint32_t code = 0;
  679. int i, x1, y1;
  680. uint8_t *p;
  681. Glyph *glyph = NULL;
  682. for (i = 0, p = text; *p; i++) {
  683. Glyph dummy = { 0 };
  684. GET_UTF8(code, *p++, continue;);
  685. /* skip new line chars, just go to new line */
  686. if (code == '\n' || code == '\r' || code == '\t')
  687. continue;
  688. dummy.code = code;
  689. glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
  690. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  691. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  692. return AVERROR(EINVAL);
  693. x1 = s->positions[i].x+s->x+x;
  694. y1 = s->positions[i].y+s->y+y;
  695. ff_blend_mask(&s->dc, color,
  696. frame->data, frame->linesize, width, height,
  697. glyph->bitmap.buffer, glyph->bitmap.pitch,
  698. glyph->bitmap.width, glyph->bitmap.rows,
  699. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  700. 0, x1, y1);
  701. }
  702. return 0;
  703. }
  704. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  705. int width, int height)
  706. {
  707. DrawTextContext *s = ctx->priv;
  708. AVFilterLink *inlink = ctx->inputs[0];
  709. uint32_t code = 0, prev_code = 0;
  710. int x = 0, y = 0, i = 0, ret;
  711. int max_text_line_w = 0, len;
  712. int box_w, box_h;
  713. char *text = s->text;
  714. uint8_t *p;
  715. int y_min = 32000, y_max = -32000;
  716. int x_min = 32000, x_max = -32000;
  717. FT_Vector delta;
  718. Glyph *glyph = NULL, *prev_glyph = NULL;
  719. Glyph dummy = { 0 };
  720. time_t now = time(0);
  721. struct tm ltime;
  722. AVBPrint *bp = &s->expanded_text;
  723. av_bprint_clear(bp);
  724. if(s->basetime != AV_NOPTS_VALUE)
  725. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  726. switch (s->exp_mode) {
  727. case EXP_NONE:
  728. av_bprintf(bp, "%s", s->text);
  729. break;
  730. case EXP_NORMAL:
  731. if ((ret = expand_text(ctx)) < 0)
  732. return ret;
  733. break;
  734. case EXP_STRFTIME:
  735. localtime_r(&now, &ltime);
  736. av_bprint_strftime(bp, s->text, &ltime);
  737. break;
  738. }
  739. if (s->tc_opt_string) {
  740. char tcbuf[AV_TIMECODE_STR_SIZE];
  741. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
  742. av_bprint_clear(bp);
  743. av_bprintf(bp, "%s%s", s->text, tcbuf);
  744. }
  745. if (!av_bprint_is_complete(bp))
  746. return AVERROR(ENOMEM);
  747. text = s->expanded_text.str;
  748. if ((len = s->expanded_text.len) > s->nb_positions) {
  749. if (!(s->positions =
  750. av_realloc(s->positions, len*sizeof(*s->positions))))
  751. return AVERROR(ENOMEM);
  752. s->nb_positions = len;
  753. }
  754. x = 0;
  755. y = 0;
  756. /* load and cache glyphs */
  757. for (i = 0, p = text; *p; i++) {
  758. GET_UTF8(code, *p++, continue;);
  759. /* get glyph */
  760. dummy.code = code;
  761. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  762. if (!glyph) {
  763. load_glyph(ctx, &glyph, code);
  764. }
  765. y_min = FFMIN(glyph->bbox.yMin, y_min);
  766. y_max = FFMAX(glyph->bbox.yMax, y_max);
  767. x_min = FFMIN(glyph->bbox.xMin, x_min);
  768. x_max = FFMAX(glyph->bbox.xMax, x_max);
  769. }
  770. s->max_glyph_h = y_max - y_min;
  771. s->max_glyph_w = x_max - x_min;
  772. /* compute and save position for each glyph */
  773. glyph = NULL;
  774. for (i = 0, p = text; *p; i++) {
  775. GET_UTF8(code, *p++, continue;);
  776. /* skip the \n in the sequence \r\n */
  777. if (prev_code == '\r' && code == '\n')
  778. continue;
  779. prev_code = code;
  780. if (is_newline(code)) {
  781. max_text_line_w = FFMAX(max_text_line_w, x);
  782. y += s->max_glyph_h;
  783. x = 0;
  784. continue;
  785. }
  786. /* get glyph */
  787. prev_glyph = glyph;
  788. dummy.code = code;
  789. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  790. /* kerning */
  791. if (s->use_kerning && prev_glyph && glyph->code) {
  792. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  793. ft_kerning_default, &delta);
  794. x += delta.x >> 6;
  795. }
  796. /* save position */
  797. s->positions[i].x = x + glyph->bitmap_left;
  798. s->positions[i].y = y - glyph->bitmap_top + y_max;
  799. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  800. else x += glyph->advance;
  801. }
  802. max_text_line_w = FFMAX(x, max_text_line_w);
  803. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  804. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  805. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  806. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  807. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  808. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  809. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  810. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  811. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  812. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  813. s->draw = av_expr_eval(s->draw_pexpr, s->var_values, &s->prng);
  814. if(!s->draw)
  815. return 0;
  816. box_w = FFMIN(width - 1 , max_text_line_w);
  817. box_h = FFMIN(height - 1, y + s->max_glyph_h);
  818. /* draw box */
  819. if (s->draw_box)
  820. ff_blend_rectangle(&s->dc, &s->boxcolor,
  821. frame->data, frame->linesize, width, height,
  822. s->x, s->y, box_w, box_h);
  823. if (s->shadowx || s->shadowy) {
  824. if ((ret = draw_glyphs(s, frame, width, height, s->shadowcolor.rgba,
  825. &s->shadowcolor, s->shadowx, s->shadowy)) < 0)
  826. return ret;
  827. }
  828. if ((ret = draw_glyphs(s, frame, width, height, s->fontcolor.rgba,
  829. &s->fontcolor, 0, 0)) < 0)
  830. return ret;
  831. return 0;
  832. }
  833. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  834. {
  835. AVFilterContext *ctx = inlink->dst;
  836. AVFilterLink *outlink = ctx->outputs[0];
  837. DrawTextContext *s = ctx->priv;
  838. int ret;
  839. if (s->reload)
  840. if ((ret = load_textfile(ctx)) < 0)
  841. return ret;
  842. s->var_values[VAR_N] = inlink->frame_count+s->start_number;
  843. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  844. NAN : frame->pts * av_q2d(inlink->time_base);
  845. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  846. draw_text(ctx, frame, frame->width, frame->height);
  847. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  848. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  849. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  850. s->x, s->y);
  851. return ff_filter_frame(outlink, frame);
  852. }
  853. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  854. {
  855. .name = "default",
  856. .type = AVMEDIA_TYPE_VIDEO,
  857. .get_video_buffer = ff_null_get_video_buffer,
  858. .filter_frame = filter_frame,
  859. .config_props = config_input,
  860. .needs_writable = 1,
  861. },
  862. { NULL }
  863. };
  864. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  865. {
  866. .name = "default",
  867. .type = AVMEDIA_TYPE_VIDEO,
  868. },
  869. { NULL }
  870. };
  871. AVFilter avfilter_vf_drawtext = {
  872. .name = "drawtext",
  873. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  874. .priv_size = sizeof(DrawTextContext),
  875. .priv_class = &drawtext_class,
  876. .init = init,
  877. .uninit = uninit,
  878. .query_formats = query_formats,
  879. .inputs = avfilter_vf_drawtext_inputs,
  880. .outputs = avfilter_vf_drawtext_outputs,
  881. .process_command = command,
  882. };