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.

875 lines
32KB

  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 *dtext = ctx->priv;
  211. Glyph *glyph;
  212. struct AVTreeNode *node = NULL;
  213. int ret;
  214. /* load glyph into dtext->face->glyph */
  215. if (FT_Load_Char(dtext->face, code, dtext->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(dtext->face->glyph, glyph->glyph)) {
  225. ret = AVERROR(EINVAL);
  226. goto error;
  227. }
  228. glyph->bitmap = dtext->face->glyph->bitmap;
  229. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  230. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  231. glyph->advance = dtext->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(&dtext->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 *dtext = ctx->priv;
  254. Glyph *glyph;
  255. if (!dtext->fontfile) {
  256. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  257. return AVERROR(EINVAL);
  258. }
  259. if (dtext->textfile) {
  260. uint8_t *textbuf;
  261. size_t textbuf_size;
  262. if (dtext->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(dtext->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. dtext->textfile);
  271. return err;
  272. }
  273. if (!(dtext->text = av_malloc(textbuf_size+1)))
  274. return AVERROR(ENOMEM);
  275. memcpy(dtext->text, textbuf, textbuf_size);
  276. dtext->text[textbuf_size] = 0;
  277. av_file_unmap(textbuf, textbuf_size);
  278. }
  279. if (!dtext->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(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
  285. av_log(ctx, AV_LOG_ERROR,
  286. "Invalid font color '%s'\n", dtext->fontcolor_string);
  287. return err;
  288. }
  289. if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
  290. av_log(ctx, AV_LOG_ERROR,
  291. "Invalid box color '%s'\n", dtext->boxcolor_string);
  292. return err;
  293. }
  294. if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
  295. av_log(ctx, AV_LOG_ERROR,
  296. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  297. return err;
  298. }
  299. if ((err = FT_Init_FreeType(&(dtext->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(dtext->library, dtext->fontfile, 0, &dtext->face))) {
  306. av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
  307. dtext->fontfile, FT_ERRMSG(err));
  308. return AVERROR(EINVAL);
  309. }
  310. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  311. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  312. dtext->fontsize, FT_ERRMSG(err));
  313. return AVERROR(EINVAL);
  314. }
  315. dtext->use_kerning = FT_HAS_KERNING(dtext->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. dtext->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 *dtext = ctx->priv;
  351. int i;
  352. av_freep(&dtext->expanded_text);
  353. av_freep(&dtext->positions);
  354. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  355. av_tree_destroy(dtext->glyphs);
  356. dtext->glyphs = 0;
  357. FT_Done_Face(dtext->face);
  358. FT_Done_FreeType(dtext->library);
  359. for (i = 0; i < 4; i++) {
  360. av_freep(&dtext->box_line[i]);
  361. dtext->pixel_step[i] = 0;
  362. }
  363. }
  364. static inline int is_newline(uint32_t c)
  365. {
  366. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  367. }
  368. static int dtext_prepare_text(AVFilterContext *ctx)
  369. {
  370. DrawTextContext *dtext = ctx->priv;
  371. uint32_t code = 0, prev_code = 0;
  372. int x = 0, y = 0, i = 0, ret;
  373. int text_height, baseline;
  374. char *text = dtext->text;
  375. uint8_t *p;
  376. int str_w = 0, len;
  377. int y_min = 32000, y_max = -32000;
  378. FT_Vector delta;
  379. Glyph *glyph = NULL, *prev_glyph = NULL;
  380. Glyph dummy = { 0 };
  381. int width = ctx->inputs[0]->w;
  382. int height = ctx->inputs[0]->h;
  383. #if HAVE_LOCALTIME_R
  384. time_t now = time(0);
  385. struct tm ltime;
  386. uint8_t *buf = dtext->expanded_text;
  387. int buf_size = dtext->expanded_text_size;
  388. if (!buf)
  389. buf_size = 2*strlen(dtext->text)+1;
  390. localtime_r(&now, &ltime);
  391. while ((buf = av_realloc(buf, buf_size))) {
  392. *buf = 1;
  393. if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
  394. break;
  395. buf_size *= 2;
  396. }
  397. if (!buf)
  398. return AVERROR(ENOMEM);
  399. text = dtext->expanded_text = buf;
  400. dtext->expanded_text_size = buf_size;
  401. #endif
  402. if ((len = strlen(text)) > dtext->nb_positions) {
  403. FT_Vector *p = av_realloc(dtext->positions,
  404. len * sizeof(*dtext->positions));
  405. if (!p) {
  406. av_freep(dtext->positions);
  407. dtext->nb_positions = 0;
  408. return AVERROR(ENOMEM);
  409. } else {
  410. dtext->positions = p;
  411. dtext->nb_positions = len;
  412. }
  413. }
  414. /* load and cache glyphs */
  415. for (i = 0, p = text; *p; i++) {
  416. GET_UTF8(code, *p++, continue;);
  417. /* get glyph */
  418. dummy.code = code;
  419. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  420. if (!glyph) {
  421. ret = load_glyph(ctx, &glyph, code);
  422. if (ret)
  423. return ret;
  424. }
  425. y_min = FFMIN(glyph->bbox.yMin, y_min);
  426. y_max = FFMAX(glyph->bbox.yMax, y_max);
  427. }
  428. text_height = y_max - y_min;
  429. baseline = y_max;
  430. /* compute and save position for each glyph */
  431. glyph = NULL;
  432. for (i = 0, p = text; *p; i++) {
  433. GET_UTF8(code, *p++, continue;);
  434. /* skip the \n in the sequence \r\n */
  435. if (prev_code == '\r' && code == '\n')
  436. continue;
  437. prev_code = code;
  438. if (is_newline(code)) {
  439. str_w = FFMAX(str_w, x - dtext->x);
  440. y += text_height;
  441. x = 0;
  442. continue;
  443. }
  444. /* get glyph */
  445. prev_glyph = glyph;
  446. dummy.code = code;
  447. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  448. /* kerning */
  449. if (dtext->use_kerning && prev_glyph && glyph->code) {
  450. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  451. ft_kerning_default, &delta);
  452. x += delta.x >> 6;
  453. }
  454. if (x + glyph->bbox.xMax >= width) {
  455. str_w = FFMAX(str_w, x);
  456. y += text_height;
  457. x = 0;
  458. }
  459. /* save position */
  460. dtext->positions[i].x = x + glyph->bitmap_left;
  461. dtext->positions[i].y = y - glyph->bitmap_top + baseline;
  462. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  463. else x += glyph->advance;
  464. }
  465. str_w = FFMIN(width - 1, FFMAX(str_w, x));
  466. y = FFMIN(y + text_height, height - 1);
  467. dtext->w = str_w;
  468. dtext->var_values[VAR_TEXT_W] = dtext->var_values[VAR_TW] = dtext->w;
  469. dtext->h = y;
  470. dtext->var_values[VAR_TEXT_H] = dtext->var_values[VAR_TH] = dtext->h;
  471. return 0;
  472. }
  473. static int config_input(AVFilterLink *inlink)
  474. {
  475. AVFilterContext *ctx = inlink->dst;
  476. DrawTextContext *dtext = ctx->priv;
  477. const AVPixFmtDescriptor *pix_desc = av_pix_fmt_desc_get(inlink->format);
  478. int ret;
  479. dtext->hsub = pix_desc->log2_chroma_w;
  480. dtext->vsub = pix_desc->log2_chroma_h;
  481. dtext->var_values[VAR_E ] = M_E;
  482. dtext->var_values[VAR_PHI] = M_PHI;
  483. dtext->var_values[VAR_PI ] = M_PI;
  484. dtext->var_values[VAR_MAIN_W] =
  485. dtext->var_values[VAR_MW] = ctx->inputs[0]->w;
  486. dtext->var_values[VAR_MAIN_H] =
  487. dtext->var_values[VAR_MH] = ctx->inputs[0]->h;
  488. dtext->var_values[VAR_X] = 0;
  489. dtext->var_values[VAR_Y] = 0;
  490. dtext->var_values[VAR_N] = 0;
  491. dtext->var_values[VAR_T] = NAN;
  492. av_lfg_init(&dtext->prng, av_get_random_seed());
  493. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  494. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  495. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  496. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  497. (ret = av_expr_parse(&dtext->d_pexpr, dtext->d_expr, var_names,
  498. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  499. return AVERROR(EINVAL);
  500. if ((ret =
  501. ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
  502. inlink->w, dtext->boxcolor,
  503. inlink->format, dtext->boxcolor_rgba,
  504. &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
  505. return ret;
  506. if (!dtext->is_packed_rgb) {
  507. uint8_t *rgba = dtext->fontcolor_rgba;
  508. dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  509. dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  510. dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  511. dtext->fontcolor[3] = rgba[3];
  512. rgba = dtext->shadowcolor_rgba;
  513. dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  514. dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  515. dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  516. dtext->shadowcolor[3] = rgba[3];
  517. }
  518. dtext->draw = 1;
  519. return dtext_prepare_text(ctx);
  520. }
  521. #define GET_BITMAP_VAL(r, c) \
  522. bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
  523. (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
  524. bitmap->buffer[(r) * bitmap->pitch + (c)]
  525. #define SET_PIXEL_YUV(frame, yuva_color, val, x, y, hsub, vsub) { \
  526. luma_pos = ((x) ) + ((y) ) * frame->linesize[0]; \
  527. alpha = yuva_color[3] * (val) * 129; \
  528. frame->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * frame->data[0][luma_pos] ) >> 23; \
  529. if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
  530. chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[1]; \
  531. chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * frame->linesize[2]; \
  532. frame->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * frame->data[1][chroma_pos1]) >> 23; \
  533. frame->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * frame->data[2][chroma_pos2]) >> 23; \
  534. }\
  535. }
  536. static inline int draw_glyph_yuv(AVFrame *frame, FT_Bitmap *bitmap, unsigned int x,
  537. unsigned int y, unsigned int width, unsigned int height,
  538. const uint8_t yuva_color[4], int hsub, int vsub)
  539. {
  540. int r, c, alpha;
  541. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  542. uint8_t src_val;
  543. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  544. for (c = 0; c < bitmap->width && c+x < width; c++) {
  545. /* get intensity value in the glyph bitmap (source) */
  546. src_val = GET_BITMAP_VAL(r, c);
  547. if (!src_val)
  548. continue;
  549. SET_PIXEL_YUV(frame, yuva_color, src_val, c+x, y+r, hsub, vsub);
  550. }
  551. }
  552. return 0;
  553. }
  554. #define SET_PIXEL_RGB(frame, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
  555. p = frame->data[0] + (x) * pixel_step + ((y) * frame->linesize[0]); \
  556. alpha = rgba_color[3] * (val) * 129; \
  557. *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
  558. *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
  559. *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
  560. }
  561. static inline int draw_glyph_rgb(AVFrame *frame, FT_Bitmap *bitmap,
  562. unsigned int x, unsigned int y,
  563. unsigned int width, unsigned int height, int pixel_step,
  564. const uint8_t rgba_color[4], const uint8_t rgba_map[4])
  565. {
  566. int r, c, alpha;
  567. uint8_t *p;
  568. uint8_t src_val;
  569. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  570. for (c = 0; c < bitmap->width && c+x < width; c++) {
  571. /* get intensity value in the glyph bitmap (source) */
  572. src_val = GET_BITMAP_VAL(r, c);
  573. if (!src_val)
  574. continue;
  575. SET_PIXEL_RGB(frame, rgba_color, src_val, c+x, y+r, pixel_step,
  576. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  577. }
  578. }
  579. return 0;
  580. }
  581. static inline void drawbox(AVFrame *frame, unsigned int x, unsigned int y,
  582. unsigned int width, unsigned int height,
  583. uint8_t *line[4], int pixel_step[4], uint8_t color[4],
  584. int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
  585. {
  586. int i, j, alpha;
  587. if (color[3] != 0xFF) {
  588. if (is_rgba_packed) {
  589. uint8_t *p;
  590. for (j = 0; j < height; j++)
  591. for (i = 0; i < width; i++)
  592. SET_PIXEL_RGB(frame, color, 255, i+x, y+j, pixel_step[0],
  593. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  594. } else {
  595. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  596. for (j = 0; j < height; j++)
  597. for (i = 0; i < width; i++)
  598. SET_PIXEL_YUV(frame, color, 255, i+x, y+j, hsub, vsub);
  599. }
  600. } else {
  601. ff_draw_rectangle(frame->data, frame->linesize,
  602. line, pixel_step, hsub, vsub,
  603. x, y, width, height);
  604. }
  605. }
  606. static int draw_glyphs(DrawTextContext *dtext, AVFrame *frame,
  607. int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
  608. {
  609. char *text = HAVE_LOCALTIME_R ? dtext->expanded_text : dtext->text;
  610. uint32_t code = 0;
  611. int i;
  612. uint8_t *p;
  613. Glyph *glyph = NULL;
  614. for (i = 0, p = text; *p; i++) {
  615. Glyph dummy = { 0 };
  616. GET_UTF8(code, *p++, continue;);
  617. /* skip new line chars, just go to new line */
  618. if (code == '\n' || code == '\r' || code == '\t')
  619. continue;
  620. dummy.code = code;
  621. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  622. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  623. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  624. return AVERROR(EINVAL);
  625. if (dtext->is_packed_rgb) {
  626. draw_glyph_rgb(frame, &glyph->bitmap,
  627. dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
  628. dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
  629. } else {
  630. draw_glyph_yuv(frame, &glyph->bitmap,
  631. dtext->positions[i].x+x, dtext->positions[i].y+y, width, height,
  632. yuvcolor, dtext->hsub, dtext->vsub);
  633. }
  634. }
  635. return 0;
  636. }
  637. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  638. int width, int height)
  639. {
  640. DrawTextContext *dtext = ctx->priv;
  641. int ret;
  642. /* draw box */
  643. if (dtext->draw_box)
  644. drawbox(frame, dtext->x, dtext->y, dtext->w, dtext->h,
  645. dtext->box_line, dtext->pixel_step, dtext->boxcolor,
  646. dtext->hsub, dtext->vsub, dtext->is_packed_rgb,
  647. dtext->rgba_map);
  648. if (dtext->shadowx || dtext->shadowy) {
  649. if ((ret = draw_glyphs(dtext, frame, width, height,
  650. dtext->shadowcolor_rgba,
  651. dtext->shadowcolor,
  652. dtext->x + dtext->shadowx,
  653. dtext->y + dtext->shadowy)) < 0)
  654. return ret;
  655. }
  656. if ((ret = draw_glyphs(dtext, frame, width, height,
  657. dtext->fontcolor_rgba,
  658. dtext->fontcolor,
  659. dtext->x,
  660. dtext->y)) < 0)
  661. return ret;
  662. return 0;
  663. }
  664. static inline int normalize_double(int *n, double d)
  665. {
  666. int ret = 0;
  667. if (isnan(d)) {
  668. ret = AVERROR(EINVAL);
  669. } else if (d > INT_MAX || d < INT_MIN) {
  670. *n = d > INT_MAX ? INT_MAX : INT_MIN;
  671. ret = AVERROR(EINVAL);
  672. } else
  673. *n = round(d);
  674. return ret;
  675. }
  676. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  677. {
  678. AVFilterContext *ctx = inlink->dst;
  679. DrawTextContext *dtext = ctx->priv;
  680. int ret = 0;
  681. if ((ret = dtext_prepare_text(ctx)) < 0) {
  682. av_log(ctx, AV_LOG_ERROR, "Can't draw text\n");
  683. av_frame_free(&frame);
  684. return ret;
  685. }
  686. dtext->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  687. NAN : frame->pts * av_q2d(inlink->time_base);
  688. dtext->var_values[VAR_X] =
  689. av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  690. dtext->var_values[VAR_Y] =
  691. av_expr_eval(dtext->y_pexpr, dtext->var_values, &dtext->prng);
  692. dtext->var_values[VAR_X] =
  693. av_expr_eval(dtext->x_pexpr, dtext->var_values, &dtext->prng);
  694. dtext->draw = av_expr_eval(dtext->d_pexpr, dtext->var_values, &dtext->prng);
  695. normalize_double(&dtext->x, dtext->var_values[VAR_X]);
  696. normalize_double(&dtext->y, dtext->var_values[VAR_Y]);
  697. if (dtext->fix_bounds) {
  698. if (dtext->x < 0) dtext->x = 0;
  699. if (dtext->y < 0) dtext->y = 0;
  700. if ((unsigned)dtext->x + (unsigned)dtext->w > inlink->w)
  701. dtext->x = inlink->w - dtext->w;
  702. if ((unsigned)dtext->y + (unsigned)dtext->h > inlink->h)
  703. dtext->y = inlink->h - dtext->h;
  704. }
  705. dtext->x &= ~((1 << dtext->hsub) - 1);
  706. dtext->y &= ~((1 << dtext->vsub) - 1);
  707. av_dlog(ctx, "n:%d t:%f x:%d y:%d x+w:%d y+h:%d\n",
  708. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  709. dtext->x, dtext->y, dtext->x+dtext->w, dtext->y+dtext->h);
  710. if (dtext->draw)
  711. draw_text(inlink->dst, frame, frame->width, frame->height);
  712. dtext->var_values[VAR_N] += 1.0;
  713. return ff_filter_frame(inlink->dst->outputs[0], frame);
  714. }
  715. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  716. {
  717. .name = "default",
  718. .type = AVMEDIA_TYPE_VIDEO,
  719. .get_video_buffer = ff_null_get_video_buffer,
  720. .filter_frame = filter_frame,
  721. .config_props = config_input,
  722. .needs_writable = 1,
  723. },
  724. { NULL }
  725. };
  726. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  727. {
  728. .name = "default",
  729. .type = AVMEDIA_TYPE_VIDEO,
  730. },
  731. { NULL }
  732. };
  733. AVFilter avfilter_vf_drawtext = {
  734. .name = "drawtext",
  735. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  736. .priv_size = sizeof(DrawTextContext),
  737. .priv_class = &drawtext_class,
  738. .init = init,
  739. .uninit = uninit,
  740. .query_formats = query_formats,
  741. .inputs = avfilter_vf_drawtext_inputs,
  742. .outputs = avfilter_vf_drawtext_outputs,
  743. };