vf_drawtext.c 28 KB

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