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.

731 lines
28KB

  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. int64_t basetime; ///< base pts time in the real world for display
  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, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  81. {"text", "set text", OFFSET(text), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  82. {"textfile", "set text file", OFFSET(textfile), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  83. {"fontcolor","set foreground color", OFFSET(fontcolor_string), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  84. {"boxcolor", "set box color", OFFSET(boxcolor_string), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  85. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), FF_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  86. {"box", "set box", OFFSET(draw_box), FF_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  87. {"fontsize", "set font size", OFFSET(fontsize), FF_OPT_TYPE_INT, {.dbl=16}, 1, 72 },
  88. {"x", "set x", OFFSET(x), FF_OPT_TYPE_INT, {.dbl=0}, 0, INT_MAX },
  89. {"y", "set y", OFFSET(y), FF_OPT_TYPE_INT, {.dbl=0}, 0, INT_MAX },
  90. {"shadowx", "set x", OFFSET(shadowx), FF_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  91. {"shadowy", "set y", OFFSET(shadowy), FF_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  92. {"tabsize", "set tab size", OFFSET(tabsize), FF_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
  93. {"basetime", "set base time", OFFSET(basetime), FF_OPT_TYPE_INT64, {.dbl=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX },
  94. /* FT_LOAD_* flags */
  95. {"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" },
  96. {"default", "set default", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  97. {"no_scale", "set no_scale", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  98. {"no_hinting", "set no_hinting", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  99. {"render", "set render", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  100. {"no_bitmap", "set no_bitmap", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  101. {"vertical_layout", "set vertical_layout", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  102. {"force_autohint", "set force_autohint", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  103. {"crop_bitmap", "set crop_bitmap", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  104. {"pedantic", "set pedantic", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  105. {"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" },
  106. {"no_recurse", "set no_recurse", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  107. {"ignore_transform", "set ignore_transform", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  108. {"monochrome", "set monochrome", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  109. {"linear_design", "set linear_design", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  110. {"no_autohint", "set no_autohint", 0, FF_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  111. {NULL},
  112. };
  113. static const char *drawtext_get_name(void *ctx)
  114. {
  115. return "drawtext";
  116. }
  117. static const AVClass drawtext_class = {
  118. "DrawTextContext",
  119. drawtext_get_name,
  120. drawtext_options
  121. };
  122. #undef __FTERRORS_H__
  123. #define FT_ERROR_START_LIST {
  124. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  125. #define FT_ERROR_END_LIST { 0, NULL } };
  126. struct ft_error
  127. {
  128. int err;
  129. const char *err_msg;
  130. } static ft_errors[] =
  131. #include FT_ERRORS_H
  132. #define FT_ERRMSG(e) ft_errors[e].err_msg
  133. typedef struct {
  134. FT_Glyph *glyph;
  135. uint32_t code;
  136. FT_Bitmap bitmap; ///< array holding bitmaps of font
  137. FT_BBox bbox;
  138. int advance;
  139. int bitmap_left;
  140. int bitmap_top;
  141. } Glyph;
  142. static int glyph_cmp(void *key, const void *b)
  143. {
  144. const Glyph *a = key, *bb = b;
  145. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  146. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  147. }
  148. /**
  149. * Load glyphs corresponding to the UTF-32 codepoint code.
  150. */
  151. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  152. {
  153. DrawTextContext *dtext = ctx->priv;
  154. Glyph *glyph;
  155. struct AVTreeNode *node = NULL;
  156. int ret;
  157. /* load glyph into dtext->face->glyph */
  158. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  159. return AVERROR(EINVAL);
  160. /* save glyph */
  161. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  162. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  163. ret = AVERROR(ENOMEM);
  164. goto error;
  165. }
  166. glyph->code = code;
  167. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  168. ret = AVERROR(EINVAL);
  169. goto error;
  170. }
  171. glyph->bitmap = dtext->face->glyph->bitmap;
  172. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  173. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  174. glyph->advance = dtext->face->glyph->advance.x >> 6;
  175. /* measure text height to calculate text_height (or the maximum text height) */
  176. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  177. /* cache the newly created glyph */
  178. if (!(node = av_mallocz(av_tree_node_size))) {
  179. ret = AVERROR(ENOMEM);
  180. goto error;
  181. }
  182. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  183. if (glyph_ptr)
  184. *glyph_ptr = glyph;
  185. return 0;
  186. error:
  187. if (glyph)
  188. av_freep(&glyph->glyph);
  189. av_freep(&glyph);
  190. av_freep(&node);
  191. return ret;
  192. }
  193. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  194. {
  195. int err;
  196. DrawTextContext *dtext = ctx->priv;
  197. Glyph *glyph;
  198. dtext->class = &drawtext_class;
  199. av_opt_set_defaults(dtext);
  200. dtext->fontcolor_string = av_strdup("black");
  201. dtext->boxcolor_string = av_strdup("white");
  202. dtext->shadowcolor_string = av_strdup("black");
  203. if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
  204. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  205. return err;
  206. }
  207. if (!dtext->fontfile) {
  208. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  209. return AVERROR(EINVAL);
  210. }
  211. if (dtext->textfile) {
  212. uint8_t *textbuf;
  213. size_t textbuf_size;
  214. if (dtext->text) {
  215. av_log(ctx, AV_LOG_ERROR,
  216. "Both text and text file provided. Please provide only one\n");
  217. return AVERROR(EINVAL);
  218. }
  219. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  220. av_log(ctx, AV_LOG_ERROR,
  221. "The text file '%s' could not be read or is empty\n",
  222. dtext->textfile);
  223. return err;
  224. }
  225. if (!(dtext->text = av_malloc(textbuf_size+1)))
  226. return AVERROR(ENOMEM);
  227. memcpy(dtext->text, textbuf, textbuf_size);
  228. dtext->text[textbuf_size] = 0;
  229. av_file_unmap(textbuf, textbuf_size);
  230. }
  231. if (!dtext->text) {
  232. av_log(ctx, AV_LOG_ERROR,
  233. "Either text or a valid file must be provided\n");
  234. return AVERROR(EINVAL);
  235. }
  236. if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
  237. av_log(ctx, AV_LOG_ERROR,
  238. "Invalid font color '%s'\n", dtext->fontcolor_string);
  239. return err;
  240. }
  241. if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
  242. av_log(ctx, AV_LOG_ERROR,
  243. "Invalid box color '%s'\n", dtext->boxcolor_string);
  244. return err;
  245. }
  246. if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
  247. av_log(ctx, AV_LOG_ERROR,
  248. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  249. return err;
  250. }
  251. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  252. av_log(ctx, AV_LOG_ERROR,
  253. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  254. return AVERROR(EINVAL);
  255. }
  256. /* load the face, and set up the encoding, which is by default UTF-8 */
  257. if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
  258. av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
  259. dtext->fontfile, FT_ERRMSG(err));
  260. return AVERROR(EINVAL);
  261. }
  262. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  263. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  264. dtext->fontsize, FT_ERRMSG(err));
  265. return AVERROR(EINVAL);
  266. }
  267. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  268. /* load the fallback glyph with code 0 */
  269. load_glyph(ctx, NULL, 0);
  270. /* set the tabsize in pixels */
  271. if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
  272. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  273. return err;
  274. }
  275. dtext->tabsize *= glyph->advance;
  276. return 0;
  277. }
  278. static int query_formats(AVFilterContext *ctx)
  279. {
  280. static const enum PixelFormat pix_fmts[] = {
  281. PIX_FMT_ARGB, PIX_FMT_RGBA,
  282. PIX_FMT_ABGR, PIX_FMT_BGRA,
  283. PIX_FMT_RGB24, PIX_FMT_BGR24,
  284. PIX_FMT_YUV420P, PIX_FMT_YUV444P,
  285. PIX_FMT_YUV422P, PIX_FMT_YUV411P,
  286. PIX_FMT_YUV410P, PIX_FMT_YUV440P,
  287. PIX_FMT_NONE
  288. };
  289. avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
  290. return 0;
  291. }
  292. static int glyph_enu_free(void *opaque, void *elem)
  293. {
  294. av_free(elem);
  295. return 0;
  296. }
  297. static av_cold void uninit(AVFilterContext *ctx)
  298. {
  299. DrawTextContext *dtext = ctx->priv;
  300. int i;
  301. av_freep(&dtext->fontfile);
  302. av_freep(&dtext->text);
  303. av_freep(&dtext->expanded_text);
  304. av_freep(&dtext->fontcolor_string);
  305. av_freep(&dtext->boxcolor_string);
  306. av_freep(&dtext->positions);
  307. dtext->nb_positions = 0;
  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. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  347. {
  348. if(!strcmp(cmd, "reinit")){
  349. int ret;
  350. uninit(ctx);
  351. if((ret=init(ctx, arg, NULL)) < 0)
  352. return ret;
  353. return config_input(ctx->inputs[0]);
  354. }
  355. return AVERROR(ENOSYS);
  356. }
  357. #define GET_BITMAP_VAL(r, c) \
  358. bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
  359. (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
  360. bitmap->buffer[(r) * bitmap->pitch + (c)]
  361. #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
  362. luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
  363. alpha = yuva_color[3] * (val) * 129; \
  364. picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
  365. if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
  366. chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
  367. chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
  368. picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
  369. picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
  370. }\
  371. }
  372. static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap, unsigned int x,
  373. unsigned int y, unsigned int width, unsigned int height,
  374. const uint8_t yuva_color[4], int hsub, int vsub)
  375. {
  376. int r, c, alpha;
  377. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  378. uint8_t src_val;
  379. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  380. for (c = 0; c < bitmap->width && c+x < width; c++) {
  381. /* get intensity value in the glyph bitmap (source) */
  382. src_val = GET_BITMAP_VAL(r, c);
  383. if (!src_val)
  384. continue;
  385. SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
  386. }
  387. }
  388. return 0;
  389. }
  390. #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
  391. p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
  392. alpha = rgba_color[3] * (val) * 129; \
  393. *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
  394. *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
  395. *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
  396. }
  397. static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
  398. unsigned int x, unsigned int y,
  399. unsigned int width, unsigned int height, int pixel_step,
  400. const uint8_t rgba_color[4], const uint8_t rgba_map[4])
  401. {
  402. int r, c, alpha;
  403. uint8_t *p;
  404. uint8_t src_val;
  405. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  406. for (c = 0; c < bitmap->width && c+x < width; c++) {
  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 = dtext->expanded_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. time_t now = time(0);
  492. struct tm ltime;
  493. uint8_t *buf = dtext->expanded_text;
  494. int buf_size = dtext->expanded_text_size;
  495. if(dtext->basetime != AV_NOPTS_VALUE)
  496. now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  497. if (!buf) {
  498. buf_size = 2*strlen(dtext->text)+1;
  499. buf = av_malloc(buf_size);
  500. }
  501. #if HAVE_LOCALTIME_R
  502. localtime_r(&now, &ltime);
  503. #else
  504. if(strchr(dtext->text, '%'))
  505. ltime= *localtime(&now);
  506. #endif
  507. do {
  508. *buf = 1;
  509. if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
  510. break;
  511. buf_size *= 2;
  512. } while ((buf = av_realloc(buf, buf_size)));
  513. if (!buf)
  514. return AVERROR(ENOMEM);
  515. text = dtext->expanded_text = buf;
  516. dtext->expanded_text_size = buf_size;
  517. if ((len = strlen(text)) > dtext->nb_positions) {
  518. if (!(dtext->positions =
  519. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  520. return AVERROR(ENOMEM);
  521. dtext->nb_positions = len;
  522. }
  523. x = dtext->x;
  524. y = dtext->y;
  525. /* load and cache glyphs */
  526. for (i = 0, p = text; *p; i++) {
  527. GET_UTF8(code, *p++, continue;);
  528. /* get glyph */
  529. dummy.code = code;
  530. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  531. if (!glyph)
  532. load_glyph(ctx, &glyph, code);
  533. y_min = FFMIN(glyph->bbox.yMin, y_min);
  534. y_max = FFMAX(glyph->bbox.yMax, y_max);
  535. }
  536. text_height = y_max - y_min;
  537. baseline = y_max;
  538. /* compute and save position for each glyph */
  539. glyph = NULL;
  540. for (i = 0, p = text; *p; i++) {
  541. GET_UTF8(code, *p++, continue;);
  542. /* skip the \n in the sequence \r\n */
  543. if (prev_code == '\r' && code == '\n')
  544. continue;
  545. prev_code = code;
  546. if (is_newline(code)) {
  547. str_w = FFMAX(str_w, x - dtext->x);
  548. y += text_height;
  549. x = dtext->x;
  550. continue;
  551. }
  552. /* get glyph */
  553. prev_glyph = glyph;
  554. dummy.code = code;
  555. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  556. /* kerning */
  557. if (dtext->use_kerning && prev_glyph && glyph->code) {
  558. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  559. ft_kerning_default, &delta);
  560. x += delta.x >> 6;
  561. }
  562. if (x + glyph->bbox.xMax >= width) {
  563. str_w = FFMAX(str_w, x - dtext->x);
  564. y += text_height;
  565. x = dtext->x;
  566. }
  567. /* save position */
  568. dtext->positions[i].x = x + glyph->bitmap_left;
  569. dtext->positions[i].y = y - glyph->bitmap_top + baseline;
  570. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  571. else x += glyph->advance;
  572. }
  573. str_w = FFMIN(width - dtext->x - 1, FFMAX(str_w, x - dtext->x));
  574. y = FFMIN(y + text_height, height - 1);
  575. /* draw box */
  576. if (dtext->draw_box)
  577. drawbox(picref, dtext->x, dtext->y, str_w, y-dtext->y,
  578. dtext->box_line, dtext->pixel_step, dtext->boxcolor,
  579. dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
  580. if (dtext->shadowx || dtext->shadowy) {
  581. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor_rgba,
  582. dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  583. return ret;
  584. }
  585. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor_rgba,
  586. dtext->fontcolor, 0, 0)) < 0)
  587. return ret;
  588. return 0;
  589. }
  590. static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
  591. static void end_frame(AVFilterLink *inlink)
  592. {
  593. AVFilterLink *outlink = inlink->dst->outputs[0];
  594. AVFilterBufferRef *picref = inlink->cur_buf;
  595. draw_text(inlink->dst, picref, picref->video->w, picref->video->h);
  596. avfilter_draw_slice(outlink, 0, picref->video->h, 1);
  597. avfilter_end_frame(outlink);
  598. }
  599. AVFilter avfilter_vf_drawtext = {
  600. .name = "drawtext",
  601. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  602. .priv_size = sizeof(DrawTextContext),
  603. .init = init,
  604. .uninit = uninit,
  605. .query_formats = query_formats,
  606. .inputs = (AVFilterPad[]) {{ .name = "default",
  607. .type = AVMEDIA_TYPE_VIDEO,
  608. .get_video_buffer = avfilter_null_get_video_buffer,
  609. .start_frame = avfilter_null_start_frame,
  610. .draw_slice = null_draw_slice,
  611. .end_frame = end_frame,
  612. .config_props = config_input,
  613. .min_perms = AV_PERM_WRITE |
  614. AV_PERM_READ,
  615. .rej_perms = AV_PERM_PRESERVE },
  616. { .name = NULL}},
  617. .outputs = (AVFilterPad[]) {{ .name = "default",
  618. .type = AVMEDIA_TYPE_VIDEO, },
  619. { .name = NULL}},
  620. .process_command = command,
  621. };