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.

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