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.

1076 lines
37KB

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