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.

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