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.

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