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.

651 lines
25KB

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