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.

973 lines
33KB

  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 Libav.
  7. *
  8. * Libav 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. * Libav 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 Libav; 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 "config.h"
  28. #include <sys/types.h>
  29. #include <sys/time.h>
  30. #include <sys/stat.h>
  31. #include <time.h>
  32. #include <unistd.h>
  33. #if CONFIG_LIBFONTCONFIG
  34. #include <fontconfig/fontconfig.h>
  35. #endif
  36. #include "libavutil/colorspace.h"
  37. #include "libavutil/common.h"
  38. #include "libavutil/file.h"
  39. #include "libavutil/eval.h"
  40. #include "libavutil/opt.h"
  41. #include "libavutil/mathematics.h"
  42. #include "libavutil/random_seed.h"
  43. #include "libavutil/parseutils.h"
  44. #include "libavutil/pixdesc.h"
  45. #include "libavutil/tree.h"
  46. #include "libavutil/lfg.h"
  47. #include "avfilter.h"
  48. #include "drawutils.h"
  49. #include "formats.h"
  50. #include "internal.h"
  51. #include "video.h"
  52. #include <ft2build.h>
  53. #include FT_FREETYPE_H
  54. #include FT_GLYPH_H
  55. static const char *const var_names[] = {
  56. "E",
  57. "PHI",
  58. "PI",
  59. "main_w", "W", ///< width of the main video
  60. "main_h", "H", ///< height of the main video
  61. "text_w", "w", ///< width of the overlay text
  62. "text_h", "h", ///< height of the overlay text
  63. "x",
  64. "y",
  65. "n", ///< number of processed frames
  66. "t", ///< timestamp expressed in seconds
  67. NULL
  68. };
  69. static const char *const fun2_names[] = {
  70. "rand"
  71. };
  72. static double drand(void *opaque, double min, double max)
  73. {
  74. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  75. }
  76. typedef double (*eval_func2)(void *, double a, double b);
  77. static const eval_func2 fun2[] = {
  78. drand,
  79. NULL
  80. };
  81. enum var_name {
  82. VAR_E,
  83. VAR_PHI,
  84. VAR_PI,
  85. VAR_MAIN_W, VAR_MW,
  86. VAR_MAIN_H, VAR_MH,
  87. VAR_TEXT_W, VAR_TW,
  88. VAR_TEXT_H, VAR_TH,
  89. VAR_X,
  90. VAR_Y,
  91. VAR_N,
  92. VAR_T,
  93. VAR_VARS_NB
  94. };
  95. typedef struct DrawTextContext {
  96. const AVClass *class;
  97. #if CONFIG_LIBFONTCONFIG
  98. uint8_t *font; ///< font to be used
  99. #endif
  100. uint8_t *fontfile; ///< font to be used
  101. uint8_t *text; ///< text to be drawn
  102. uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
  103. size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
  104. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  105. FT_Vector *positions; ///< positions for each element in the text
  106. size_t nb_positions; ///< number of elements of positions array
  107. char *textfile; ///< file with text to be drawn
  108. int x, y; ///< position to start drawing text
  109. int w, h; ///< dimension of the text block
  110. int shadowx, shadowy;
  111. unsigned int fontsize; ///< font size to use
  112. char *fontcolor_string; ///< font color as string
  113. char *boxcolor_string; ///< box color as string
  114. char *shadowcolor_string; ///< shadow color as string
  115. uint8_t fontcolor[4]; ///< foreground color
  116. uint8_t boxcolor[4]; ///< background color
  117. uint8_t shadowcolor[4]; ///< shadow color
  118. uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
  119. uint8_t boxcolor_rgba[4]; ///< background color in RGBA
  120. uint8_t shadowcolor_rgba[4]; ///< shadow color in RGBA
  121. short int draw_box; ///< draw box around text - true or false
  122. int use_kerning; ///< font kerning is used - true/false
  123. int tabsize; ///< tab size
  124. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  125. FT_Library library; ///< freetype font library handle
  126. FT_Face face; ///< freetype font face handle
  127. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  128. int hsub, vsub; ///< chroma subsampling values
  129. int is_packed_rgb;
  130. int pixel_step[4]; ///< distance in bytes between the component of each pixel
  131. uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
  132. uint8_t *box_line[4]; ///< line used for filling the box background
  133. char *x_expr, *y_expr;
  134. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  135. double var_values[VAR_VARS_NB];
  136. char *d_expr;
  137. AVExpr *d_pexpr;
  138. int draw; ///< set to zero to prevent drawing
  139. AVLFG prng; ///< random
  140. } DrawTextContext;
  141. #define OFFSET(x) offsetof(DrawTextContext, x)
  142. #define FLAGS AV_OPT_FLAG_VIDEO_PARAM
  143. static const AVOption drawtext_options[]= {
  144. #if CONFIG_LIBFONTCONFIG
  145. { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
  146. #endif
  147. { "fontfile", NULL, OFFSET(fontfile), AV_OPT_TYPE_STRING, .flags = FLAGS },
  148. { "text", NULL, OFFSET(text), AV_OPT_TYPE_STRING, .flags = FLAGS },
  149. { "textfile", NULL, OFFSET(textfile), AV_OPT_TYPE_STRING, .flags = FLAGS },
  150. { "fontcolor", NULL, OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, { .str = "black" }, .flags = FLAGS },
  151. { "boxcolor", NULL, OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, { .str = "white" }, .flags = FLAGS },
  152. { "shadowcolor", NULL, OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, { .str = "black" }, .flags = FLAGS },
  153. { "box", NULL, OFFSET(draw_box), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, FLAGS },
  154. { "fontsize", NULL, OFFSET(fontsize), AV_OPT_TYPE_INT, { .i64 = 16 }, 1, 72, FLAGS },
  155. { "x", NULL, OFFSET(x_expr), AV_OPT_TYPE_STRING, { .str = "0" }, .flags = FLAGS },
  156. { "y", NULL, OFFSET(y_expr), AV_OPT_TYPE_STRING, { .str = "0" }, .flags = FLAGS },
  157. { "shadowx", NULL, OFFSET(shadowx), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS },
  158. { "shadowy", NULL, OFFSET(shadowy), AV_OPT_TYPE_INT, { .i64 = 0 }, INT_MIN, INT_MAX, FLAGS },
  159. { "tabsize", NULL, OFFSET(tabsize), AV_OPT_TYPE_INT, { .i64 = 4 }, 0, INT_MAX, FLAGS },
  160. { "draw", "if false do not draw", OFFSET(d_expr), AV_OPT_TYPE_STRING, { .str = "1" }, .flags = FLAGS },
  161. { "fix_bounds", "if true, check and fix text coords to avoid clipping",
  162. OFFSET(fix_bounds), AV_OPT_TYPE_INT, { .i64 = 1 }, 0, 1, FLAGS },
  163. /* FT_LOAD_* flags */
  164. { "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" },
  165. { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  166. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  167. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  168. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  169. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  170. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  171. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  172. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  173. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  174. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  175. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  176. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  177. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  178. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  179. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  180. { NULL},
  181. };
  182. static const char *drawtext_get_name(void *ctx)
  183. {
  184. return "drawtext";
  185. }
  186. static const AVClass drawtext_class = {
  187. "DrawTextContext",
  188. drawtext_get_name,
  189. drawtext_options
  190. };
  191. #undef __FTERRORS_H__
  192. #define FT_ERROR_START_LIST {
  193. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  194. #define FT_ERROR_END_LIST { 0, NULL } };
  195. struct ft_error
  196. {
  197. int err;
  198. const char *err_msg;
  199. } static ft_errors[] =
  200. #include FT_ERRORS_H
  201. #define FT_ERRMSG(e) ft_errors[e].err_msg
  202. typedef struct Glyph {
  203. FT_Glyph *glyph;
  204. uint32_t code;
  205. FT_Bitmap bitmap; ///< array holding bitmaps of font
  206. FT_BBox bbox;
  207. int advance;
  208. int bitmap_left;
  209. int bitmap_top;
  210. } Glyph;
  211. static int glyph_cmp(void *key, const void *b)
  212. {
  213. const Glyph *a = key, *bb = b;
  214. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  215. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  216. }
  217. /**
  218. * Load glyphs corresponding to the UTF-32 codepoint code.
  219. */
  220. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  221. {
  222. DrawTextContext *s = ctx->priv;
  223. Glyph *glyph;
  224. struct AVTreeNode *node = NULL;
  225. int ret;
  226. /* load glyph into s->face->glyph */
  227. if (FT_Load_Char(s->face, code, s->ft_load_flags))
  228. return AVERROR(EINVAL);
  229. /* save glyph */
  230. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  231. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  232. ret = AVERROR(ENOMEM);
  233. goto error;
  234. }
  235. glyph->code = code;
  236. if (FT_Get_Glyph(s->face->glyph, glyph->glyph)) {
  237. ret = AVERROR(EINVAL);
  238. goto error;
  239. }
  240. glyph->bitmap = s->face->glyph->bitmap;
  241. glyph->bitmap_left = s->face->glyph->bitmap_left;
  242. glyph->bitmap_top = s->face->glyph->bitmap_top;
  243. glyph->advance = s->face->glyph->advance.x >> 6;
  244. /* measure text height to calculate text_height (or the maximum text height) */
  245. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  246. /* cache the newly created glyph */
  247. if (!(node = av_tree_node_alloc())) {
  248. ret = AVERROR(ENOMEM);
  249. goto error;
  250. }
  251. av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
  252. if (glyph_ptr)
  253. *glyph_ptr = glyph;
  254. return 0;
  255. error:
  256. if (glyph)
  257. av_freep(&glyph->glyph);
  258. av_freep(&glyph);
  259. av_freep(&node);
  260. return ret;
  261. }
  262. static int parse_font(AVFilterContext *ctx)
  263. {
  264. DrawTextContext *s = ctx->priv;
  265. #if !CONFIG_LIBFONTCONFIG
  266. if (!s->fontfile) {
  267. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  268. return AVERROR(EINVAL);
  269. }
  270. return 0;
  271. #else
  272. FcPattern *pat, *best;
  273. FcResult result = FcResultMatch;
  274. FcBool fc_bool;
  275. FcChar8* fc_string;
  276. int err = AVERROR(ENOENT);
  277. if (s->fontfile)
  278. return 0;
  279. if (!FcInit())
  280. return AVERROR_UNKNOWN;
  281. if (!(pat = FcPatternCreate()))
  282. return AVERROR(ENOMEM);
  283. FcPatternAddString(pat, FC_FAMILY, s->font);
  284. FcPatternAddBool(pat, FC_OUTLINE, FcTrue);
  285. FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
  286. FcDefaultSubstitute(pat);
  287. if (!FcConfigSubstitute(NULL, pat, FcMatchPattern)) {
  288. FcPatternDestroy(pat);
  289. return AVERROR(ENOMEM);
  290. }
  291. best = FcFontMatch(NULL, pat, &result);
  292. FcPatternDestroy(pat);
  293. if (!best || result == FcResultNoMatch) {
  294. av_log(ctx, AV_LOG_ERROR,
  295. "Cannot find a valid font for the family %s\n",
  296. s->font);
  297. goto fail;
  298. }
  299. if (FcPatternGetBool(best, FC_OUTLINE, 0, &fc_bool) != FcResultMatch ||
  300. !fc_bool) {
  301. av_log(ctx, AV_LOG_ERROR, "Outline not available for %s\n",
  302. s->font);
  303. goto fail;
  304. }
  305. if (FcPatternGetString(best, FC_FAMILY, 0, &fc_string) != FcResultMatch) {
  306. av_log(ctx, AV_LOG_ERROR, "No matches for %s\n",
  307. s->font);
  308. goto fail;
  309. }
  310. if (FcPatternGetString(best, FC_FILE, 0, &fc_string) != FcResultMatch) {
  311. av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
  312. s->font);
  313. goto fail;
  314. }
  315. s->fontfile = av_strdup(fc_string);
  316. if (!s->fontfile)
  317. err = AVERROR(ENOMEM);
  318. else
  319. err = 0;
  320. fail:
  321. FcPatternDestroy(best);
  322. return err;
  323. #endif
  324. }
  325. static av_cold int init(AVFilterContext *ctx)
  326. {
  327. int err;
  328. DrawTextContext *s = ctx->priv;
  329. Glyph *glyph;
  330. if ((err = parse_font(ctx)) < 0)
  331. return err;
  332. if (s->textfile) {
  333. uint8_t *textbuf;
  334. size_t textbuf_size;
  335. if (s->text) {
  336. av_log(ctx, AV_LOG_ERROR,
  337. "Both text and text file provided. Please provide only one\n");
  338. return AVERROR(EINVAL);
  339. }
  340. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  341. av_log(ctx, AV_LOG_ERROR,
  342. "The text file '%s' could not be read or is empty\n",
  343. s->textfile);
  344. return err;
  345. }
  346. if (!(s->text = av_malloc(textbuf_size+1)))
  347. return AVERROR(ENOMEM);
  348. memcpy(s->text, textbuf, textbuf_size);
  349. s->text[textbuf_size] = 0;
  350. av_file_unmap(textbuf, textbuf_size);
  351. }
  352. if (!s->text) {
  353. av_log(ctx, AV_LOG_ERROR,
  354. "Either text or a valid file must be provided\n");
  355. return AVERROR(EINVAL);
  356. }
  357. if ((err = av_parse_color(s->fontcolor_rgba, s->fontcolor_string, -1, ctx))) {
  358. av_log(ctx, AV_LOG_ERROR,
  359. "Invalid font color '%s'\n", s->fontcolor_string);
  360. return err;
  361. }
  362. if ((err = av_parse_color(s->boxcolor_rgba, s->boxcolor_string, -1, ctx))) {
  363. av_log(ctx, AV_LOG_ERROR,
  364. "Invalid box color '%s'\n", s->boxcolor_string);
  365. return err;
  366. }
  367. if ((err = av_parse_color(s->shadowcolor_rgba, s->shadowcolor_string, -1, ctx))) {
  368. av_log(ctx, AV_LOG_ERROR,
  369. "Invalid shadow color '%s'\n", s->shadowcolor_string);
  370. return err;
  371. }
  372. if ((err = FT_Init_FreeType(&(s->library)))) {
  373. av_log(ctx, AV_LOG_ERROR,
  374. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  375. return AVERROR(EINVAL);
  376. }
  377. /* load the face, and set up the encoding, which is by default UTF-8 */
  378. if ((err = FT_New_Face(s->library, s->fontfile, 0, &s->face))) {
  379. av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
  380. s->fontfile, FT_ERRMSG(err));
  381. return AVERROR(EINVAL);
  382. }
  383. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  384. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  385. s->fontsize, FT_ERRMSG(err));
  386. return AVERROR(EINVAL);
  387. }
  388. s->use_kerning = FT_HAS_KERNING(s->face);
  389. /* load the fallback glyph with code 0 */
  390. load_glyph(ctx, NULL, 0);
  391. /* set the tabsize in pixels */
  392. if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
  393. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  394. return err;
  395. }
  396. s->tabsize *= glyph->advance;
  397. #if !HAVE_LOCALTIME_R
  398. av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
  399. #endif
  400. return 0;
  401. }
  402. static int query_formats(AVFilterContext *ctx)
  403. {
  404. static const enum AVPixelFormat pix_fmts[] = {
  405. AV_PIX_FMT_ARGB, AV_PIX_FMT_RGBA,
  406. AV_PIX_FMT_ABGR, AV_PIX_FMT_BGRA,
  407. AV_PIX_FMT_RGB24, AV_PIX_FMT_BGR24,
  408. AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV444P,
  409. AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV411P,
  410. AV_PIX_FMT_YUV410P, AV_PIX_FMT_YUV440P,
  411. AV_PIX_FMT_NONE
  412. };
  413. ff_set_common_formats(ctx, ff_make_format_list(pix_fmts));
  414. return 0;
  415. }
  416. static int glyph_enu_free(void *opaque, void *elem)
  417. {
  418. av_free(elem);
  419. return 0;
  420. }
  421. static av_cold void uninit(AVFilterContext *ctx)
  422. {
  423. DrawTextContext *s = ctx->priv;
  424. int i;
  425. av_expr_free(s->x_pexpr);
  426. av_expr_free(s->y_pexpr);
  427. av_expr_free(s->d_pexpr);
  428. s->x_pexpr = s->y_pexpr = s->d_pexpr = NULL;
  429. av_freep(&s->expanded_text);
  430. av_freep(&s->positions);
  431. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  432. av_tree_destroy(s->glyphs);
  433. s->glyphs = 0;
  434. FT_Done_Face(s->face);
  435. FT_Done_FreeType(s->library);
  436. for (i = 0; i < 4; i++) {
  437. av_freep(&s->box_line[i]);
  438. s->pixel_step[i] = 0;
  439. }
  440. }
  441. static inline int is_newline(uint32_t c)
  442. {
  443. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  444. }
  445. static int dtext_prepare_text(AVFilterContext *ctx)
  446. {
  447. DrawTextContext *s = ctx->priv;
  448. uint32_t code = 0, prev_code = 0;
  449. int x = 0, y = 0, i = 0, ret;
  450. int text_height, baseline;
  451. char *text = s->text;
  452. uint8_t *p;
  453. int str_w = 0, len;
  454. int y_min = 32000, y_max = -32000;
  455. FT_Vector delta;
  456. Glyph *glyph = NULL, *prev_glyph = NULL;
  457. Glyph dummy = { 0 };
  458. int width = ctx->inputs[0]->w;
  459. int height = ctx->inputs[0]->h;
  460. #if HAVE_LOCALTIME_R
  461. time_t now = time(0);
  462. struct tm ltime;
  463. uint8_t *buf = s->expanded_text;
  464. int buf_size = s->expanded_text_size;
  465. if (!buf)
  466. buf_size = 2*strlen(s->text)+1;
  467. localtime_r(&now, &ltime);
  468. while ((buf = av_realloc(buf, buf_size))) {
  469. *buf = 1;
  470. if (strftime(buf, buf_size, s->text, &ltime) != 0 || *buf == 0)
  471. break;
  472. buf_size *= 2;
  473. }
  474. if (!buf)
  475. return AVERROR(ENOMEM);
  476. text = s->expanded_text = buf;
  477. s->expanded_text_size = buf_size;
  478. #endif
  479. if ((len = strlen(text)) > s->nb_positions) {
  480. FT_Vector *p = av_realloc(s->positions,
  481. len * sizeof(*s->positions));
  482. if (!p) {
  483. av_freep(s->positions);
  484. s->nb_positions = 0;
  485. return AVERROR(ENOMEM);
  486. } else {
  487. s->positions = p;
  488. s->nb_positions = len;
  489. }
  490. }
  491. /* load and cache glyphs */
  492. for (i = 0, p = text; *p; i++) {
  493. GET_UTF8(code, *p++, continue;);
  494. /* get glyph */
  495. dummy.code = code;
  496. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  497. if (!glyph) {
  498. ret = load_glyph(ctx, &glyph, code);
  499. if (ret)
  500. return ret;
  501. }
  502. y_min = FFMIN(glyph->bbox.yMin, y_min);
  503. y_max = FFMAX(glyph->bbox.yMax, y_max);
  504. }
  505. text_height = y_max - y_min;
  506. baseline = y_max;
  507. /* compute and save position for each glyph */
  508. glyph = NULL;
  509. for (i = 0, p = text; *p; i++) {
  510. GET_UTF8(code, *p++, continue;);
  511. /* skip the \n in the sequence \r\n */
  512. if (prev_code == '\r' && code == '\n')
  513. continue;
  514. prev_code = code;
  515. if (is_newline(code)) {
  516. str_w = FFMAX(str_w, x - s->x);
  517. y += text_height;
  518. x = 0;
  519. continue;
  520. }
  521. /* get glyph */
  522. prev_glyph = glyph;
  523. dummy.code = code;
  524. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  525. /* kerning */
  526. if (s->use_kerning && prev_glyph && glyph->code) {
  527. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  528. ft_kerning_default, &delta);
  529. x += delta.x >> 6;
  530. }
  531. if (x + glyph->bbox.xMax >= width) {
  532. str_w = FFMAX(str_w, x);
  533. y += text_height;
  534. x = 0;
  535. }
  536. /* save position */
  537. s->positions[i].x = x + glyph->bitmap_left;
  538. s->positions[i].y = y - glyph->bitmap_top + baseline;
  539. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  540. else x += glyph->advance;
  541. }
  542. str_w = FFMIN(width - 1, FFMAX(str_w, x));
  543. y = FFMIN(y + text_height, height - 1);
  544. s->w = str_w;
  545. s->var_values[VAR_TEXT_W] = s->var_values[VAR_TW] = s->w;
  546. s->h = y;
  547. s->var_values[VAR_TEXT_H] = s->var_values[VAR_TH] = s->h;
  548. return 0;
  549. }
  550. static int config_input(AVFilterLink *inlink)
  551. {
  552. AVFilterContext *ctx = inlink->dst;
  553. DrawTextContext *s = ctx->priv;
  554. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
  555. int ret;
  556. s->hsub = pix_desc->log2_chroma_w;
  557. s->vsub = pix_desc->log2_chroma_h;
  558. s->var_values[VAR_E ] = M_E;
  559. s->var_values[VAR_PHI] = M_PHI;
  560. s->var_values[VAR_PI ] = M_PI;
  561. s->var_values[VAR_MAIN_W] =
  562. s->var_values[VAR_MW] = ctx->inputs[0]->w;
  563. s->var_values[VAR_MAIN_H] =
  564. s->var_values[VAR_MH] = ctx->inputs[0]->h;
  565. s->var_values[VAR_X] = 0;
  566. s->var_values[VAR_Y] = 0;
  567. s->var_values[VAR_T] = NAN;
  568. av_lfg_init(&s->prng, av_get_random_seed());
  569. av_expr_free(s->x_pexpr);
  570. av_expr_free(s->y_pexpr);
  571. av_expr_free(s->d_pexpr);
  572. s->x_pexpr = s->y_pexpr = s->d_pexpr = NULL;
  573. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  574. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  575. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  576. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  577. (ret = av_expr_parse(&s->d_pexpr, s->d_expr, var_names,
  578. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  579. return AVERROR(EINVAL);
  580. if ((ret =
  581. ff_fill_line_with_color(s->box_line, s->pixel_step,
  582. inlink->w, s->boxcolor,
  583. inlink->format, s->boxcolor_rgba,
  584. &s->is_packed_rgb, s->rgba_map)) < 0)
  585. return ret;
  586. if (!s->is_packed_rgb) {
  587. uint8_t *rgba = s->fontcolor_rgba;
  588. s->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  589. s->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  590. s->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  591. s->fontcolor[3] = rgba[3];
  592. rgba = s->shadowcolor_rgba;
  593. s->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  594. s->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  595. s->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  596. s->shadowcolor[3] = rgba[3];
  597. }
  598. s->draw = 1;
  599. return dtext_prepare_text(ctx);
  600. }
  601. #define GET_BITMAP_VAL(r, c) \
  602. bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
  603. (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
  604. bitmap->buffer[(r) * bitmap->pitch + (c)]
  605. #define SET_PIXEL_YUV(frame, yuva_color, val, x, y, hsub, vsub) { \
  606. luma_pos = ((x) ) + ((y) ) * frame->linesize[0]; \
  607. alpha = yuva_color[3] * (val) * 129; \
  608. frame->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * frame->data[0][luma_pos] ) >> 23; \
  609. if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
  610. chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[1]; \
  611. chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[2]; \
  612. frame->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * frame->data[1][chroma_pos1]) >> 23; \
  613. frame->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * frame->data[2][chroma_pos2]) >> 23; \
  614. }\
  615. }
  616. static inline int draw_glyph_yuv(AVFrame *frame, FT_Bitmap *bitmap, unsigned int x,
  617. unsigned int y, unsigned int width, unsigned int height,
  618. const uint8_t yuva_color[4], int hsub, int vsub)
  619. {
  620. int r, c, alpha;
  621. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  622. uint8_t src_val;
  623. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  624. for (c = 0; c < bitmap->width && c+x < width; c++) {
  625. /* get intensity value in the glyph bitmap (source) */
  626. src_val = GET_BITMAP_VAL(r, c);
  627. if (!src_val)
  628. continue;
  629. SET_PIXEL_YUV(frame, yuva_color, src_val, c+x, y+r, hsub, vsub);
  630. }
  631. }
  632. return 0;
  633. }
  634. #define SET_PIXEL_RGB(frame, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
  635. p = frame->data[0] + (x) * pixel_step + ((y) * frame->linesize[0]); \
  636. alpha = rgba_color[3] * (val) * 129; \
  637. *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
  638. *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
  639. *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
  640. }
  641. static inline int draw_glyph_rgb(AVFrame *frame, FT_Bitmap *bitmap,
  642. unsigned int x, unsigned int y,
  643. unsigned int width, unsigned int height, int pixel_step,
  644. const uint8_t rgba_color[4], const uint8_t rgba_map[4])
  645. {
  646. int r, c, alpha;
  647. uint8_t *p;
  648. uint8_t src_val;
  649. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  650. for (c = 0; c < bitmap->width && c+x < width; c++) {
  651. /* get intensity value in the glyph bitmap (source) */
  652. src_val = GET_BITMAP_VAL(r, c);
  653. if (!src_val)
  654. continue;
  655. SET_PIXEL_RGB(frame, rgba_color, src_val, c+x, y+r, pixel_step,
  656. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  657. }
  658. }
  659. return 0;
  660. }
  661. static inline void drawbox(AVFrame *frame, unsigned int x, unsigned int y,
  662. unsigned int width, unsigned int height,
  663. uint8_t *line[4], int pixel_step[4], uint8_t color[4],
  664. int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
  665. {
  666. int i, j, alpha;
  667. if (color[3] != 0xFF) {
  668. if (is_rgba_packed) {
  669. uint8_t *p;
  670. for (j = 0; j < height; j++)
  671. for (i = 0; i < width; i++)
  672. SET_PIXEL_RGB(frame, color, 255, i+x, y+j, pixel_step[0],
  673. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  674. } else {
  675. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  676. for (j = 0; j < height; j++)
  677. for (i = 0; i < width; i++)
  678. SET_PIXEL_YUV(frame, color, 255, i+x, y+j, hsub, vsub);
  679. }
  680. } else {
  681. ff_draw_rectangle(frame->data, frame->linesize,
  682. line, pixel_step, hsub, vsub,
  683. x, y, width, height);
  684. }
  685. }
  686. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  687. int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
  688. {
  689. char *text = HAVE_LOCALTIME_R ? s->expanded_text : s->text;
  690. uint32_t code = 0;
  691. int i;
  692. uint8_t *p;
  693. Glyph *glyph = NULL;
  694. for (i = 0, p = text; *p; i++) {
  695. Glyph dummy = { 0 };
  696. GET_UTF8(code, *p++, continue;);
  697. /* skip new line chars, just go to new line */
  698. if (code == '\n' || code == '\r' || code == '\t')
  699. continue;
  700. dummy.code = code;
  701. glyph = av_tree_find(s->glyphs, &dummy, (void *)glyph_cmp, NULL);
  702. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  703. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  704. return AVERROR(EINVAL);
  705. if (s->is_packed_rgb) {
  706. draw_glyph_rgb(frame, &glyph->bitmap,
  707. s->positions[i].x+x, s->positions[i].y+y, width, height,
  708. s->pixel_step[0], rgbcolor, s->rgba_map);
  709. } else {
  710. draw_glyph_yuv(frame, &glyph->bitmap,
  711. s->positions[i].x+x, s->positions[i].y+y, width, height,
  712. yuvcolor, s->hsub, s->vsub);
  713. }
  714. }
  715. return 0;
  716. }
  717. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  718. int width, int height)
  719. {
  720. DrawTextContext *s = ctx->priv;
  721. int ret;
  722. /* draw box */
  723. if (s->draw_box)
  724. drawbox(frame, s->x, s->y, s->w, s->h,
  725. s->box_line, s->pixel_step, s->boxcolor,
  726. s->hsub, s->vsub, s->is_packed_rgb,
  727. s->rgba_map);
  728. if (s->shadowx || s->shadowy) {
  729. if ((ret = draw_glyphs(s, frame, width, height,
  730. s->shadowcolor_rgba,
  731. s->shadowcolor,
  732. s->x + s->shadowx,
  733. s->y + s->shadowy)) < 0)
  734. return ret;
  735. }
  736. if ((ret = draw_glyphs(s, frame, width, height,
  737. s->fontcolor_rgba,
  738. s->fontcolor,
  739. s->x,
  740. s->y)) < 0)
  741. return ret;
  742. return 0;
  743. }
  744. static inline int normalize_double(int *n, double d)
  745. {
  746. int ret = 0;
  747. if (isnan(d)) {
  748. ret = AVERROR(EINVAL);
  749. } else if (d > INT_MAX || d < INT_MIN) {
  750. *n = d > INT_MAX ? INT_MAX : INT_MIN;
  751. ret = AVERROR(EINVAL);
  752. } else
  753. *n = round(d);
  754. return ret;
  755. }
  756. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  757. {
  758. AVFilterContext *ctx = inlink->dst;
  759. DrawTextContext *s = ctx->priv;
  760. int ret = 0;
  761. if ((ret = dtext_prepare_text(ctx)) < 0) {
  762. av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
  763. av_frame_free(&frame);
  764. return ret;
  765. }
  766. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  767. NAN : frame->pts * av_q2d(inlink->time_base);
  768. s->var_values[VAR_X] =
  769. av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  770. s->var_values[VAR_Y] =
  771. av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  772. s->var_values[VAR_X] =
  773. av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  774. s->draw = av_expr_eval(s->d_pexpr, s->var_values, &s->prng);
  775. normalize_double(&s->x, s->var_values[VAR_X]);
  776. normalize_double(&s->y, s->var_values[VAR_Y]);
  777. if (s->fix_bounds) {
  778. if (s->x < 0) s->x = 0;
  779. if (s->y < 0) s->y = 0;
  780. if ((unsigned)s->x + (unsigned)s->w > inlink->w)
  781. s->x = inlink->w - s->w;
  782. if ((unsigned)s->y + (unsigned)s->h > inlink->h)
  783. s->y = inlink->h - s->h;
  784. }
  785. s->x &= ~((1 << s->hsub) - 1);
  786. s->y &= ~((1 << s->vsub) - 1);
  787. av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
  788. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  789. s->x, s->y, s->x+s->w, s->y+s->h);
  790. if (s->draw)
  791. draw_text(inlink->dst, frame, frame->width, frame->height);
  792. s->var_values[VAR_N] += 1.0;
  793. return ff_filter_frame(inlink->dst->outputs[0], frame);
  794. }
  795. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  796. {
  797. .name = "default",
  798. .type = AVMEDIA_TYPE_VIDEO,
  799. .get_video_buffer = ff_null_get_video_buffer,
  800. .filter_frame = filter_frame,
  801. .config_props = config_input,
  802. .needs_writable = 1,
  803. },
  804. { NULL }
  805. };
  806. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  807. {
  808. .name = "default",
  809. .type = AVMEDIA_TYPE_VIDEO,
  810. },
  811. { NULL }
  812. };
  813. AVFilter ff_vf_drawtext = {
  814. .name = "drawtext",
  815. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  816. .priv_size = sizeof(DrawTextContext),
  817. .priv_class = &drawtext_class,
  818. .init = init,
  819. .uninit = uninit,
  820. .query_formats = query_formats,
  821. .inputs = avfilter_vf_drawtext_inputs,
  822. .outputs = avfilter_vf_drawtext_outputs,
  823. };