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.

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