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.

674 lines
26KB

  1. /*
  2. * Copyright (c) 2011 Stefano Sabatini
  3. * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
  4. * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
  5. *
  6. * This file is part of FFmpeg.
  7. *
  8. * FFmpeg is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU Lesser General Public
  10. * License as published by the Free Software Foundation; either
  11. * version 2.1 of the License, or (at your option) any later version.
  12. *
  13. * FFmpeg is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  16. * Lesser General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU Lesser General Public
  19. * License along with FFmpeg; if not, write to the Free Software
  20. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  21. */
  22. /**
  23. * @file
  24. * drawtext filter, based on the original FFmpeg 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/file.h"
  31. #include "libavutil/opt.h"
  32. #include "libavutil/parseutils.h"
  33. #include "libavutil/pixdesc.h"
  34. #include "libavutil/tree.h"
  35. #include "avfilter.h"
  36. #include "drawutils.h"
  37. #undef time
  38. #include <ft2build.h>
  39. #include <freetype/config/ftheader.h>
  40. #include FT_FREETYPE_H
  41. #include FT_GLYPH_H
  42. typedef struct {
  43. const AVClass *class;
  44. uint8_t *fontfile; ///< font to be used
  45. uint8_t *text; ///< text to be drawn
  46. uint8_t *text_priv; ///< used to detect whether text changed
  47. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  48. FT_Vector *positions; ///< positions for each element in the text
  49. char *textfile; ///< file with text to be drawn
  50. unsigned int x; ///< x position to start drawing text
  51. unsigned int y; ///< y position to start drawing text
  52. unsigned int fontsize; ///< font size to use
  53. char *fontcolor_string; ///< font color as string
  54. char *boxcolor_string; ///< box color as string
  55. uint8_t fontcolor[4]; ///< foreground color
  56. uint8_t boxcolor[4]; ///< background color
  57. uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
  58. uint8_t boxcolor_rgba[4]; ///< background color in RGBA
  59. short int draw_box; ///< draw box around text - true or false
  60. int use_kerning; ///< font kerning is used - true/false
  61. int tabsize; ///< tab size
  62. FT_Library library; ///< freetype font library handle
  63. FT_Face face; ///< freetype font face handle
  64. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  65. int hsub, vsub; ///< chroma subsampling values
  66. int is_packed_rgb;
  67. int pixel_step[4]; ///< distance in bytes between the component of each pixel
  68. uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
  69. uint8_t *box_line[4]; ///< line used for filling the box background
  70. } DrawTextContext;
  71. #define OFFSET(x) offsetof(DrawTextContext, x)
  72. static const AVOption drawtext_options[]= {
  73. {"fontfile", "set font file", OFFSET(fontfile), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
  74. {"text", "set text", OFFSET(text), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
  75. {"textfile", "set text file", OFFSET(textfile), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
  76. {"fontcolor","set foreground color", OFFSET(fontcolor_string), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
  77. {"boxcolor", "set box color", OFFSET(boxcolor_string), FF_OPT_TYPE_STRING, 0, CHAR_MIN, CHAR_MAX },
  78. {"box", "set box", OFFSET(draw_box), FF_OPT_TYPE_INT, 0, 0, 1 },
  79. {"fontsize", "set font size", OFFSET(fontsize), FF_OPT_TYPE_INT, 16, 1, 72 },
  80. {"x", "set x", OFFSET(x), FF_OPT_TYPE_INT, 0, 0, INT_MAX },
  81. {"y", "set y", OFFSET(y), FF_OPT_TYPE_INT, 0, 0, INT_MAX },
  82. {"tabsize", "set tab size", OFFSET(tabsize), FF_OPT_TYPE_INT, 4, 0, INT_MAX },
  83. /* FT_LOAD_* flags */
  84. {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), FF_OPT_TYPE_FLAGS, FT_LOAD_DEFAULT|FT_LOAD_RENDER, 0, INT_MAX, 0, "ft_load_flags" },
  85. {"default", "set default", 0, FF_OPT_TYPE_CONST, FT_LOAD_DEFAULT, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  86. {"no_scale", "set no_scale", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_SCALE, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  87. {"no_hinting", "set no_hinting", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_HINTING, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  88. {"render", "set render", 0, FF_OPT_TYPE_CONST, FT_LOAD_RENDER, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  89. {"no_bitmap", "set no_bitmap", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_BITMAP, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  90. {"vertical_layout", "set vertical_layout", 0, FF_OPT_TYPE_CONST, FT_LOAD_VERTICAL_LAYOUT, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  91. {"force_autohint", "set force_autohint", 0, FF_OPT_TYPE_CONST, FT_LOAD_FORCE_AUTOHINT, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  92. {"crop_bitmap", "set crop_bitmap", 0, FF_OPT_TYPE_CONST, FT_LOAD_CROP_BITMAP, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  93. {"pedantic", "set pedantic", 0, FF_OPT_TYPE_CONST, FT_LOAD_PEDANTIC, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  94. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  95. {"no_recurse", "set no_recurse", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_RECURSE, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  96. {"ignore_transform", "set ignore_transform", 0, FF_OPT_TYPE_CONST, FT_LOAD_IGNORE_TRANSFORM, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  97. {"monochrome", "set monochrome", 0, FF_OPT_TYPE_CONST, FT_LOAD_MONOCHROME, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  98. {"linear_design", "set linear_design", 0, FF_OPT_TYPE_CONST, FT_LOAD_LINEAR_DESIGN, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  99. {"no_autohint", "set no_autohint", 0, FF_OPT_TYPE_CONST, FT_LOAD_NO_AUTOHINT, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  100. {NULL},
  101. };
  102. static const char *drawtext_get_name(void *ctx)
  103. {
  104. return "drawtext";
  105. }
  106. static const AVClass drawtext_class = {
  107. "DrawTextContext",
  108. drawtext_get_name,
  109. drawtext_options
  110. };
  111. #undef __FTERRORS_H__
  112. #define FT_ERROR_START_LIST {
  113. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  114. #define FT_ERROR_END_LIST { 0, NULL } };
  115. struct ft_error
  116. {
  117. int err;
  118. const char *err_msg;
  119. } static ft_errors[] =
  120. #include FT_ERRORS_H
  121. #define FT_ERRMSG(e) ft_errors[e].err_msg
  122. typedef struct {
  123. FT_Glyph *glyph;
  124. uint32_t code;
  125. FT_Bitmap bitmap; ///< array holding bitmaps of font
  126. FT_BBox bbox;
  127. int advance;
  128. int bitmap_left;
  129. int bitmap_top;
  130. } Glyph;
  131. static int glyph_cmp(void *key, const void *b)
  132. {
  133. const Glyph *a = key, *bb = b;
  134. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  135. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  136. }
  137. /**
  138. * Load glyphs corresponding to the UTF-32 codepoint code.
  139. */
  140. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  141. {
  142. DrawTextContext *dtext = ctx->priv;
  143. Glyph *glyph;
  144. struct AVTreeNode *node = NULL;
  145. int ret;
  146. /* load glyph into dtext->face->glyph */
  147. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  148. return AVERROR(EINVAL);
  149. /* save glyph */
  150. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  151. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  152. ret = AVERROR(ENOMEM);
  153. goto error;
  154. }
  155. glyph->code = code;
  156. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  157. ret = AVERROR(EINVAL);
  158. goto error;
  159. }
  160. glyph->bitmap = dtext->face->glyph->bitmap;
  161. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  162. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  163. glyph->advance = dtext->face->glyph->advance.x >> 6;
  164. /* measure text height to calculate text_height (or the maximum text height) */
  165. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  166. /* cache the newly created glyph */
  167. if (!(node = av_mallocz(av_tree_node_size))) {
  168. ret = AVERROR(ENOMEM);
  169. goto error;
  170. }
  171. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  172. if (glyph_ptr)
  173. *glyph_ptr = glyph;
  174. return 0;
  175. error:
  176. if (glyph)
  177. av_freep(&glyph->glyph);
  178. av_freep(&glyph);
  179. av_freep(&node);
  180. return ret;
  181. }
  182. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  183. {
  184. int err;
  185. DrawTextContext *dtext = ctx->priv;
  186. Glyph *glyph;
  187. dtext->class = &drawtext_class;
  188. av_opt_set_defaults2(dtext, 0, 0);
  189. dtext->fontcolor_string = av_strdup("black");
  190. dtext->boxcolor_string = av_strdup("white");
  191. if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
  192. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  193. return err;
  194. }
  195. if (!dtext->fontfile) {
  196. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  197. return AVERROR(EINVAL);
  198. }
  199. if (dtext->textfile) {
  200. uint8_t *textbuf;
  201. size_t textbuf_size;
  202. if (dtext->text) {
  203. av_log(ctx, AV_LOG_ERROR,
  204. "Both text and text file provided. Please provide only one\n");
  205. return AVERROR(EINVAL);
  206. }
  207. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  208. av_log(ctx, AV_LOG_ERROR,
  209. "The text file '%s' could not be read or is empty\n",
  210. dtext->textfile);
  211. return err;
  212. }
  213. if (!(dtext->text = av_malloc(textbuf_size+1)))
  214. return AVERROR(ENOMEM);
  215. memcpy(dtext->text, textbuf, textbuf_size);
  216. dtext->text[textbuf_size] = 0;
  217. av_file_unmap(textbuf, textbuf_size);
  218. }
  219. if (!dtext->text) {
  220. av_log(ctx, AV_LOG_ERROR,
  221. "Either text or a valid file must be provided\n");
  222. return AVERROR(EINVAL);
  223. }
  224. if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
  225. av_log(ctx, AV_LOG_ERROR,
  226. "Invalid font color '%s'\n", dtext->fontcolor_string);
  227. return err;
  228. }
  229. if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
  230. av_log(ctx, AV_LOG_ERROR,
  231. "Invalid box color '%s'\n", dtext->boxcolor_string);
  232. return err;
  233. }
  234. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  235. av_log(ctx, AV_LOG_ERROR,
  236. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  237. return AVERROR(EINVAL);
  238. }
  239. /* load the face, and set up the encoding, which is by default UTF-8 */
  240. if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
  241. av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
  242. dtext->fontfile, FT_ERRMSG(err));
  243. return AVERROR(EINVAL);
  244. }
  245. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  246. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  247. dtext->fontsize, FT_ERRMSG(err));
  248. return AVERROR(EINVAL);
  249. }
  250. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  251. /* load the fallback glyph with code 0 */
  252. load_glyph(ctx, NULL, 0);
  253. /* set the tabsize in pixels */
  254. if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
  255. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  256. return err;
  257. }
  258. dtext->tabsize *= glyph->advance;
  259. #if !HAVE_LOCALTIME_R
  260. av_log(ctx, AV_LOG_WARNING, "strftime() expansion unavailable!\n");
  261. #endif
  262. return 0;
  263. }
  264. static int query_formats(AVFilterContext *ctx)
  265. {
  266. static const enum PixelFormat pix_fmts[] = {
  267. PIX_FMT_ARGB, PIX_FMT_RGBA,
  268. PIX_FMT_ABGR, PIX_FMT_BGRA,
  269. PIX_FMT_RGB24, PIX_FMT_BGR24,
  270. PIX_FMT_YUV420P, PIX_FMT_YUV444P,
  271. PIX_FMT_YUV422P, PIX_FMT_YUV411P,
  272. PIX_FMT_YUV410P, PIX_FMT_YUV440P,
  273. PIX_FMT_NONE
  274. };
  275. avfilter_set_common_formats(ctx, avfilter_make_format_list(pix_fmts));
  276. return 0;
  277. }
  278. static int glyph_enu_free(void *opaque, void *elem)
  279. {
  280. av_free(elem);
  281. return 0;
  282. }
  283. static av_cold void uninit(AVFilterContext *ctx)
  284. {
  285. DrawTextContext *dtext = ctx->priv;
  286. int i;
  287. av_freep(&dtext->fontfile);
  288. av_freep(&dtext->text);
  289. av_freep(&dtext->fontcolor_string);
  290. av_freep(&dtext->boxcolor_string);
  291. av_freep(&dtext->positions);
  292. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  293. av_tree_destroy(dtext->glyphs);
  294. dtext->glyphs = 0;
  295. FT_Done_Face(dtext->face);
  296. FT_Done_FreeType(dtext->library);
  297. for (i = 0; i < 4; i++) {
  298. av_freep(&dtext->box_line[i]);
  299. dtext->pixel_step[i] = 0;
  300. }
  301. }
  302. static int config_input(AVFilterLink *inlink)
  303. {
  304. DrawTextContext *dtext = inlink->dst->priv;
  305. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
  306. int ret;
  307. dtext->hsub = pix_desc->log2_chroma_w;
  308. dtext->vsub = pix_desc->log2_chroma_h;
  309. if ((ret =
  310. ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
  311. inlink->w, dtext->boxcolor,
  312. inlink->format, dtext->boxcolor_rgba,
  313. &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
  314. return ret;
  315. if (!dtext->is_packed_rgb) {
  316. uint8_t *rgba = dtext->fontcolor_rgba;
  317. dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  318. dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  319. dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  320. dtext->fontcolor[3] = rgba[3];
  321. }
  322. return 0;
  323. }
  324. #define GET_BITMAP_VAL(r, c) \
  325. bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
  326. (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
  327. bitmap->buffer[(r) * bitmap->pitch + (c)]
  328. #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
  329. luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
  330. alpha = yuva_color[3] * (val) * 129; \
  331. picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
  332. if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
  333. chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
  334. chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
  335. picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
  336. picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
  337. }\
  338. }
  339. static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
  340. unsigned int y, unsigned int width, unsigned int height,
  341. const uint8_t yuva_color[4], int hsub, int vsub)
  342. {
  343. int r, c, alpha;
  344. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  345. uint8_t src_val, dst_pixel[4];
  346. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  347. for (c = 0; c < bitmap->width && c+x < width; c++) {
  348. /* get pixel in the picref (destination) */
  349. dst_pixel[0] = picref->data[0][ c+x + (y+r) * picref->linesize[0]];
  350. dst_pixel[1] = picref->data[1][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[1]];
  351. dst_pixel[2] = picref->data[2][((c+x) >> hsub) + ((y+r) >> vsub) * picref->linesize[2]];
  352. /* get intensity value in the glyph bitmap (source) */
  353. src_val = GET_BITMAP_VAL(r, c);
  354. if (!src_val)
  355. continue;
  356. SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
  357. }
  358. }
  359. return 0;
  360. }
  361. #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
  362. p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
  363. alpha = rgba_color[3] * (val) * 129; \
  364. *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
  365. *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
  366. *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
  367. }
  368. static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
  369. unsigned int x, unsigned int y,
  370. unsigned int width, unsigned int height, int pixel_step,
  371. const uint8_t rgba_color[4], const uint8_t rgba_map[4])
  372. {
  373. int r, c, alpha;
  374. uint8_t *p;
  375. uint8_t src_val, dst_pixel[4];
  376. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  377. for (c = 0; c < bitmap->width && c+x < width; c++) {
  378. /* get pixel in the picref (destination) */
  379. dst_pixel[0] = picref->data[0][(c+x + rgba_map[0]) * pixel_step +
  380. (y+r) * picref->linesize[0]];
  381. dst_pixel[1] = picref->data[0][(c+x + rgba_map[1]) * pixel_step +
  382. (y+r) * picref->linesize[0]];
  383. dst_pixel[2] = picref->data[0][(c+x + rgba_map[2]) * pixel_step +
  384. (y+r) * picref->linesize[0]];
  385. /* get intensity value in the glyph bitmap (source) */
  386. src_val = GET_BITMAP_VAL(r, c);
  387. if (!src_val)
  388. continue;
  389. SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
  390. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  391. }
  392. }
  393. return 0;
  394. }
  395. static inline void drawbox(AVFilterBufferRef *picref, unsigned int x, unsigned int y,
  396. unsigned int width, unsigned int height,
  397. uint8_t *line[4], int pixel_step[4], uint8_t color[4],
  398. int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
  399. {
  400. int i, j, alpha;
  401. if (color[3] != 0xFF) {
  402. if (is_rgba_packed) {
  403. uint8_t *p;
  404. for (j = 0; j < height; j++)
  405. for (i = 0; i < width; i++)
  406. SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
  407. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  408. } else {
  409. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  410. for (j = 0; j < height; j++)
  411. for (i = 0; i < width; i++)
  412. SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
  413. }
  414. } else {
  415. ff_draw_rectangle(picref->data, picref->linesize,
  416. line, pixel_step, hsub, vsub,
  417. x, y, width, height);
  418. }
  419. }
  420. static inline int is_newline(uint32_t c)
  421. {
  422. return (c == '\n' || c == '\r' || c == '\f' || c == '\v');
  423. }
  424. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  425. int width, int height)
  426. {
  427. DrawTextContext *dtext = ctx->priv;
  428. uint32_t code = 0, prev_code = 0;
  429. int x = 0, y = 0, i = 0;
  430. int text_height, baseline;
  431. uint8_t *p;
  432. int str_w = 0;
  433. int y_min = 32000, y_max = -32000;
  434. FT_Vector delta;
  435. Glyph *glyph = NULL, *prev_glyph = NULL;
  436. Glyph dummy = { 0 };
  437. if (dtext->text != dtext->text_priv) {
  438. #if HAVE_LOCALTIME_R
  439. time_t now = time(0);
  440. struct tm ltime;
  441. uint8_t *buf = NULL;
  442. int buflen = 2*strlen(dtext->text) + 1, len;
  443. localtime_r(&now, &ltime);
  444. while ((buf = av_realloc(buf, buflen))) {
  445. *buf = 1;
  446. if ((len = strftime(buf, buflen, dtext->text, &ltime)) != 0 || *buf == 0)
  447. break;
  448. buflen *= 2;
  449. }
  450. if (!buf)
  451. return AVERROR(ENOMEM);
  452. av_freep(&dtext->text);
  453. dtext->text = dtext->text_priv = buf;
  454. #else
  455. dtext->text_priv = dtext->text;
  456. #endif
  457. if (!(dtext->positions = av_realloc(dtext->positions,
  458. strlen(dtext->text)*sizeof(*dtext->positions))))
  459. return AVERROR(ENOMEM);
  460. }
  461. x = dtext->x;
  462. y = dtext->y;
  463. /* load and cache glyphs */
  464. for (i = 0, p = dtext->text; *p; i++) {
  465. GET_UTF8(code, *p++, continue;);
  466. /* get glyph */
  467. dummy.code = code;
  468. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  469. if (!glyph)
  470. load_glyph(ctx, &glyph, code);
  471. y_min = FFMIN(glyph->bbox.yMin, y_min);
  472. y_max = FFMAX(glyph->bbox.yMax, y_max);
  473. }
  474. text_height = y_max - y_min;
  475. baseline = y_max;
  476. /* compute and save position for each glyph */
  477. glyph = NULL;
  478. for (i = 0, p = dtext->text; *p; i++) {
  479. GET_UTF8(code, *p++, continue;);
  480. /* skip the \n in the sequence \r\n */
  481. if (prev_code == '\r' && code == '\n')
  482. continue;
  483. prev_code = code;
  484. if (is_newline(code)) {
  485. str_w = FFMAX(str_w, x - dtext->x);
  486. y += text_height;
  487. x = dtext->x;
  488. continue;
  489. }
  490. /* get glyph */
  491. prev_glyph = glyph;
  492. dummy.code = code;
  493. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  494. /* kerning */
  495. if (dtext->use_kerning && prev_glyph && glyph->code) {
  496. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  497. ft_kerning_default, &delta);
  498. x += delta.x >> 6;
  499. }
  500. if (x + glyph->bbox.xMax >= width) {
  501. str_w = FFMAX(str_w, x - dtext->x);
  502. y += text_height;
  503. x = dtext->x;
  504. }
  505. /* save position */
  506. dtext->positions[i].x = x + glyph->bitmap_left;
  507. dtext->positions[i].y = y - glyph->bitmap_top + baseline;
  508. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  509. else x += glyph->advance;
  510. }
  511. str_w = FFMIN(width - dtext->x - 1, FFMAX(str_w, x - dtext->x));
  512. y = FFMIN(y + text_height, height - 1);
  513. /* draw box */
  514. if (dtext->draw_box)
  515. drawbox(picref, dtext->x, dtext->y, str_w, y-dtext->y,
  516. dtext->box_line, dtext->pixel_step, dtext->boxcolor,
  517. dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
  518. /* draw glyphs */
  519. for (i = 0, p = dtext->text; *p; i++) {
  520. Glyph dummy = { 0 };
  521. GET_UTF8(code, *p++, continue;);
  522. /* skip new line chars, just go to new line */
  523. if (is_newline(code) || code == ' ' || code == '\t')
  524. continue;
  525. dummy.code = code;
  526. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  527. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  528. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  529. return AVERROR(EINVAL);
  530. if (dtext->is_packed_rgb) {
  531. draw_glyph_rgb(picref, &glyph->bitmap,
  532. dtext->positions[i].x, dtext->positions[i].y, width, height,
  533. dtext->pixel_step[0], dtext->fontcolor_rgba, dtext->rgba_map);
  534. } else {
  535. draw_glyph_yuv(picref, &glyph->bitmap,
  536. dtext->positions[i].x, dtext->positions[i].y, width, height,
  537. dtext->fontcolor, dtext->hsub, dtext->vsub);
  538. }
  539. }
  540. return 0;
  541. }
  542. static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
  543. static void end_frame(AVFilterLink *inlink)
  544. {
  545. AVFilterLink *outlink = inlink->dst->outputs[0];
  546. AVFilterBufferRef *picref = inlink->cur_buf;
  547. draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
  548. avfilter_draw_slice(outlink, 0, picref->video->h, 1);
  549. avfilter_end_frame(outlink);
  550. }
  551. AVFilter avfilter_vf_drawtext = {
  552. .name = "drawtext",
  553. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  554. .priv_size = sizeof(DrawTextContext),
  555. .init = init,
  556. .uninit = uninit,
  557. .query_formats = query_formats,
  558. .inputs = (AVFilterPad[]) {{ .name = "default",
  559. .type = AVMEDIA_TYPE_VIDEO,
  560. .get_video_buffer = avfilter_null_get_video_buffer,
  561. .start_frame = avfilter_null_start_frame,
  562. .draw_slice = null_draw_slice,
  563. .end_frame = end_frame,
  564. .config_props = config_input,
  565. .min_perms = AV_PERM_WRITE |
  566. AV_PERM_READ,
  567. .rej_perms = AV_PERM_PRESERVE },
  568. { .name = NULL}},
  569. .outputs = (AVFilterPad[]) {{ .name = "default",
  570. .type = AVMEDIA_TYPE_VIDEO, },
  571. { .name = NULL}},
  572. };