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.

691 lines
27KB

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