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.

843 lines
31KB

  1. /*
  2. * Copyright (c) 2011 Stefano Sabatini
  3. * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
  4. * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * drawtext filter, based on the original vhook/drawtext.c
  25. * filter by Gustavo Sverzut Barbieri
  26. */
  27. #include <sys/time.h>
  28. #include <time.h>
  29. #include "config.h"
  30. #include "libavutil/avstring.h"
  31. #include "libavutil/bprint.h"
  32. #include "libavutil/common.h"
  33. #include "libavutil/file.h"
  34. #include "libavutil/eval.h"
  35. #include "libavutil/opt.h"
  36. #include "libavutil/random_seed.h"
  37. #include "libavutil/parseutils.h"
  38. #include "libavutil/timecode.h"
  39. #include "libavutil/tree.h"
  40. #include "libavutil/lfg.h"
  41. #include "avfilter.h"
  42. #include "drawutils.h"
  43. #include "formats.h"
  44. #include "internal.h"
  45. #include "video.h"
  46. #undef time
  47. #include <ft2build.h>
  48. #include <freetype/config/ftheader.h>
  49. #include FT_FREETYPE_H
  50. #include FT_GLYPH_H
  51. #if CONFIG_FONTCONFIG
  52. #include <fontconfig/fontconfig.h>
  53. #endif
  54. static const char *const var_names[] = {
  55. "dar",
  56. "hsub", "vsub",
  57. "line_h", "lh", ///< line height, same as max_glyph_h
  58. "main_h", "h", "H", ///< height of the input video
  59. "main_w", "w", "W", ///< width of the input video
  60. "max_glyph_a", "ascent", ///< max glyph ascent
  61. "max_glyph_d", "descent", ///< min glyph descent
  62. "max_glyph_h", ///< max glyph height
  63. "max_glyph_w", ///< max glyph width
  64. "n", ///< number of frame
  65. "sar",
  66. "t", ///< timestamp expressed in seconds
  67. "text_h", "th", ///< height of the rendered text
  68. "text_w", "tw", ///< width of the rendered text
  69. "x",
  70. "y",
  71. NULL
  72. };
  73. static const char *const fun2_names[] = {
  74. "rand"
  75. };
  76. static double drand(void *opaque, double min, double max)
  77. {
  78. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  79. }
  80. typedef double (*eval_func2)(void *, double a, double b);
  81. static const eval_func2 fun2[] = {
  82. drand,
  83. NULL
  84. };
  85. enum var_name {
  86. VAR_DAR,
  87. VAR_HSUB, VAR_VSUB,
  88. VAR_LINE_H, VAR_LH,
  89. VAR_MAIN_H, VAR_h, VAR_H,
  90. VAR_MAIN_W, VAR_w, VAR_W,
  91. VAR_MAX_GLYPH_A, VAR_ASCENT,
  92. VAR_MAX_GLYPH_D, VAR_DESCENT,
  93. VAR_MAX_GLYPH_H,
  94. VAR_MAX_GLYPH_W,
  95. VAR_N,
  96. VAR_SAR,
  97. VAR_T,
  98. VAR_TEXT_H, VAR_TH,
  99. VAR_TEXT_W, VAR_TW,
  100. VAR_X,
  101. VAR_Y,
  102. VAR_VARS_NB
  103. };
  104. typedef struct {
  105. const AVClass *class;
  106. int reinit; ///< tells if the filter is being reinited
  107. uint8_t *fontfile; ///< font to be used
  108. uint8_t *text; ///< text to be drawn
  109. AVBPrint expanded_text; ///< used to contain the expanded text
  110. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  111. FT_Vector *positions; ///< positions for each element in the text
  112. size_t nb_positions; ///< number of elements of positions array
  113. char *textfile; ///< file with text to be drawn
  114. int x; ///< x position to start drawing text
  115. int y; ///< y position to start drawing text
  116. int max_glyph_w; ///< max glyph width
  117. int max_glyph_h; ///< max glyph height
  118. int shadowx, shadowy;
  119. unsigned int fontsize; ///< font size to use
  120. char *fontcolor_string; ///< font color as string
  121. char *boxcolor_string; ///< box color as string
  122. char *shadowcolor_string; ///< shadow color as string
  123. short int draw_box; ///< draw box around text - true or false
  124. int use_kerning; ///< font kerning is used - true/false
  125. int tabsize; ///< tab size
  126. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  127. FFDrawContext dc;
  128. FFDrawColor fontcolor; ///< foreground color
  129. FFDrawColor shadowcolor; ///< shadow color
  130. FFDrawColor boxcolor; ///< background color
  131. FT_Library library; ///< freetype font library handle
  132. FT_Face face; ///< freetype font face handle
  133. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  134. char *x_expr; ///< expression for x position
  135. char *y_expr; ///< expression for y position
  136. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  137. int64_t basetime; ///< base pts time in the real world for display
  138. double var_values[VAR_VARS_NB];
  139. char *draw_expr; ///< expression for draw
  140. AVExpr *draw_pexpr; ///< parsed expression for draw
  141. int draw; ///< set to zero to prevent drawing
  142. AVLFG prng; ///< random
  143. char *tc_opt_string; ///< specified timecode option string
  144. AVRational tc_rate; ///< frame rate for timecode
  145. AVTimecode tc; ///< timecode context
  146. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  147. int frame_id;
  148. } DrawTextContext;
  149. #define OFFSET(x) offsetof(DrawTextContext, x)
  150. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  151. static const AVOption drawtext_options[]= {
  152. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  153. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  154. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  155. {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  156. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  157. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  158. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.i64=0}, 0, 1 , FLAGS},
  159. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  160. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  161. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  162. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  163. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  164. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  165. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  166. {"draw", "if false do not draw", OFFSET(draw_expr), AV_OPT_TYPE_STRING, {.str="1"}, CHAR_MIN, CHAR_MAX, FLAGS},
  167. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  168. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_INT, {.i64=0}, 0, 1, FLAGS},
  169. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  170. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  171. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  172. {"fix_bounds", "if true, check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_INT, {.i64=1}, 0, 1, FLAGS},
  173. /* FT_LOAD_* flags */
  174. {"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"},
  175. {"default", "set default", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  176. {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  177. {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  178. {"render", "set render", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_RENDER}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  179. {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  180. {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  181. {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  182. {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  183. {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  184. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  185. {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  186. {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  187. {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  188. {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  189. {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.i64=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, FLAGS, "ft_load_flags"},
  190. {NULL},
  191. };
  192. AVFILTER_DEFINE_CLASS(drawtext);
  193. #undef __FTERRORS_H__
  194. #define FT_ERROR_START_LIST {
  195. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  196. #define FT_ERROR_END_LIST { 0, NULL } };
  197. struct ft_error
  198. {
  199. int err;
  200. const char *err_msg;
  201. } static ft_errors[] =
  202. #include FT_ERRORS_H
  203. #define FT_ERRMSG(e) ft_errors[e].err_msg
  204. typedef struct {
  205. FT_Glyph *glyph;
  206. uint32_t code;
  207. FT_Bitmap bitmap; ///< array holding bitmaps of font
  208. FT_BBox bbox;
  209. int advance;
  210. int bitmap_left;
  211. int bitmap_top;
  212. } Glyph;
  213. static int glyph_cmp(void *key, const void *b)
  214. {
  215. const Glyph *a = key, *bb = b;
  216. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  217. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  218. }
  219. /**
  220. * Load glyphs corresponding to the UTF-32 codepoint code.
  221. */
  222. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  223. {
  224. DrawTextContext *dtext = ctx->priv;
  225. Glyph *glyph;
  226. struct AVTreeNode *node = NULL;
  227. int ret;
  228. /* load glyph into dtext->face->glyph */
  229. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  230. return AVERROR(EINVAL);
  231. /* save glyph */
  232. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  233. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  234. ret = AVERROR(ENOMEM);
  235. goto error;
  236. }
  237. glyph->code = code;
  238. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  239. ret = AVERROR(EINVAL);
  240. goto error;
  241. }
  242. glyph->bitmap = dtext->face->glyph->bitmap;
  243. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  244. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  245. glyph->advance = dtext->face->glyph->advance.x >> 6;
  246. /* measure text height to calculate text_height (or the maximum text height) */
  247. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  248. /* cache the newly created glyph */
  249. if (!(node = av_tree_node_alloc())) {
  250. ret = AVERROR(ENOMEM);
  251. goto error;
  252. }
  253. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  254. if (glyph_ptr)
  255. *glyph_ptr = glyph;
  256. return 0;
  257. error:
  258. if (glyph)
  259. av_freep(&glyph->glyph);
  260. av_freep(&glyph);
  261. av_freep(&node);
  262. return ret;
  263. }
  264. static int load_font_file(AVFilterContext *ctx, const char *path, int index,
  265. const char **error)
  266. {
  267. DrawTextContext *dtext = ctx->priv;
  268. int err;
  269. err = FT_New_Face(dtext->library, path, index, &dtext->face);
  270. if (err) {
  271. *error = FT_ERRMSG(err);
  272. return AVERROR(EINVAL);
  273. }
  274. return 0;
  275. }
  276. #if CONFIG_FONTCONFIG
  277. static int load_font_fontconfig(AVFilterContext *ctx, const char **error)
  278. {
  279. DrawTextContext *dtext = ctx->priv;
  280. FcConfig *fontconfig;
  281. FcPattern *pattern, *fpat;
  282. FcResult result = FcResultMatch;
  283. FcChar8 *filename;
  284. int err, index;
  285. double size;
  286. fontconfig = FcInitLoadConfigAndFonts();
  287. if (!fontconfig) {
  288. *error = "impossible to init fontconfig\n";
  289. return AVERROR(EINVAL);
  290. }
  291. pattern = FcNameParse(dtext->fontfile ? dtext->fontfile :
  292. (uint8_t *)(intptr_t)"default");
  293. if (!pattern) {
  294. *error = "could not parse fontconfig pattern";
  295. return AVERROR(EINVAL);
  296. }
  297. if (!FcConfigSubstitute(fontconfig, pattern, FcMatchPattern)) {
  298. *error = "could not substitue fontconfig options"; /* very unlikely */
  299. return AVERROR(EINVAL);
  300. }
  301. FcDefaultSubstitute(pattern);
  302. fpat = FcFontMatch(fontconfig, pattern, &result);
  303. if (!fpat || result != FcResultMatch) {
  304. *error = "impossible to find a matching font";
  305. return AVERROR(EINVAL);
  306. }
  307. if (FcPatternGetString (fpat, FC_FILE, 0, &filename) != FcResultMatch ||
  308. FcPatternGetInteger(fpat, FC_INDEX, 0, &index ) != FcResultMatch ||
  309. FcPatternGetDouble (fpat, FC_SIZE, 0, &size ) != FcResultMatch) {
  310. *error = "impossible to find font information";
  311. return AVERROR(EINVAL);
  312. }
  313. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  314. if (!dtext->fontsize)
  315. dtext->fontsize = size + 0.5;
  316. err = load_font_file(ctx, filename, index, error);
  317. if (err)
  318. return err;
  319. FcPatternDestroy(fpat);
  320. FcPatternDestroy(pattern);
  321. FcConfigDestroy(fontconfig);
  322. return 0;
  323. }
  324. #endif
  325. static int load_font(AVFilterContext *ctx)
  326. {
  327. DrawTextContext *dtext = ctx->priv;
  328. int err;
  329. const char *error = "unknown error\n";
  330. /* load the face, and set up the encoding, which is by default UTF-8 */
  331. err = load_font_file(ctx, dtext->fontfile, 0, &error);
  332. if (!err)
  333. return 0;
  334. #if CONFIG_FONTCONFIG
  335. err = load_font_fontconfig(ctx, &error);
  336. if (!err)
  337. return 0;
  338. #endif
  339. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  340. dtext->fontfile, error);
  341. return err;
  342. }
  343. static av_cold int init(AVFilterContext *ctx, const char *args)
  344. {
  345. int err;
  346. DrawTextContext *dtext = ctx->priv;
  347. Glyph *glyph;
  348. dtext->class = &drawtext_class;
  349. av_opt_set_defaults(dtext);
  350. if ((err = av_set_options_string(dtext, args, "=", ":")) < 0)
  351. return err;
  352. if (!dtext->fontfile && !CONFIG_FONTCONFIG) {
  353. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  354. return AVERROR(EINVAL);
  355. }
  356. if (dtext->textfile) {
  357. uint8_t *textbuf;
  358. size_t textbuf_size;
  359. if (dtext->text) {
  360. av_log(ctx, AV_LOG_ERROR,
  361. "Both text and text file provided. Please provide only one\n");
  362. return AVERROR(EINVAL);
  363. }
  364. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  365. av_log(ctx, AV_LOG_ERROR,
  366. "The text file '%s' could not be read or is empty\n",
  367. dtext->textfile);
  368. return err;
  369. }
  370. if (!(dtext->text = av_malloc(textbuf_size+1)))
  371. return AVERROR(ENOMEM);
  372. memcpy(dtext->text, textbuf, textbuf_size);
  373. dtext->text[textbuf_size] = 0;
  374. av_file_unmap(textbuf, textbuf_size);
  375. }
  376. if (dtext->tc_opt_string) {
  377. int ret = av_timecode_init_from_string(&dtext->tc, dtext->tc_rate,
  378. dtext->tc_opt_string, ctx);
  379. if (ret < 0)
  380. return ret;
  381. if (dtext->tc24hmax)
  382. dtext->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  383. if (!dtext->text)
  384. dtext->text = av_strdup("");
  385. }
  386. if (!dtext->text) {
  387. av_log(ctx, AV_LOG_ERROR,
  388. "Either text, a valid file or a timecode must be provided\n");
  389. return AVERROR(EINVAL);
  390. }
  391. if ((err = av_parse_color(dtext->fontcolor.rgba, dtext->fontcolor_string, -1, ctx))) {
  392. av_log(ctx, AV_LOG_ERROR,
  393. "Invalid font color '%s'\n", dtext->fontcolor_string);
  394. return err;
  395. }
  396. if ((err = av_parse_color(dtext->boxcolor.rgba, dtext->boxcolor_string, -1, ctx))) {
  397. av_log(ctx, AV_LOG_ERROR,
  398. "Invalid box color '%s'\n", dtext->boxcolor_string);
  399. return err;
  400. }
  401. if ((err = av_parse_color(dtext->shadowcolor.rgba, dtext->shadowcolor_string, -1, ctx))) {
  402. av_log(ctx, AV_LOG_ERROR,
  403. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  404. return err;
  405. }
  406. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  407. av_log(ctx, AV_LOG_ERROR,
  408. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  409. return AVERROR(EINVAL);
  410. }
  411. err = load_font(ctx);
  412. if (err)
  413. return err;
  414. if (!dtext->fontsize)
  415. dtext->fontsize = 16;
  416. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  417. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  418. dtext->fontsize, FT_ERRMSG(err));
  419. return AVERROR(EINVAL);
  420. }
  421. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  422. /* load the fallback glyph with code 0 */
  423. load_glyph(ctx, NULL, 0);
  424. /* set the tabsize in pixels */
  425. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  426. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  427. return err;
  428. }
  429. dtext->tabsize *= glyph->advance;
  430. av_bprint_init(&dtext->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  431. return 0;
  432. }
  433. static int query_formats(AVFilterContext *ctx)
  434. {
  435. ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  436. return 0;
  437. }
  438. static int glyph_enu_free(void *opaque, void *elem)
  439. {
  440. Glyph *glyph = elem;
  441. FT_Done_Glyph(*glyph->glyph);
  442. av_freep(&glyph->glyph);
  443. av_free(elem);
  444. return 0;
  445. }
  446. static av_cold void uninit(AVFilterContext *ctx)
  447. {
  448. DrawTextContext *dtext = ctx->priv;
  449. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  450. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  451. av_expr_free(dtext->draw_pexpr); dtext->draw_pexpr = NULL;
  452. av_opt_free(dtext);
  453. av_freep(&dtext->positions);
  454. dtext->nb_positions = 0;
  455. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  456. av_tree_destroy(dtext->glyphs);
  457. dtext->glyphs = NULL;
  458. FT_Done_Face(dtext->face);
  459. FT_Done_FreeType(dtext->library);
  460. av_bprint_finalize(&dtext->expanded_text, NULL);
  461. }
  462. static inline int is_newline(uint32_t c)
  463. {
  464. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  465. }
  466. static int config_input(AVFilterLink *inlink)
  467. {
  468. AVFilterContext *ctx = inlink->dst;
  469. DrawTextContext *dtext = ctx->priv;
  470. int ret;
  471. ff_draw_init(&dtext->dc, inlink->format, 0);
  472. ff_draw_color(&dtext->dc, &dtext->fontcolor, dtext->fontcolor.rgba);
  473. ff_draw_color(&dtext->dc, &dtext->shadowcolor, dtext->shadowcolor.rgba);
  474. ff_draw_color(&dtext->dc, &dtext->boxcolor, dtext->boxcolor.rgba);
  475. dtext->var_values[VAR_w] = dtext->var_values[VAR_W] = dtext->var_values[VAR_MAIN_W] = inlink->w;
  476. dtext->var_values[VAR_h] = dtext->var_values[VAR_H] = dtext->var_values[VAR_MAIN_H] = inlink->h;
  477. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  478. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  479. dtext->var_values[VAR_HSUB] = 1 << dtext->dc.hsub_max;
  480. dtext->var_values[VAR_VSUB] = 1 << dtext->dc.vsub_max;
  481. dtext->var_values[VAR_X] = NAN;
  482. dtext->var_values[VAR_Y] = NAN;
  483. if (!dtext->reinit)
  484. dtext->var_values[VAR_N] = 0;
  485. dtext->var_values[VAR_T] = NAN;
  486. av_lfg_init(&dtext->prng, av_get_random_seed());
  487. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  488. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  489. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  490. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  491. (ret = av_expr_parse(&dtext->draw_pexpr, dtext->draw_expr, var_names,
  492. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  493. return AVERROR(EINVAL);
  494. return 0;
  495. }
  496. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  497. {
  498. DrawTextContext *dtext = ctx->priv;
  499. if (!strcmp(cmd, "reinit")) {
  500. int ret;
  501. uninit(ctx);
  502. dtext->reinit = 1;
  503. if ((ret = init(ctx, arg)) < 0)
  504. return ret;
  505. return config_input(ctx->inputs[0]);
  506. }
  507. return AVERROR(ENOSYS);
  508. }
  509. static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
  510. int width, int height, const uint8_t rgbcolor[4], FFDrawColor *color, int x, int y)
  511. {
  512. char *text = dtext->expanded_text.str;
  513. uint32_t code = 0;
  514. int i, x1, y1;
  515. uint8_t *p;
  516. Glyph *glyph = NULL;
  517. for (i = 0, p = text; *p; i++) {
  518. Glyph dummy = { 0 };
  519. GET_UTF8(code, *p++, continue;);
  520. /* skip new line chars, just go to new line */
  521. if (code == '\n' || code == '\r' || code == '\t')
  522. continue;
  523. dummy.code = code;
  524. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  525. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  526. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  527. return AVERROR(EINVAL);
  528. x1 = dtext->positions[i].x+dtext->x+x;
  529. y1 = dtext->positions[i].y+dtext->y+y;
  530. ff_blend_mask(&dtext->dc, color,
  531. picref->data, picref->linesize, width, height,
  532. glyph->bitmap.buffer, glyph->bitmap.pitch,
  533. glyph->bitmap.width, glyph->bitmap.rows,
  534. glyph->bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  535. 0, x1, y1);
  536. }
  537. return 0;
  538. }
  539. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  540. int width, int height)
  541. {
  542. DrawTextContext *dtext = ctx->priv;
  543. uint32_t code = 0, prev_code = 0;
  544. int x = 0, y = 0, i = 0, ret;
  545. int max_text_line_w = 0, len;
  546. int box_w, box_h;
  547. char *text = dtext->text;
  548. uint8_t *p;
  549. int y_min = 32000, y_max = -32000;
  550. int x_min = 32000, x_max = -32000;
  551. FT_Vector delta;
  552. Glyph *glyph = NULL, *prev_glyph = NULL;
  553. Glyph dummy = { 0 };
  554. time_t now = time(0);
  555. struct tm ltime;
  556. AVBPrint *bp = &dtext->expanded_text;
  557. av_bprint_clear(bp);
  558. if(dtext->basetime != AV_NOPTS_VALUE)
  559. now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  560. #if HAVE_LOCALTIME_R
  561. localtime_r(&now, &ltime);
  562. #else
  563. if(strchr(dtext->text, '%'))
  564. ltime= *localtime(&now);
  565. #endif
  566. av_bprint_strftime(bp, dtext->text, &ltime);
  567. if (dtext->tc_opt_string) {
  568. char tcbuf[AV_TIMECODE_STR_SIZE];
  569. av_timecode_make_string(&dtext->tc, tcbuf, dtext->frame_id++);
  570. av_bprint_clear(bp);
  571. av_bprintf(bp, "%s%s", dtext->text, tcbuf);
  572. }
  573. if (!av_bprint_is_complete(bp))
  574. return AVERROR(ENOMEM);
  575. text = dtext->expanded_text.str;
  576. if ((len = dtext->expanded_text.len) > dtext->nb_positions) {
  577. if (!(dtext->positions =
  578. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  579. return AVERROR(ENOMEM);
  580. dtext->nb_positions = len;
  581. }
  582. x = 0;
  583. y = 0;
  584. /* load and cache glyphs */
  585. for (i = 0, p = text; *p; i++) {
  586. GET_UTF8(code, *p++, continue;);
  587. /* get glyph */
  588. dummy.code = code;
  589. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  590. if (!glyph) {
  591. load_glyph(ctx, &glyph, code);
  592. }
  593. y_min = FFMIN(glyph->bbox.yMin, y_min);
  594. y_max = FFMAX(glyph->bbox.yMax, y_max);
  595. x_min = FFMIN(glyph->bbox.xMin, x_min);
  596. x_max = FFMAX(glyph->bbox.xMax, x_max);
  597. }
  598. dtext->max_glyph_h = y_max - y_min;
  599. dtext->max_glyph_w = x_max - x_min;
  600. /* compute and save position for each glyph */
  601. glyph = NULL;
  602. for (i = 0, p = text; *p; i++) {
  603. GET_UTF8(code, *p++, continue;);
  604. /* skip the \n in the sequence \r\n */
  605. if (prev_code == '\r' && code == '\n')
  606. continue;
  607. prev_code = code;
  608. if (is_newline(code)) {
  609. max_text_line_w = FFMAX(max_text_line_w, x);
  610. y += dtext->max_glyph_h;
  611. x = 0;
  612. continue;
  613. }
  614. /* get glyph */
  615. prev_glyph = glyph;
  616. dummy.code = code;
  617. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  618. /* kerning */
  619. if (dtext->use_kerning && prev_glyph && glyph->code) {
  620. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  621. ft_kerning_default, &delta);
  622. x += delta.x >> 6;
  623. }
  624. /* save position */
  625. dtext->positions[i].x = x + glyph->bitmap_left;
  626. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  627. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  628. else x += glyph->advance;
  629. }
  630. max_text_line_w = FFMAX(x, max_text_line_w);
  631. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  632. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  633. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  634. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  635. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  636. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  637. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  638. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  639. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  640. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  641. dtext->draw = av_expr_eval(dtext->draw_pexpr, dtext->var_values, &dtext->prng);
  642. if(!dtext->draw)
  643. return 0;
  644. box_w = FFMIN(width - 1 , max_text_line_w);
  645. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  646. /* draw box */
  647. if (dtext->draw_box)
  648. ff_blend_rectangle(&dtext->dc, &dtext->boxcolor,
  649. picref->data, picref->linesize, width, height,
  650. dtext->x, dtext->y, box_w, box_h);
  651. if (dtext->shadowx || dtext->shadowy) {
  652. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor.rgba,
  653. &dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  654. return ret;
  655. }
  656. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor.rgba,
  657. &dtext->fontcolor, 0, 0)) < 0)
  658. return ret;
  659. return 0;
  660. }
  661. static int null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir)
  662. {
  663. return 0;
  664. }
  665. static int end_frame(AVFilterLink *inlink)
  666. {
  667. AVFilterContext *ctx = inlink->dst;
  668. AVFilterLink *outlink = ctx->outputs[0];
  669. DrawTextContext *dtext = ctx->priv;
  670. AVFilterBufferRef *picref = inlink->cur_buf;
  671. int ret;
  672. dtext->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
  673. NAN : picref->pts * av_q2d(inlink->time_base);
  674. draw_text(ctx, picref, picref->video->w, picref->video->h);
  675. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  676. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  677. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  678. dtext->x, dtext->y);
  679. dtext->var_values[VAR_N] += 1.0;
  680. if ((ret = ff_draw_slice(outlink, 0, picref->video->h, 1)) < 0 ||
  681. (ret = ff_end_frame(outlink)) < 0)
  682. return ret;
  683. return 0;
  684. }
  685. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  686. {
  687. .name = "default",
  688. .type = AVMEDIA_TYPE_VIDEO,
  689. .get_video_buffer = ff_null_get_video_buffer,
  690. .start_frame = ff_null_start_frame,
  691. .draw_slice = null_draw_slice,
  692. .end_frame = end_frame,
  693. .config_props = config_input,
  694. .min_perms = AV_PERM_WRITE |
  695. AV_PERM_READ,
  696. },
  697. { NULL }
  698. };
  699. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  700. {
  701. .name = "default",
  702. .type = AVMEDIA_TYPE_VIDEO,
  703. },
  704. { NULL }
  705. };
  706. AVFilter avfilter_vf_drawtext = {
  707. .name = "drawtext",
  708. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  709. .priv_size = sizeof(DrawTextContext),
  710. .init = init,
  711. .uninit = uninit,
  712. .query_formats = query_formats,
  713. .inputs = avfilter_vf_drawtext_inputs,
  714. .outputs = avfilter_vf_drawtext_outputs,
  715. .process_command = command,
  716. .priv_class = &drawtext_class,
  717. };