vf_drawtext.c 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  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 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/eval.h"
  31. #include "libavutil/file.h"
  32. #include "libavutil/opt.h"
  33. #include "libavutil/parseutils.h"
  34. #include "libavutil/pixdesc.h"
  35. #include "libavutil/tree.h"
  36. #include "avfilter.h"
  37. #include "drawutils.h"
  38. #undef time
  39. #include <ft2build.h>
  40. #include <freetype/config/ftheader.h>
  41. #include FT_FREETYPE_H
  42. #include FT_GLYPH_H
  43. static const char *var_names[] = {
  44. "w", ///< width of the input video
  45. "h", ///< height of the input video
  46. "tw", "text_w", ///< width of the rendered text
  47. "th", "text_h", ///< height of the rendered text
  48. "max_glyph_w", ///< max glyph width
  49. "max_glyph_h", ///< max glyph height
  50. "max_glyph_a", "ascent", ///< max glyph ascent
  51. "max_glyph_d", "descent", ///< min glyph descent
  52. "line_h", "lh", ///< line height, same as max_glyph_h
  53. "sar",
  54. "dar",
  55. "hsub",
  56. "vsub",
  57. "x",
  58. "y",
  59. "n", ///< number of frame
  60. "t", ///< timestamp expressed in seconds
  61. NULL
  62. };
  63. enum var_name {
  64. VAR_W,
  65. VAR_H,
  66. VAR_TW, VAR_TEXT_W,
  67. VAR_TH, VAR_TEXT_H,
  68. VAR_MAX_GLYPH_W,
  69. VAR_MAX_GLYPH_H,
  70. VAR_MAX_GLYPH_A, VAR_ASCENT,
  71. VAR_MAX_GLYPH_D, VAR_DESCENT,
  72. VAR_LINE_H, VAR_LH,
  73. VAR_SAR,
  74. VAR_DAR,
  75. VAR_HSUB,
  76. VAR_VSUB,
  77. VAR_X,
  78. VAR_Y,
  79. VAR_N,
  80. VAR_T,
  81. VAR_VARS_NB
  82. };
  83. typedef struct {
  84. const AVClass *class;
  85. int reinit; ///< tells if the filter is being reinited
  86. uint8_t *fontfile; ///< font to be used
  87. uint8_t *text; ///< text to be drawn
  88. uint8_t *expanded_text; ///< used to contain the strftime()-expanded text
  89. size_t expanded_text_size; ///< size in bytes of the expanded_text buffer
  90. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  91. FT_Vector *positions; ///< positions for each element in the text
  92. size_t nb_positions; ///< number of elements of positions array
  93. char *textfile; ///< file with text to be drawn
  94. int x; ///< x position to start drawing text
  95. int y; ///< y position to start drawing text
  96. char *x_expr; ///< expression for x position
  97. char *y_expr; ///< expression for y position
  98. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  99. int max_glyph_w; ///< max glyph width
  100. int max_glyph_h; ///< max glyph heigth
  101. int shadowx, shadowy;
  102. unsigned int fontsize; ///< font size to use
  103. char *fontcolor_string; ///< font color as string
  104. char *boxcolor_string; ///< box color as string
  105. char *shadowcolor_string; ///< shadow color as string
  106. uint8_t fontcolor[4]; ///< foreground color
  107. uint8_t boxcolor[4]; ///< background color
  108. uint8_t shadowcolor[4]; ///< shadow color
  109. uint8_t fontcolor_rgba[4]; ///< foreground color in RGBA
  110. uint8_t boxcolor_rgba[4]; ///< background color in RGBA
  111. uint8_t shadowcolor_rgba[4]; ///< shadow color in RGBA
  112. short int draw_box; ///< draw box around text - true or false
  113. int use_kerning; ///< font kerning is used - true/false
  114. int tabsize; ///< tab size
  115. FT_Library library; ///< freetype font library handle
  116. FT_Face face; ///< freetype font face handle
  117. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  118. int hsub, vsub; ///< chroma subsampling values
  119. int is_packed_rgb;
  120. int pixel_step[4]; ///< distance in bytes between the component of each pixel
  121. uint8_t rgba_map[4]; ///< map RGBA offsets to the positions in the packed RGBA format
  122. uint8_t *box_line[4]; ///< line used for filling the box background
  123. int64_t basetime; ///< base pts time in the real world for display
  124. double var_values[VAR_VARS_NB];
  125. } DrawTextContext;
  126. #define OFFSET(x) offsetof(DrawTextContext, x)
  127. static const AVOption drawtext_options[]= {
  128. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  129. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  130. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX },
  131. {"fontcolor", "set foreground color", OFFSET(fontcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
  132. {"boxcolor", "set box color", OFFSET(boxcolor_string), AV_OPT_TYPE_STRING, {.str="white"}, CHAR_MIN, CHAR_MAX },
  133. {"shadowcolor", "set shadow color", OFFSET(shadowcolor_string), AV_OPT_TYPE_STRING, {.str="black"}, CHAR_MIN, CHAR_MAX },
  134. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_INT, {.dbl=0}, 0, 1 },
  135. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.dbl=16}, 1, INT_MAX },
  136. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
  137. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX },
  138. {"shadowx", "set x", OFFSET(shadowx), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  139. {"shadowy", "set y", OFFSET(shadowy), AV_OPT_TYPE_INT, {.dbl=0}, INT_MIN, INT_MAX },
  140. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.dbl=4}, 0, INT_MAX },
  141. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.dbl=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX },
  142. /* FT_LOAD_* flags */
  143. {"ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, {.dbl=FT_LOAD_DEFAULT|FT_LOAD_RENDER}, 0, INT_MAX, 0, "ft_load_flags" },
  144. {"default", "set default", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_DEFAULT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  145. {"no_scale", "set no_scale", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_SCALE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  146. {"no_hinting", "set no_hinting", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_HINTING}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  147. {"render", "set render", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_RENDER}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  148. {"no_bitmap", "set no_bitmap", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  149. {"vertical_layout", "set vertical_layout", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_VERTICAL_LAYOUT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  150. {"force_autohint", "set force_autohint", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_FORCE_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  151. {"crop_bitmap", "set crop_bitmap", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_CROP_BITMAP}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  152. {"pedantic", "set pedantic", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_PEDANTIC}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  153. {"ignore_global_advance_width", "set ignore_global_advance_width", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  154. {"no_recurse", "set no_recurse", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_RECURSE}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  155. {"ignore_transform", "set ignore_transform", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_IGNORE_TRANSFORM}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  156. {"monochrome", "set monochrome", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_MONOCHROME}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  157. {"linear_design", "set linear_design", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_LINEAR_DESIGN}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  158. {"no_autohint", "set no_autohint", 0, AV_OPT_TYPE_CONST, {.dbl=FT_LOAD_NO_AUTOHINT}, INT_MIN, INT_MAX, 0, "ft_load_flags" },
  159. {NULL},
  160. };
  161. static const char *drawtext_get_name(void *ctx)
  162. {
  163. return "drawtext";
  164. }
  165. static const AVClass drawtext_class = {
  166. "DrawTextContext",
  167. drawtext_get_name,
  168. drawtext_options
  169. };
  170. #undef __FTERRORS_H__
  171. #define FT_ERROR_START_LIST {
  172. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  173. #define FT_ERROR_END_LIST { 0, NULL } };
  174. struct ft_error
  175. {
  176. int err;
  177. const char *err_msg;
  178. } static ft_errors[] =
  179. #include FT_ERRORS_H
  180. #define FT_ERRMSG(e) ft_errors[e].err_msg
  181. typedef struct {
  182. FT_Glyph *glyph;
  183. uint32_t code;
  184. FT_Bitmap bitmap; ///< array holding bitmaps of font
  185. FT_BBox bbox;
  186. int advance;
  187. int bitmap_left;
  188. int bitmap_top;
  189. } Glyph;
  190. static int glyph_cmp(void *key, const void *b)
  191. {
  192. const Glyph *a = key, *bb = b;
  193. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  194. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  195. }
  196. /**
  197. * Load glyphs corresponding to the UTF-32 codepoint code.
  198. */
  199. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  200. {
  201. DrawTextContext *dtext = ctx->priv;
  202. Glyph *glyph;
  203. struct AVTreeNode *node = NULL;
  204. int ret;
  205. /* load glyph into dtext->face->glyph */
  206. if (FT_Load_Char(dtext->face, code, dtext->ft_load_flags))
  207. return AVERROR(EINVAL);
  208. /* save glyph */
  209. if (!(glyph = av_mallocz(sizeof(*glyph))) ||
  210. !(glyph->glyph = av_mallocz(sizeof(*glyph->glyph)))) {
  211. ret = AVERROR(ENOMEM);
  212. goto error;
  213. }
  214. glyph->code = code;
  215. if (FT_Get_Glyph(dtext->face->glyph, glyph->glyph)) {
  216. ret = AVERROR(EINVAL);
  217. goto error;
  218. }
  219. glyph->bitmap = dtext->face->glyph->bitmap;
  220. glyph->bitmap_left = dtext->face->glyph->bitmap_left;
  221. glyph->bitmap_top = dtext->face->glyph->bitmap_top;
  222. glyph->advance = dtext->face->glyph->advance.x >> 6;
  223. /* measure text height to calculate text_height (or the maximum text height) */
  224. FT_Glyph_Get_CBox(*glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  225. /* cache the newly created glyph */
  226. if (!(node = av_mallocz(av_tree_node_size))) {
  227. ret = AVERROR(ENOMEM);
  228. goto error;
  229. }
  230. av_tree_insert(&dtext->glyphs, glyph, glyph_cmp, &node);
  231. if (glyph_ptr)
  232. *glyph_ptr = glyph;
  233. return 0;
  234. error:
  235. if (glyph)
  236. av_freep(&glyph->glyph);
  237. av_freep(&glyph);
  238. av_freep(&node);
  239. return ret;
  240. }
  241. static av_cold int init(AVFilterContext *ctx, const char *args, void *opaque)
  242. {
  243. int err;
  244. DrawTextContext *dtext = ctx->priv;
  245. Glyph *glyph;
  246. dtext->class = &drawtext_class;
  247. av_opt_set_defaults(dtext);
  248. if ((err = (av_set_options_string(dtext, args, "=", ":"))) < 0) {
  249. av_log(ctx, AV_LOG_ERROR, "Error parsing options string: '%s'\n", args);
  250. return err;
  251. }
  252. if (!dtext->fontfile) {
  253. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  254. return AVERROR(EINVAL);
  255. }
  256. if (dtext->textfile) {
  257. uint8_t *textbuf;
  258. size_t textbuf_size;
  259. if (dtext->text) {
  260. av_log(ctx, AV_LOG_ERROR,
  261. "Both text and text file provided. Please provide only one\n");
  262. return AVERROR(EINVAL);
  263. }
  264. if ((err = av_file_map(dtext->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  265. av_log(ctx, AV_LOG_ERROR,
  266. "The text file '%s' could not be read or is empty\n",
  267. dtext->textfile);
  268. return err;
  269. }
  270. if (!(dtext->text = av_malloc(textbuf_size+1)))
  271. return AVERROR(ENOMEM);
  272. memcpy(dtext->text, textbuf, textbuf_size);
  273. dtext->text[textbuf_size] = 0;
  274. av_file_unmap(textbuf, textbuf_size);
  275. }
  276. if (!dtext->text) {
  277. av_log(ctx, AV_LOG_ERROR,
  278. "Either text or a valid file must be provided\n");
  279. return AVERROR(EINVAL);
  280. }
  281. if ((err = av_parse_color(dtext->fontcolor_rgba, dtext->fontcolor_string, -1, ctx))) {
  282. av_log(ctx, AV_LOG_ERROR,
  283. "Invalid font color '%s'\n", dtext->fontcolor_string);
  284. return err;
  285. }
  286. if ((err = av_parse_color(dtext->boxcolor_rgba, dtext->boxcolor_string, -1, ctx))) {
  287. av_log(ctx, AV_LOG_ERROR,
  288. "Invalid box color '%s'\n", dtext->boxcolor_string);
  289. return err;
  290. }
  291. if ((err = av_parse_color(dtext->shadowcolor_rgba, dtext->shadowcolor_string, -1, ctx))) {
  292. av_log(ctx, AV_LOG_ERROR,
  293. "Invalid shadow color '%s'\n", dtext->shadowcolor_string);
  294. return err;
  295. }
  296. if ((err = FT_Init_FreeType(&(dtext->library)))) {
  297. av_log(ctx, AV_LOG_ERROR,
  298. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  299. return AVERROR(EINVAL);
  300. }
  301. /* load the face, and set up the encoding, which is by default UTF-8 */
  302. if ((err = FT_New_Face(dtext->library, dtext->fontfile, 0, &dtext->face))) {
  303. av_log(ctx, AV_LOG_ERROR, "Could not load fontface from file '%s': %s\n",
  304. dtext->fontfile, FT_ERRMSG(err));
  305. return AVERROR(EINVAL);
  306. }
  307. if ((err = FT_Set_Pixel_Sizes(dtext->face, 0, dtext->fontsize))) {
  308. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  309. dtext->fontsize, FT_ERRMSG(err));
  310. return AVERROR(EINVAL);
  311. }
  312. dtext->use_kerning = FT_HAS_KERNING(dtext->face);
  313. /* load the fallback glyph with code 0 */
  314. load_glyph(ctx, NULL, 0);
  315. /* set the tabsize in pixels */
  316. if ((err = load_glyph(ctx, &glyph, ' ') < 0)) {
  317. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  318. return err;
  319. }
  320. dtext->tabsize *= glyph->advance;
  321. return 0;
  322. }
  323. static int query_formats(AVFilterContext *ctx)
  324. {
  325. static const enum PixelFormat pix_fmts[] = {
  326. PIX_FMT_ARGB, PIX_FMT_RGBA,
  327. PIX_FMT_ABGR, PIX_FMT_BGRA,
  328. PIX_FMT_RGB24, PIX_FMT_BGR24,
  329. PIX_FMT_YUV420P, PIX_FMT_YUV444P,
  330. PIX_FMT_YUV422P, PIX_FMT_YUV411P,
  331. PIX_FMT_YUV410P, PIX_FMT_YUV440P,
  332. PIX_FMT_NONE
  333. };
  334. avfilter_set_common_pixel_formats(ctx, avfilter_make_format_list(pix_fmts));
  335. return 0;
  336. }
  337. static int glyph_enu_free(void *opaque, void *elem)
  338. {
  339. av_free(elem);
  340. return 0;
  341. }
  342. static av_cold void uninit(AVFilterContext *ctx)
  343. {
  344. DrawTextContext *dtext = ctx->priv;
  345. int i;
  346. av_expr_free(dtext->x_pexpr); dtext->x_pexpr = NULL;
  347. av_expr_free(dtext->y_pexpr); dtext->y_pexpr = NULL;
  348. av_freep(&dtext->boxcolor_string);
  349. av_freep(&dtext->expanded_text);
  350. av_freep(&dtext->fontcolor_string);
  351. av_freep(&dtext->fontfile);
  352. av_freep(&dtext->shadowcolor_string);
  353. av_freep(&dtext->text);
  354. av_freep(&dtext->x_expr);
  355. av_freep(&dtext->y_expr);
  356. av_freep(&dtext->positions);
  357. dtext->nb_positions = 0;
  358. av_tree_enumerate(dtext->glyphs, NULL, NULL, glyph_enu_free);
  359. av_tree_destroy(dtext->glyphs);
  360. dtext->glyphs = NULL;
  361. FT_Done_Face(dtext->face);
  362. FT_Done_FreeType(dtext->library);
  363. for (i = 0; i < 4; i++) {
  364. av_freep(&dtext->box_line[i]);
  365. dtext->pixel_step[i] = 0;
  366. }
  367. }
  368. static int config_input(AVFilterLink *inlink)
  369. {
  370. AVFilterContext *ctx = inlink->dst;
  371. DrawTextContext *dtext = inlink->dst->priv;
  372. const AVPixFmtDescriptor *pix_desc = &av_pix_fmt_descriptors[inlink->format];
  373. int ret;
  374. dtext->hsub = pix_desc->log2_chroma_w;
  375. dtext->vsub = pix_desc->log2_chroma_h;
  376. if ((ret =
  377. ff_fill_line_with_color(dtext->box_line, dtext->pixel_step,
  378. inlink->w, dtext->boxcolor,
  379. inlink->format, dtext->boxcolor_rgba,
  380. &dtext->is_packed_rgb, dtext->rgba_map)) < 0)
  381. return ret;
  382. if (!dtext->is_packed_rgb) {
  383. uint8_t *rgba = dtext->fontcolor_rgba;
  384. dtext->fontcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  385. dtext->fontcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  386. dtext->fontcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  387. dtext->fontcolor[3] = rgba[3];
  388. rgba = dtext->shadowcolor_rgba;
  389. dtext->shadowcolor[0] = RGB_TO_Y_CCIR(rgba[0], rgba[1], rgba[2]);
  390. dtext->shadowcolor[1] = RGB_TO_U_CCIR(rgba[0], rgba[1], rgba[2], 0);
  391. dtext->shadowcolor[2] = RGB_TO_V_CCIR(rgba[0], rgba[1], rgba[2], 0);
  392. dtext->shadowcolor[3] = rgba[3];
  393. }
  394. dtext->var_values[VAR_W] = inlink->w;
  395. dtext->var_values[VAR_H] = inlink->h;
  396. dtext->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  397. dtext->var_values[VAR_DAR] = (double)inlink->w / inlink->h * dtext->var_values[VAR_SAR];
  398. dtext->var_values[VAR_HSUB] = 1<<pix_desc->log2_chroma_w;
  399. dtext->var_values[VAR_VSUB] = 1<<pix_desc->log2_chroma_h;
  400. dtext->var_values[VAR_X] = NAN;
  401. dtext->var_values[VAR_Y] = NAN;
  402. if (!dtext->reinit)
  403. dtext->var_values[VAR_N] = 0;
  404. dtext->var_values[VAR_T] = NAN;
  405. if ((ret = av_expr_parse(&dtext->x_pexpr, dtext->x_expr, var_names,
  406. NULL, NULL, NULL, NULL, 0, ctx)) < 0 ||
  407. (ret = av_expr_parse(&dtext->y_pexpr, dtext->y_expr, var_names,
  408. NULL, NULL, NULL, NULL, 0, ctx)) < 0)
  409. return AVERROR(EINVAL);
  410. return 0;
  411. }
  412. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  413. {
  414. DrawTextContext *dtext = ctx->priv;
  415. if (!strcmp(cmd, "reinit")) {
  416. int ret;
  417. uninit(ctx);
  418. dtext->reinit = 1;
  419. if ((ret = init(ctx, arg, NULL)) < 0)
  420. return ret;
  421. return config_input(ctx->inputs[0]);
  422. }
  423. return AVERROR(ENOSYS);
  424. }
  425. #define GET_BITMAP_VAL(r, c) \
  426. bitmap->pixel_mode == FT_PIXEL_MODE_MONO ? \
  427. (bitmap->buffer[(r) * bitmap->pitch + ((c)>>3)] & (0x80 >> ((c)&7))) * 255 : \
  428. bitmap->buffer[(r) * bitmap->pitch + (c)]
  429. #define SET_PIXEL_YUV(picref, yuva_color, val, x, y, hsub, vsub) { \
  430. luma_pos = ((x) ) + ((y) ) * picref->linesize[0]; \
  431. alpha = yuva_color[3] * (val) * 129; \
  432. picref->data[0][luma_pos] = (alpha * yuva_color[0] + (255*255*129 - alpha) * picref->data[0][luma_pos] ) >> 23; \
  433. if (((x) & ((1<<(hsub)) - 1)) == 0 && ((y) & ((1<<(vsub)) - 1)) == 0) {\
  434. chroma_pos1 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[1]; \
  435. chroma_pos2 = ((x) >> (hsub)) + ((y) >> (vsub)) * picref->linesize[2]; \
  436. picref->data[1][chroma_pos1] = (alpha * yuva_color[1] + (255*255*129 - alpha) * picref->data[1][chroma_pos1]) >> 23; \
  437. picref->data[2][chroma_pos2] = (alpha * yuva_color[2] + (255*255*129 - alpha) * picref->data[2][chroma_pos2]) >> 23; \
  438. }\
  439. }
  440. static inline int draw_glyph_yuv(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
  441. int x, int y, int width, int height,
  442. const uint8_t yuva_color[4], int hsub, int vsub)
  443. {
  444. int r, c, alpha;
  445. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  446. uint8_t src_val;
  447. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  448. for (c = 0; c < bitmap->width && c+x < width; c++) {
  449. if (c+x < 0 || r+y < 0)
  450. continue;
  451. /* get intensity value in the glyph bitmap (source) */
  452. src_val = GET_BITMAP_VAL(r, c);
  453. if (!src_val)
  454. continue;
  455. SET_PIXEL_YUV(picref, yuva_color, src_val, c+x, y+r, hsub, vsub);
  456. }
  457. }
  458. return 0;
  459. }
  460. #define SET_PIXEL_RGB(picref, rgba_color, val, x, y, pixel_step, r_off, g_off, b_off, a_off) { \
  461. p = picref->data[0] + (x) * pixel_step + ((y) * picref->linesize[0]); \
  462. alpha = rgba_color[3] * (val) * 129; \
  463. *(p+r_off) = (alpha * rgba_color[0] + (255*255*129 - alpha) * *(p+r_off)) >> 23; \
  464. *(p+g_off) = (alpha * rgba_color[1] + (255*255*129 - alpha) * *(p+g_off)) >> 23; \
  465. *(p+b_off) = (alpha * rgba_color[2] + (255*255*129 - alpha) * *(p+b_off)) >> 23; \
  466. }
  467. static inline int draw_glyph_rgb(AVFilterBufferRef *picref, FT_Bitmap *bitmap,
  468. int x, int y, int width, int height, int pixel_step,
  469. const uint8_t rgba_color[4], const uint8_t rgba_map[4])
  470. {
  471. int r, c, alpha;
  472. uint8_t *p;
  473. uint8_t src_val;
  474. for (r = 0; r < bitmap->rows && r+y < height; r++) {
  475. for (c = 0; c < bitmap->width && c+x < width; c++) {
  476. if (c+x < 0 || r+y < 0)
  477. continue;
  478. /* get intensity value in the glyph bitmap (source) */
  479. src_val = GET_BITMAP_VAL(r, c);
  480. if (!src_val)
  481. continue;
  482. SET_PIXEL_RGB(picref, rgba_color, src_val, c+x, y+r, pixel_step,
  483. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  484. }
  485. }
  486. return 0;
  487. }
  488. static inline void drawbox(AVFilterBufferRef *picref, int x, int y,
  489. int width, int height,
  490. uint8_t *line[4], int pixel_step[4], uint8_t color[4],
  491. int hsub, int vsub, int is_rgba_packed, uint8_t rgba_map[4])
  492. {
  493. int i, j, alpha;
  494. if (color[3] != 0xFF) {
  495. if (is_rgba_packed) {
  496. uint8_t *p;
  497. for (j = 0; j < height; j++)
  498. for (i = 0; i < width; i++)
  499. SET_PIXEL_RGB(picref, color, 255, i+x, y+j, pixel_step[0],
  500. rgba_map[0], rgba_map[1], rgba_map[2], rgba_map[3]);
  501. } else {
  502. unsigned int luma_pos, chroma_pos1, chroma_pos2;
  503. for (j = 0; j < height; j++)
  504. for (i = 0; i < width; i++)
  505. SET_PIXEL_YUV(picref, color, 255, i+x, y+j, hsub, vsub);
  506. }
  507. } else {
  508. ff_draw_rectangle(picref->data, picref->linesize,
  509. line, pixel_step, hsub, vsub,
  510. x, y, width, height);
  511. }
  512. }
  513. static inline int is_newline(uint32_t c)
  514. {
  515. return (c == '\n' || c == '\r' || c == '\f' || c == '\v');
  516. }
  517. static int draw_glyphs(DrawTextContext *dtext, AVFilterBufferRef *picref,
  518. int width, int height, const uint8_t rgbcolor[4], const uint8_t yuvcolor[4], int x, int y)
  519. {
  520. char *text = dtext->expanded_text;
  521. uint32_t code = 0;
  522. int i, x1, y1;
  523. uint8_t *p;
  524. Glyph *glyph = NULL;
  525. for (i = 0, p = text; *p; i++) {
  526. Glyph dummy = { 0 };
  527. GET_UTF8(code, *p++, continue;);
  528. /* skip new line chars, just go to new line */
  529. if (code == '\n' || code == '\r' || code == '\t')
  530. continue;
  531. dummy.code = code;
  532. glyph = av_tree_find(dtext->glyphs, &dummy, (void *)glyph_cmp, NULL);
  533. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  534. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  535. return AVERROR(EINVAL);
  536. x1 = dtext->positions[i].x+dtext->x+x;
  537. y1 = dtext->positions[i].y+dtext->y+y;
  538. if (dtext->is_packed_rgb) {
  539. draw_glyph_rgb(picref, &glyph->bitmap,
  540. x1, y1, width, height,
  541. dtext->pixel_step[0], rgbcolor, dtext->rgba_map);
  542. } else {
  543. draw_glyph_yuv(picref, &glyph->bitmap,
  544. x1, y1, width, height,
  545. yuvcolor, dtext->hsub, dtext->vsub);
  546. }
  547. }
  548. return 0;
  549. }
  550. static int draw_text(AVFilterContext *ctx, AVFilterBufferRef *picref,
  551. int width, int height)
  552. {
  553. DrawTextContext *dtext = ctx->priv;
  554. uint32_t code = 0, prev_code = 0;
  555. int x = 0, y = 0, i = 0, ret;
  556. int max_text_line_w = 0, len;
  557. int box_w, box_h;
  558. char *text = dtext->text;
  559. uint8_t *p;
  560. int y_min = 32000, y_max = -32000;
  561. int x_min = 32000, x_max = -32000;
  562. FT_Vector delta;
  563. Glyph *glyph = NULL, *prev_glyph = NULL;
  564. Glyph dummy = { 0 };
  565. time_t now = time(0);
  566. struct tm ltime;
  567. uint8_t *buf = dtext->expanded_text;
  568. int buf_size = dtext->expanded_text_size;
  569. if(dtext->basetime != AV_NOPTS_VALUE)
  570. now= picref->pts*av_q2d(ctx->inputs[0]->time_base) + dtext->basetime/1000000;
  571. if (!buf) {
  572. buf_size = 2*strlen(dtext->text)+1;
  573. buf = av_malloc(buf_size);
  574. }
  575. #if HAVE_LOCALTIME_R
  576. localtime_r(&now, &ltime);
  577. #else
  578. if(strchr(dtext->text, '%'))
  579. ltime= *localtime(&now);
  580. #endif
  581. do {
  582. *buf = 1;
  583. if (strftime(buf, buf_size, dtext->text, &ltime) != 0 || *buf == 0)
  584. break;
  585. buf_size *= 2;
  586. } while ((buf = av_realloc(buf, buf_size)));
  587. if (!buf)
  588. return AVERROR(ENOMEM);
  589. text = dtext->expanded_text = buf;
  590. dtext->expanded_text_size = buf_size;
  591. if ((len = strlen(text)) > dtext->nb_positions) {
  592. if (!(dtext->positions =
  593. av_realloc(dtext->positions, len*sizeof(*dtext->positions))))
  594. return AVERROR(ENOMEM);
  595. dtext->nb_positions = len;
  596. }
  597. x = 0;
  598. y = 0;
  599. /* load and cache glyphs */
  600. for (i = 0, p = text; *p; i++) {
  601. GET_UTF8(code, *p++, continue;);
  602. /* get glyph */
  603. dummy.code = code;
  604. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  605. if (!glyph)
  606. load_glyph(ctx, &glyph, code);
  607. y_min = FFMIN(glyph->bbox.yMin, y_min);
  608. y_max = FFMAX(glyph->bbox.yMax, y_max);
  609. x_min = FFMIN(glyph->bbox.xMin, x_min);
  610. x_max = FFMAX(glyph->bbox.xMax, x_max);
  611. }
  612. dtext->max_glyph_h = y_max - y_min;
  613. dtext->max_glyph_w = x_max - x_min;
  614. /* compute and save position for each glyph */
  615. glyph = NULL;
  616. for (i = 0, p = text; *p; i++) {
  617. GET_UTF8(code, *p++, continue;);
  618. /* skip the \n in the sequence \r\n */
  619. if (prev_code == '\r' && code == '\n')
  620. continue;
  621. prev_code = code;
  622. if (is_newline(code)) {
  623. max_text_line_w = FFMAX(max_text_line_w, x);
  624. y += dtext->max_glyph_h;
  625. x = 0;
  626. continue;
  627. }
  628. /* get glyph */
  629. prev_glyph = glyph;
  630. dummy.code = code;
  631. glyph = av_tree_find(dtext->glyphs, &dummy, glyph_cmp, NULL);
  632. /* kerning */
  633. if (dtext->use_kerning && prev_glyph && glyph->code) {
  634. FT_Get_Kerning(dtext->face, prev_glyph->code, glyph->code,
  635. ft_kerning_default, &delta);
  636. x += delta.x >> 6;
  637. }
  638. /* save position */
  639. dtext->positions[i].x = x + glyph->bitmap_left;
  640. dtext->positions[i].y = y - glyph->bitmap_top + y_max;
  641. if (code == '\t') x = (x / dtext->tabsize + 1)*dtext->tabsize;
  642. else x += glyph->advance;
  643. }
  644. max_text_line_w = FFMAX(x, max_text_line_w);
  645. dtext->var_values[VAR_TW] = dtext->var_values[VAR_TEXT_W] = max_text_line_w;
  646. dtext->var_values[VAR_TH] = dtext->var_values[VAR_TEXT_H] = y + dtext->max_glyph_h;
  647. dtext->var_values[VAR_MAX_GLYPH_W] = dtext->max_glyph_w;
  648. dtext->var_values[VAR_MAX_GLYPH_H] = dtext->max_glyph_h;
  649. dtext->var_values[VAR_MAX_GLYPH_A] = dtext->var_values[VAR_ASCENT ] = y_max;
  650. dtext->var_values[VAR_MAX_GLYPH_D] = dtext->var_values[VAR_DESCENT] = y_min;
  651. dtext->var_values[VAR_LINE_H] = dtext->var_values[VAR_LH] = dtext->max_glyph_h;
  652. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, NULL);
  653. dtext->y = dtext->var_values[VAR_Y] = av_expr_eval(dtext->y_pexpr, dtext->var_values, NULL);
  654. dtext->x = dtext->var_values[VAR_X] = av_expr_eval(dtext->x_pexpr, dtext->var_values, NULL);
  655. dtext->x &= ~((1 << dtext->hsub) - 1);
  656. dtext->y &= ~((1 << dtext->vsub) - 1);
  657. box_w = FFMIN(width - 1 , max_text_line_w);
  658. box_h = FFMIN(height - 1, y + dtext->max_glyph_h);
  659. /* draw box */
  660. if (dtext->draw_box)
  661. drawbox(picref, dtext->x, dtext->y, box_w, box_h,
  662. dtext->box_line, dtext->pixel_step, dtext->boxcolor_rgba,
  663. dtext->hsub, dtext->vsub, dtext->is_packed_rgb, dtext->rgba_map);
  664. if (dtext->shadowx || dtext->shadowy) {
  665. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->shadowcolor_rgba,
  666. dtext->shadowcolor, dtext->shadowx, dtext->shadowy)) < 0)
  667. return ret;
  668. }
  669. if ((ret = draw_glyphs(dtext, picref, width, height, dtext->fontcolor_rgba,
  670. dtext->fontcolor, 0, 0)) < 0)
  671. return ret;
  672. return 0;
  673. }
  674. static void null_draw_slice(AVFilterLink *link, int y, int h, int slice_dir) { }
  675. static void end_frame(AVFilterLink *inlink)
  676. {
  677. AVFilterContext *ctx = inlink->dst;
  678. AVFilterLink *outlink = ctx->outputs[0];
  679. DrawTextContext *dtext = ctx->priv;
  680. AVFilterBufferRef *picref = inlink->cur_buf;
  681. dtext->var_values[VAR_T] = picref->pts == AV_NOPTS_VALUE ?
  682. NAN : picref->pts * av_q2d(inlink->time_base);
  683. draw_text(ctx, picref, picref->video->w, picref->video->h);
  684. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  685. (int)dtext->var_values[VAR_N], dtext->var_values[VAR_T],
  686. (int)dtext->var_values[VAR_TEXT_W], (int)dtext->var_values[VAR_TEXT_H],
  687. dtext->x, dtext->y);
  688. dtext->var_values[VAR_N] += 1.0;
  689. avfilter_draw_slice(outlink, 0, picref->video->h, 1);
  690. avfilter_end_frame(outlink);
  691. }
  692. AVFilter avfilter_vf_drawtext = {
  693. .name = "drawtext",
  694. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  695. .priv_size = sizeof(DrawTextContext),
  696. .init = init,
  697. .uninit = uninit,
  698. .query_formats = query_formats,
  699. .inputs = (AVFilterPad[]) {{ .name = "default",
  700. .type = AVMEDIA_TYPE_VIDEO,
  701. .get_video_buffer = avfilter_null_get_video_buffer,
  702. .start_frame = avfilter_null_start_frame,
  703. .draw_slice = null_draw_slice,
  704. .end_frame = end_frame,
  705. .config_props = config_input,
  706. .min_perms = AV_PERM_WRITE |
  707. AV_PERM_READ,
  708. .rej_perms = AV_PERM_PRESERVE },
  709. { .name = NULL}},
  710. .outputs = (AVFilterPad[]) {{ .name = "default",
  711. .type = AVMEDIA_TYPE_VIDEO, },
  712. { .name = NULL}},
  713. .process_command = command,
  714. };