vf_drawtext.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  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 "config.h"
  28. #if HAVE_SYS_TIME_H
  29. #include <sys/time.h>
  30. #endif
  31. #include <sys/types.h>
  32. #include <sys/stat.h>
  33. #include <time.h>
  34. #if HAVE_UNISTD_H
  35. #include <unistd.h>
  36. #endif
  37. #include <fenv.h>
  38. #if CONFIG_LIBFONTCONFIG
  39. #include <fontconfig/fontconfig.h>
  40. #endif
  41. #include "libavutil/avstring.h"
  42. #include "libavutil/bprint.h"
  43. #include "libavutil/common.h"
  44. #include "libavutil/file.h"
  45. #include "libavutil/eval.h"
  46. #include "libavutil/opt.h"
  47. #include "libavutil/random_seed.h"
  48. #include "libavutil/parseutils.h"
  49. #include "libavutil/timecode.h"
  50. #include "libavutil/time_internal.h"
  51. #include "libavutil/tree.h"
  52. #include "libavutil/lfg.h"
  53. #include "avfilter.h"
  54. #include "drawutils.h"
  55. #include "formats.h"
  56. #include "internal.h"
  57. #include "video.h"
  58. #if CONFIG_LIBFRIBIDI
  59. #include <fribidi.h>
  60. #endif
  61. #include <ft2build.h>
  62. #include FT_FREETYPE_H
  63. #include FT_GLYPH_H
  64. #include FT_STROKER_H
  65. static const char *const var_names[] = {
  66. "dar",
  67. "hsub", "vsub",
  68. "line_h", "lh", ///< line height, same as max_glyph_h
  69. "main_h", "h", "H", ///< height of the input video
  70. "main_w", "w", "W", ///< width of the input video
  71. "max_glyph_a", "ascent", ///< max glyph ascent
  72. "max_glyph_d", "descent", ///< min glyph descent
  73. "max_glyph_h", ///< max glyph height
  74. "max_glyph_w", ///< max glyph width
  75. "n", ///< number of frame
  76. "sar",
  77. "t", ///< timestamp expressed in seconds
  78. "text_h", "th", ///< height of the rendered text
  79. "text_w", "tw", ///< width of the rendered text
  80. "x",
  81. "y",
  82. "pict_type",
  83. NULL
  84. };
  85. static const char *const fun2_names[] = {
  86. "rand"
  87. };
  88. static double drand(void *opaque, double min, double max)
  89. {
  90. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  91. }
  92. typedef double (*eval_func2)(void *, double a, double b);
  93. static const eval_func2 fun2[] = {
  94. drand,
  95. NULL
  96. };
  97. enum var_name {
  98. VAR_DAR,
  99. VAR_HSUB, VAR_VSUB,
  100. VAR_LINE_H, VAR_LH,
  101. VAR_MAIN_H, VAR_h, VAR_H,
  102. VAR_MAIN_W, VAR_w, VAR_W,
  103. VAR_MAX_GLYPH_A, VAR_ASCENT,
  104. VAR_MAX_GLYPH_D, VAR_DESCENT,
  105. VAR_MAX_GLYPH_H,
  106. VAR_MAX_GLYPH_W,
  107. VAR_N,
  108. VAR_SAR,
  109. VAR_T,
  110. VAR_TEXT_H, VAR_TH,
  111. VAR_TEXT_W, VAR_TW,
  112. VAR_X,
  113. VAR_Y,
  114. VAR_PICT_TYPE,
  115. VAR_VARS_NB
  116. };
  117. enum expansion_mode {
  118. EXP_NONE,
  119. EXP_NORMAL,
  120. EXP_STRFTIME,
  121. };
  122. typedef struct DrawTextContext {
  123. const AVClass *class;
  124. int exp_mode; ///< expansion mode to use for the text
  125. int reinit; ///< tells if the filter is being reinited
  126. #if CONFIG_LIBFONTCONFIG
  127. uint8_t *font; ///< font to be used
  128. #endif
  129. uint8_t *fontfile; ///< font to be used
  130. uint8_t *text; ///< text to be drawn
  131. AVBPrint expanded_text; ///< used to contain the expanded text
  132. uint8_t *fontcolor_expr; ///< fontcolor expression to evaluate
  133. AVBPrint expanded_fontcolor; ///< used to contain the expanded fontcolor spec
  134. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  135. FT_Vector *positions; ///< positions for each element in the text
  136. size_t nb_positions; ///< number of elements of positions array
  137. char *textfile; ///< file with text to be drawn
  138. int x; ///< x position to start drawing text
  139. int y; ///< y position to start drawing text
  140. int max_glyph_w; ///< max glyph width
  141. int max_glyph_h; ///< max glyph height
  142. int shadowx, shadowy;
  143. int borderw; ///< border width
  144. unsigned int fontsize; ///< font size to use
  145. short int draw_box; ///< draw box around text - true or false
  146. int boxborderw; ///< box border width
  147. int use_kerning; ///< font kerning is used - true/false
  148. int tabsize; ///< tab size
  149. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  150. FFDrawContext dc;
  151. FFDrawColor fontcolor; ///< foreground color
  152. FFDrawColor shadowcolor; ///< shadow color
  153. FFDrawColor bordercolor; ///< border color
  154. FFDrawColor boxcolor; ///< background color
  155. FT_Library library; ///< freetype font library handle
  156. FT_Face face; ///< freetype font face handle
  157. FT_Stroker stroker; ///< freetype stroker handle
  158. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  159. char *x_expr; ///< expression for x position
  160. char *y_expr; ///< expression for y position
  161. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  162. int64_t basetime; ///< base pts time in the real world for display
  163. double var_values[VAR_VARS_NB];
  164. char *a_expr;
  165. AVExpr *a_pexpr;
  166. int alpha;
  167. AVLFG prng; ///< random
  168. char *tc_opt_string; ///< specified timecode option string
  169. AVRational tc_rate; ///< frame rate for timecode
  170. AVTimecode tc; ///< timecode context
  171. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  172. int reload; ///< reload text file for each frame
  173. int start_number; ///< starting frame number for n/frame_num var
  174. #if CONFIG_LIBFRIBIDI
  175. int text_shaping; ///< 1 to shape the text before drawing it
  176. #endif
  177. AVDictionary *metadata;
  178. } DrawTextContext;
  179. #define OFFSET(x) offsetof(DrawTextContext, x)
  180. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  181. static const AVOption drawtext_options[]= {
  182. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  183. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  184. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  185. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  186. {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, CHAR_MIN, CHAR_MAX, FLAGS},
  187. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, CHAR_MIN, CHAR_MAX, FLAGS},
  188. {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  189. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, CHAR_MIN, CHAR_MAX, FLAGS},
  190. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1 , FLAGS},
  191. {"boxborderw", "set box border width", OFFSET(boxborderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  192. {"fontsize", "set font size", OFFSET(fontsize), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX , FLAGS},
  193. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  194. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, CHAR_MIN, CHAR_MAX, FLAGS},
  195. {"shadowx", "set shadow x offset", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  196. {"shadowy", "set shadow y offset", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  197. {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX , FLAGS},
  198. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX , FLAGS},
  199. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX , FLAGS},
  200. #if CONFIG_LIBFONTCONFIG
  201. { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
  202. #endif
  203. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, "expansion"},
  204. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, "expansion"},
  205. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, "expansion"},
  206. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, "expansion"},
  207. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, CHAR_MIN, CHAR_MAX, FLAGS},
  208. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
  209. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  210. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  211. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  212. {"reload", "reload text file for each frame", OFFSET(reload), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
  213. { "alpha", "apply alpha while rendering", OFFSET(a_expr), AV_OPT_TYPE_STRING, { .str = "1" }, .flags = FLAGS },
  214. {"fix_bounds", "check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
  215. {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
  216. #if CONFIG_LIBFRIBIDI
  217. {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
  218. #endif
  219. /* FT_LOAD_* flags */
  220. { "ft_load_flags", "set font loading flags for libfreetype", OFFSET(ft_load_flags), AV_OPT_TYPE_FLAGS, { .i64 = FT_LOAD_DEFAULT }, 0, INT_MAX, FLAGS, "ft_load_flags" },
  221. { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  222. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  223. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  224. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  225. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  226. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  227. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  228. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  229. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  230. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  231. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  232. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  233. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  234. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  235. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  236. { NULL }
  237. };
  238. AVFILTER_DEFINE_CLASS(drawtext);
  239. #undef __FTERRORS_H__
  240. #define FT_ERROR_START_LIST {
  241. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  242. #define FT_ERROR_END_LIST { 0, NULL } };
  243. static const struct ft_error
  244. {
  245. int err;
  246. const char *err_msg;
  247. } ft_errors[] =
  248. #include FT_ERRORS_H
  249. #define FT_ERRMSG(e) ft_errors[e].err_msg
  250. typedef struct Glyph {
  251. FT_Glyph glyph;
  252. FT_Glyph border_glyph;
  253. uint32_t code;
  254. FT_Bitmap bitmap; ///< array holding bitmaps of font
  255. FT_Bitmap border_bitmap; ///< array holding bitmaps of font border
  256. FT_BBox bbox;
  257. int advance;
  258. int bitmap_left;
  259. int bitmap_top;
  260. } Glyph;
  261. static int glyph_cmp(const void *key, const void *b)
  262. {
  263. const Glyph *a = key, *bb = b;
  264. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  265. return diff > 0 ? 1 : diff < 0 ? -1 : 0;
  266. }
  267. /**
  268. * Load glyphs corresponding to the UTF-32 codepoint code.
  269. */
  270. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code)
  271. {
  272. DrawTextContext *s = ctx->priv;
  273. FT_BitmapGlyph bitmapglyph;
  274. Glyph *glyph;
  275. struct AVTreeNode *node = NULL;
  276. int ret;
  277. /* load glyph into s->face->glyph */
  278. if (FT_Load_Char(s->face, code, s->ft_load_flags))
  279. return AVERROR(EINVAL);
  280. glyph = av_mallocz(sizeof(*glyph));
  281. if (!glyph) {
  282. ret = AVERROR(ENOMEM);
  283. goto error;
  284. }
  285. glyph->code = code;
  286. if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
  287. ret = AVERROR(EINVAL);
  288. goto error;
  289. }
  290. if (s->borderw) {
  291. glyph->border_glyph = glyph->glyph;
  292. if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0) ||
  293. FT_Glyph_To_Bitmap(&glyph->border_glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  294. ret = AVERROR_EXTERNAL;
  295. goto error;
  296. }
  297. bitmapglyph = (FT_BitmapGlyph) glyph->border_glyph;
  298. glyph->border_bitmap = bitmapglyph->bitmap;
  299. }
  300. if (FT_Glyph_To_Bitmap(&glyph->glyph, FT_RENDER_MODE_NORMAL, 0, 1)) {
  301. ret = AVERROR_EXTERNAL;
  302. goto error;
  303. }
  304. bitmapglyph = (FT_BitmapGlyph) glyph->glyph;
  305. glyph->bitmap = bitmapglyph->bitmap;
  306. glyph->bitmap_left = bitmapglyph->left;
  307. glyph->bitmap_top = bitmapglyph->top;
  308. glyph->advance = s->face->glyph->advance.x >> 6;
  309. /* measure text height to calculate text_height (or the maximum text height) */
  310. FT_Glyph_Get_CBox(glyph->glyph, ft_glyph_bbox_pixels, &glyph->bbox);
  311. /* cache the newly created glyph */
  312. if (!(node = av_tree_node_alloc())) {
  313. ret = AVERROR(ENOMEM);
  314. goto error;
  315. }
  316. av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
  317. if (glyph_ptr)
  318. *glyph_ptr = glyph;
  319. return 0;
  320. error:
  321. if (glyph)
  322. av_freep(&glyph->glyph);
  323. av_freep(&glyph);
  324. av_freep(&node);
  325. return ret;
  326. }
  327. static int load_font_file(AVFilterContext *ctx, const char *path, int index)
  328. {
  329. DrawTextContext *s = ctx->priv;
  330. int err;
  331. err = FT_New_Face(s->library, path, index, &s->face);
  332. if (err) {
  333. #if !CONFIG_LIBFONTCONFIG
  334. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  335. s->fontfile, FT_ERRMSG(err));
  336. #endif
  337. return AVERROR(EINVAL);
  338. }
  339. return 0;
  340. }
  341. #if CONFIG_LIBFONTCONFIG
  342. static int load_font_fontconfig(AVFilterContext *ctx)
  343. {
  344. DrawTextContext *s = ctx->priv;
  345. FcConfig *fontconfig;
  346. FcPattern *pat, *best;
  347. FcResult result = FcResultMatch;
  348. FcChar8 *filename;
  349. int index;
  350. double size;
  351. int err = AVERROR(ENOENT);
  352. fontconfig = FcInitLoadConfigAndFonts();
  353. if (!fontconfig) {
  354. av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
  355. return AVERROR_UNKNOWN;
  356. }
  357. pat = FcNameParse(s->fontfile ? s->fontfile :
  358. (uint8_t *)(intptr_t)"default");
  359. if (!pat) {
  360. av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
  361. return AVERROR(EINVAL);
  362. }
  363. FcPatternAddString(pat, FC_FAMILY, s->font);
  364. if (s->fontsize)
  365. FcPatternAddDouble(pat, FC_SIZE, (double)s->fontsize);
  366. FcDefaultSubstitute(pat);
  367. if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
  368. av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
  369. FcPatternDestroy(pat);
  370. return AVERROR(ENOMEM);
  371. }
  372. best = FcFontMatch(fontconfig, pat, &result);
  373. FcPatternDestroy(pat);
  374. if (!best || result != FcResultMatch) {
  375. av_log(ctx, AV_LOG_ERROR,
  376. "Cannot find a valid font for the family %s\n",
  377. s->font);
  378. goto fail;
  379. }
  380. if (
  381. FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
  382. FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
  383. av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
  384. return AVERROR(EINVAL);
  385. }
  386. if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
  387. av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
  388. s->font);
  389. goto fail;
  390. }
  391. av_log(ctx, AV_LOG_INFO, "Using \"%s\"\n", filename);
  392. if (!s->fontsize)
  393. s->fontsize = size + 0.5;
  394. err = load_font_file(ctx, filename, index);
  395. if (err)
  396. return err;
  397. FcConfigDestroy(fontconfig);
  398. fail:
  399. FcPatternDestroy(best);
  400. return err;
  401. }
  402. #endif
  403. static int load_font(AVFilterContext *ctx)
  404. {
  405. DrawTextContext *s = ctx->priv;
  406. int err;
  407. /* load the face, and set up the encoding, which is by default UTF-8 */
  408. err = load_font_file(ctx, s->fontfile, 0);
  409. if (!err)
  410. return 0;
  411. #if CONFIG_LIBFONTCONFIG
  412. err = load_font_fontconfig(ctx);
  413. if (!err)
  414. return 0;
  415. #endif
  416. return err;
  417. }
  418. static int load_textfile(AVFilterContext *ctx)
  419. {
  420. DrawTextContext *s = ctx->priv;
  421. int err;
  422. uint8_t *textbuf;
  423. uint8_t *tmp;
  424. size_t textbuf_size;
  425. if ((err = av_file_map(s->textfile, &textbuf, &textbuf_size, 0, ctx)) < 0) {
  426. av_log(ctx, AV_LOG_ERROR,
  427. "The text file '%s' could not be read or is empty\n",
  428. s->textfile);
  429. return err;
  430. }
  431. if (textbuf_size > SIZE_MAX - 1 || !(tmp = av_realloc(s->text, textbuf_size + 1))) {
  432. av_file_unmap(textbuf, textbuf_size);
  433. return AVERROR(ENOMEM);
  434. }
  435. s->text = tmp;
  436. memcpy(s->text, textbuf, textbuf_size);
  437. s->text[textbuf_size] = 0;
  438. av_file_unmap(textbuf, textbuf_size);
  439. return 0;
  440. }
  441. static inline int is_newline(uint32_t c)
  442. {
  443. return c == '\n' || c == '\r' || c == '\f' || c == '\v';
  444. }
  445. #if CONFIG_LIBFRIBIDI
  446. static int shape_text(AVFilterContext *ctx)
  447. {
  448. DrawTextContext *s = ctx->priv;
  449. uint8_t *tmp;
  450. int ret = AVERROR(ENOMEM);
  451. static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
  452. FRIBIDI_FLAGS_ARABIC;
  453. FriBidiChar *unicodestr = NULL;
  454. FriBidiStrIndex len;
  455. FriBidiParType direction = FRIBIDI_PAR_LTR;
  456. FriBidiStrIndex line_start = 0;
  457. FriBidiStrIndex line_end = 0;
  458. FriBidiLevel *embedding_levels = NULL;
  459. FriBidiArabicProp *ar_props = NULL;
  460. FriBidiCharType *bidi_types = NULL;
  461. FriBidiStrIndex i,j;
  462. len = strlen(s->text);
  463. if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
  464. goto out;
  465. }
  466. len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
  467. s->text, len, unicodestr);
  468. bidi_types = av_malloc_array(len, sizeof(*bidi_types));
  469. if (!bidi_types) {
  470. goto out;
  471. }
  472. fribidi_get_bidi_types(unicodestr, len, bidi_types);
  473. embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
  474. if (!embedding_levels) {
  475. goto out;
  476. }
  477. if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
  478. embedding_levels)) {
  479. goto out;
  480. }
  481. ar_props = av_malloc_array(len, sizeof(*ar_props));
  482. if (!ar_props) {
  483. goto out;
  484. }
  485. fribidi_get_joining_types(unicodestr, len, ar_props);
  486. fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
  487. fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
  488. for (line_end = 0, line_start = 0; line_end < len; line_end++) {
  489. if (is_newline(unicodestr[line_end]) || line_end == len - 1) {
  490. if (!fribidi_reorder_line(flags, bidi_types,
  491. line_end - line_start + 1, line_start,
  492. direction, embedding_levels, unicodestr,
  493. NULL)) {
  494. goto out;
  495. }
  496. line_start = line_end + 1;
  497. }
  498. }
  499. /* Remove zero-width fill chars put in by libfribidi */
  500. for (i = 0, j = 0; i < len; i++)
  501. if (unicodestr[i] != FRIBIDI_CHAR_FILL)
  502. unicodestr[j++] = unicodestr[i];
  503. len = j;
  504. if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
  505. /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
  506. goto out;
  507. }
  508. s->text = tmp;
  509. len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
  510. unicodestr, len, s->text);
  511. ret = 0;
  512. out:
  513. av_free(unicodestr);
  514. av_free(embedding_levels);
  515. av_free(ar_props);
  516. av_free(bidi_types);
  517. return ret;
  518. }
  519. #endif
  520. static av_cold int init(AVFilterContext *ctx)
  521. {
  522. int err;
  523. DrawTextContext *s = ctx->priv;
  524. Glyph *glyph;
  525. if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
  526. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  527. return AVERROR(EINVAL);
  528. }
  529. if (s->textfile) {
  530. if (s->text) {
  531. av_log(ctx, AV_LOG_ERROR,
  532. "Both text and text file provided. Please provide only one\n");
  533. return AVERROR(EINVAL);
  534. }
  535. if ((err = load_textfile(ctx)) < 0)
  536. return err;
  537. }
  538. if (s->reload && !s->textfile)
  539. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  540. if (s->tc_opt_string) {
  541. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  542. s->tc_opt_string, ctx);
  543. if (ret < 0)
  544. return ret;
  545. if (s->tc24hmax)
  546. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  547. if (!s->text)
  548. s->text = av_strdup("");
  549. }
  550. if (!s->text) {
  551. av_log(ctx, AV_LOG_ERROR,
  552. "Either text, a valid file or a timecode must be provided\n");
  553. return AVERROR(EINVAL);
  554. }
  555. #if CONFIG_LIBFRIBIDI
  556. if (s->text_shaping)
  557. if ((err = shape_text(ctx)) < 0)
  558. return err;
  559. #endif
  560. if ((err = FT_Init_FreeType(&(s->library)))) {
  561. av_log(ctx, AV_LOG_ERROR,
  562. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  563. return AVERROR(EINVAL);
  564. }
  565. err = load_font(ctx);
  566. if (err)
  567. return err;
  568. if (!s->fontsize)
  569. s->fontsize = 16;
  570. if ((err = FT_Set_Pixel_Sizes(s->face, 0, s->fontsize))) {
  571. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  572. s->fontsize, FT_ERRMSG(err));
  573. return AVERROR(EINVAL);
  574. }
  575. if (s->borderw) {
  576. if (FT_Stroker_New(s->library, &s->stroker)) {
  577. av_log(ctx, AV_LOG_ERROR, "Coult not init FT stroker\n");
  578. return AVERROR_EXTERNAL;
  579. }
  580. FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
  581. FT_STROKER_LINEJOIN_ROUND, 0);
  582. }
  583. s->use_kerning = FT_HAS_KERNING(s->face);
  584. /* load the fallback glyph with code 0 */
  585. load_glyph(ctx, NULL, 0);
  586. /* set the tabsize in pixels */
  587. if ((err = load_glyph(ctx, &glyph, ' ')) < 0) {
  588. av_log(ctx, AV_LOG_ERROR, "Could not set tabsize.\n");
  589. return err;
  590. }
  591. s->tabsize *= glyph->advance;
  592. if (s->exp_mode == EXP_STRFTIME &&
  593. (strchr(s->text, '%') || strchr(s->text, '\\')))
  594. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  595. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  596. av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
  597. return 0;
  598. }
  599. static int query_formats(AVFilterContext *ctx)
  600. {
  601. return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  602. }
  603. static int glyph_enu_free(void *opaque, void *elem)
  604. {
  605. Glyph *glyph = elem;
  606. FT_Done_Glyph(glyph->glyph);
  607. FT_Done_Glyph(glyph->border_glyph);
  608. av_free(elem);
  609. return 0;
  610. }
  611. static av_cold void uninit(AVFilterContext *ctx)
  612. {
  613. DrawTextContext *s = ctx->priv;
  614. av_expr_free(s->x_pexpr);
  615. av_expr_free(s->y_pexpr);
  616. s->x_pexpr = s->y_pexpr = NULL;
  617. av_freep(&s->positions);
  618. s->nb_positions = 0;
  619. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  620. av_tree_destroy(s->glyphs);
  621. s->glyphs = NULL;
  622. FT_Done_Face(s->face);
  623. FT_Stroker_Done(s->stroker);
  624. FT_Done_FreeType(s->library);
  625. av_bprint_finalize(&s->expanded_text, NULL);
  626. av_bprint_finalize(&s->expanded_fontcolor, NULL);
  627. }
  628. static int config_input(AVFilterLink *inlink)
  629. {
  630. AVFilterContext *ctx = inlink->dst;
  631. DrawTextContext *s = ctx->priv;
  632. int ret;
  633. ff_draw_init(&s->dc, inlink->format, 0);
  634. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  635. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  636. ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
  637. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  638. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  639. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  640. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  641. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  642. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  643. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  644. s->var_values[VAR_X] = NAN;
  645. s->var_values[VAR_Y] = NAN;
  646. s->var_values[VAR_T] = NAN;
  647. av_lfg_init(&s->prng, av_get_random_seed());
  648. av_expr_free(s->x_pexpr);
  649. av_expr_free(s->y_pexpr);
  650. s->x_pexpr = s->y_pexpr = NULL;
  651. if ((ret = av_expr_parse(&s->x_pexpr, s->x_expr, var_names,
  652. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  653. (ret = av_expr_parse(&s->y_pexpr, s->y_expr, var_names,
  654. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  655. (ret = av_expr_parse(&s->a_pexpr, s->a_expr, var_names,
  656. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  657. return AVERROR(EINVAL);
  658. return 0;
  659. }
  660. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  661. {
  662. DrawTextContext *s = ctx->priv;
  663. if (!strcmp(cmd, "reinit")) {
  664. int ret;
  665. uninit(ctx);
  666. s->reinit = 1;
  667. if ((ret = av_set_options_string(ctx, arg, "=", ":")) < 0)
  668. return ret;
  669. if ((ret = init(ctx)) < 0)
  670. return ret;
  671. return config_input(ctx->inputs[0]);
  672. }
  673. return AVERROR(ENOSYS);
  674. }
  675. static int func_pict_type(AVFilterContext *ctx, AVBPrint *bp,
  676. char *fct, unsigned argc, char **argv, int tag)
  677. {
  678. DrawTextContext *s = ctx->priv;
  679. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  680. return 0;
  681. }
  682. static int func_pts(AVFilterContext *ctx, AVBPrint *bp,
  683. char *fct, unsigned argc, char **argv, int tag)
  684. {
  685. DrawTextContext *s = ctx->priv;
  686. const char *fmt;
  687. double pts = s->var_values[VAR_T];
  688. int ret;
  689. fmt = argc >= 1 ? argv[0] : "flt";
  690. if (argc >= 2) {
  691. int64_t delta;
  692. if ((ret = av_parse_time(&delta, argv[1], 1)) < 0) {
  693. av_log(ctx, AV_LOG_ERROR, "Invalid delta '%s'\n", argv[1]);
  694. return ret;
  695. }
  696. pts += (double)delta / AV_TIME_BASE;
  697. }
  698. if (!strcmp(fmt, "flt")) {
  699. av_bprintf(bp, "%.6f", s->var_values[VAR_T]);
  700. } else if (!strcmp(fmt, "hms")) {
  701. if (isnan(pts)) {
  702. av_bprintf(bp, " ??:??:??.???");
  703. } else {
  704. int64_t ms = llrint(pts * 1000);
  705. char sign = ' ';
  706. if (ms < 0) {
  707. sign = '-';
  708. ms = -ms;
  709. }
  710. av_bprintf(bp, "%c%02d:%02d:%02d.%03d", sign,
  711. (int)(ms / (60 * 60 * 1000)),
  712. (int)(ms / (60 * 1000)) % 60,
  713. (int)(ms / 1000) % 60,
  714. (int)(ms % 1000));
  715. }
  716. } else if (!strcmp(fmt, "localtime") ||
  717. !strcmp(fmt, "gmtime")) {
  718. struct tm tm;
  719. time_t ms = (time_t)pts;
  720. const char *timefmt = argc >= 3 ? argv[2] : "%Y-%m-%d %H:%M:%S";
  721. if (!strcmp(fmt, "localtime"))
  722. localtime_r(&ms, &tm);
  723. else
  724. gmtime_r(&ms, &tm);
  725. av_bprint_strftime(bp, timefmt, &tm);
  726. } else {
  727. av_log(ctx, AV_LOG_ERROR, "Invalid format '%s'\n", fmt);
  728. return AVERROR(EINVAL);
  729. }
  730. return 0;
  731. }
  732. static int func_frame_num(AVFilterContext *ctx, AVBPrint *bp,
  733. char *fct, unsigned argc, char **argv, int tag)
  734. {
  735. DrawTextContext *s = ctx->priv;
  736. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  737. return 0;
  738. }
  739. static int func_metadata(AVFilterContext *ctx, AVBPrint *bp,
  740. char *fct, unsigned argc, char **argv, int tag)
  741. {
  742. DrawTextContext *s = ctx->priv;
  743. AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
  744. if (e && e->value)
  745. av_bprintf(bp, "%s", e->value);
  746. else if (argc >= 2)
  747. av_bprintf(bp, "%s", argv[1]);
  748. return 0;
  749. }
  750. static int func_strftime(AVFilterContext *ctx, AVBPrint *bp,
  751. char *fct, unsigned argc, char **argv, int tag)
  752. {
  753. const char *fmt = argc ? argv[0] : "%Y-%m-%d %H:%M:%S";
  754. time_t now;
  755. struct tm tm;
  756. time(&now);
  757. if (tag == 'L')
  758. localtime_r(&now, &tm);
  759. else
  760. tm = *gmtime_r(&now, &tm);
  761. av_bprint_strftime(bp, fmt, &tm);
  762. return 0;
  763. }
  764. static int func_eval_expr(AVFilterContext *ctx, AVBPrint *bp,
  765. char *fct, unsigned argc, char **argv, int tag)
  766. {
  767. DrawTextContext *s = ctx->priv;
  768. double res;
  769. int ret;
  770. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  771. NULL, NULL, fun2_names, fun2,
  772. &s->prng, 0, ctx);
  773. if (ret < 0)
  774. av_log(ctx, AV_LOG_ERROR,
  775. "Expression '%s' for the expr text expansion function is not valid\n",
  776. argv[0]);
  777. else
  778. av_bprintf(bp, "%f", res);
  779. return ret;
  780. }
  781. static int func_eval_expr_int_format(AVFilterContext *ctx, AVBPrint *bp,
  782. char *fct, unsigned argc, char **argv, int tag)
  783. {
  784. DrawTextContext *s = ctx->priv;
  785. double res;
  786. int intval;
  787. int ret;
  788. unsigned int positions = 0;
  789. char fmt_str[30] = "%";
  790. /*
  791. * argv[0] expression to be converted to `int`
  792. * argv[1] format: 'x', 'X', 'd' or 'u'
  793. * argv[2] positions printed (optional)
  794. */
  795. ret = av_expr_parse_and_eval(&res, argv[0], var_names, s->var_values,
  796. NULL, NULL, fun2_names, fun2,
  797. &s->prng, 0, ctx);
  798. if (ret < 0) {
  799. av_log(ctx, AV_LOG_ERROR,
  800. "Expression '%s' for the expr text expansion function is not valid\n",
  801. argv[0]);
  802. return ret;
  803. }
  804. if (!strchr("xXdu", argv[1][0])) {
  805. av_log(ctx, AV_LOG_ERROR, "Invalid format '%c' specified,"
  806. " allowed values: 'x', 'X', 'd', 'u'\n", argv[1][0]);
  807. return AVERROR(EINVAL);
  808. }
  809. if (argc == 3) {
  810. ret = sscanf(argv[2], "%u", &positions);
  811. if (ret != 1) {
  812. av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
  813. " to print: '%s'\n", argv[2]);
  814. return AVERROR(EINVAL);
  815. }
  816. }
  817. feclearexcept(FE_ALL_EXCEPT);
  818. intval = res;
  819. if ((ret = fetestexcept(FE_INVALID|FE_OVERFLOW|FE_UNDERFLOW))) {
  820. av_log(ctx, AV_LOG_ERROR, "Conversion of floating-point result to int failed. Control register: 0x%08x. Conversion result: %d\n", ret, intval);
  821. return AVERROR(EINVAL);
  822. }
  823. if (argc == 3)
  824. av_strlcatf(fmt_str, sizeof(fmt_str), "0%u", positions);
  825. av_strlcatf(fmt_str, sizeof(fmt_str), "%c", argv[1][0]);
  826. av_log(ctx, AV_LOG_DEBUG, "Formatting value %f (expr '%s') with spec '%s'\n",
  827. res, argv[0], fmt_str);
  828. av_bprintf(bp, fmt_str, intval);
  829. return 0;
  830. }
  831. static const struct drawtext_function {
  832. const char *name;
  833. unsigned argc_min, argc_max;
  834. int tag; /**< opaque argument to func */
  835. int (*func)(AVFilterContext *, AVBPrint *, char *, unsigned, char **, int);
  836. } functions[] = {
  837. { "expr", 1, 1, 0, func_eval_expr },
  838. { "e", 1, 1, 0, func_eval_expr },
  839. { "expr_int_format", 2, 3, 0, func_eval_expr_int_format },
  840. { "eif", 2, 3, 0, func_eval_expr_int_format },
  841. { "pict_type", 0, 0, 0, func_pict_type },
  842. { "pts", 0, 3, 0, func_pts },
  843. { "gmtime", 0, 1, 'G', func_strftime },
  844. { "localtime", 0, 1, 'L', func_strftime },
  845. { "frame_num", 0, 0, 0, func_frame_num },
  846. { "n", 0, 0, 0, func_frame_num },
  847. { "metadata", 1, 2, 0, func_metadata },
  848. };
  849. static int eval_function(AVFilterContext *ctx, AVBPrint *bp, char *fct,
  850. unsigned argc, char **argv)
  851. {
  852. unsigned i;
  853. for (i = 0; i < FF_ARRAY_ELEMS(functions); i++) {
  854. if (strcmp(fct, functions[i].name))
  855. continue;
  856. if (argc < functions[i].argc_min) {
  857. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at least %d arguments\n",
  858. fct, functions[i].argc_min);
  859. return AVERROR(EINVAL);
  860. }
  861. if (argc > functions[i].argc_max) {
  862. av_log(ctx, AV_LOG_ERROR, "%%{%s} requires at most %d arguments\n",
  863. fct, functions[i].argc_max);
  864. return AVERROR(EINVAL);
  865. }
  866. break;
  867. }
  868. if (i >= FF_ARRAY_ELEMS(functions)) {
  869. av_log(ctx, AV_LOG_ERROR, "%%{%s} is not known\n", fct);
  870. return AVERROR(EINVAL);
  871. }
  872. return functions[i].func(ctx, bp, fct, argc, argv, functions[i].tag);
  873. }
  874. static int expand_function(AVFilterContext *ctx, AVBPrint *bp, char **rtext)
  875. {
  876. const char *text = *rtext;
  877. char *argv[16] = { NULL };
  878. unsigned argc = 0, i;
  879. int ret;
  880. if (*text != '{') {
  881. av_log(ctx, AV_LOG_ERROR, "Stray %% near '%s'\n", text);
  882. return AVERROR(EINVAL);
  883. }
  884. text++;
  885. while (1) {
  886. if (!(argv[argc++] = av_get_token(&text, ":}"))) {
  887. ret = AVERROR(ENOMEM);
  888. goto end;
  889. }
  890. if (!*text) {
  891. av_log(ctx, AV_LOG_ERROR, "Unterminated %%{} near '%s'\n", *rtext);
  892. ret = AVERROR(EINVAL);
  893. goto end;
  894. }
  895. if (argc == FF_ARRAY_ELEMS(argv))
  896. av_freep(&argv[--argc]); /* error will be caught later */
  897. if (*text == '}')
  898. break;
  899. text++;
  900. }
  901. if ((ret = eval_function(ctx, bp, argv[0], argc - 1, argv + 1)) < 0)
  902. goto end;
  903. ret = 0;
  904. *rtext = (char *)text + 1;
  905. end:
  906. for (i = 0; i < argc; i++)
  907. av_freep(&argv[i]);
  908. return ret;
  909. }
  910. static int expand_text(AVFilterContext *ctx, char *text, AVBPrint *bp)
  911. {
  912. int ret;
  913. av_bprint_clear(bp);
  914. while (*text) {
  915. if (*text == '\\' && text[1]) {
  916. av_bprint_chars(bp, text[1], 1);
  917. text += 2;
  918. } else if (*text == '%') {
  919. text++;
  920. if ((ret = expand_function(ctx, bp, &text)) < 0)
  921. return ret;
  922. } else {
  923. av_bprint_chars(bp, *text, 1);
  924. text++;
  925. }
  926. }
  927. if (!av_bprint_is_complete(bp))
  928. return AVERROR(ENOMEM);
  929. return 0;
  930. }
  931. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  932. int width, int height,
  933. FFDrawColor *color,
  934. int x, int y, int borderw)
  935. {
  936. char *text = s->expanded_text.str;
  937. uint32_t code = 0;
  938. int i, x1, y1;
  939. uint8_t *p;
  940. Glyph *glyph = NULL;
  941. for (i = 0, p = text; *p; i++) {
  942. FT_Bitmap bitmap;
  943. Glyph dummy = { 0 };
  944. GET_UTF8(code, *p++, continue;);
  945. /* skip new line chars, just go to new line */
  946. if (code == '\n' || code == '\r' || code == '\t')
  947. continue;
  948. dummy.code = code;
  949. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  950. bitmap = borderw ? glyph->border_bitmap : glyph->bitmap;
  951. if (glyph->bitmap.pixel_mode != FT_PIXEL_MODE_MONO &&
  952. glyph->bitmap.pixel_mode != FT_PIXEL_MODE_GRAY)
  953. return AVERROR(EINVAL);
  954. x1 = s->positions[i].x+s->x+x - borderw;
  955. y1 = s->positions[i].y+s->y+y - borderw;
  956. ff_blend_mask(&s->dc, color,
  957. frame->data, frame->linesize, width, height,
  958. bitmap.buffer, bitmap.pitch,
  959. bitmap.width, bitmap.rows,
  960. bitmap.pixel_mode == FT_PIXEL_MODE_MONO ? 0 : 3,
  961. 0, x1, y1);
  962. }
  963. return 0;
  964. }
  965. static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
  966. {
  967. *color = incolor;
  968. color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
  969. ff_draw_color(&s->dc, color, color->rgba);
  970. }
  971. static void update_alpha(DrawTextContext *s)
  972. {
  973. double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
  974. if (isnan(alpha))
  975. return;
  976. if (alpha >= 1.0)
  977. s->alpha = 255;
  978. else if (alpha <= 0)
  979. s->alpha = 0;
  980. else
  981. s->alpha = 256 * alpha;
  982. }
  983. static int draw_text(AVFilterContext *ctx, AVFrame *frame,
  984. int width, int height)
  985. {
  986. DrawTextContext *s = ctx->priv;
  987. AVFilterLink *inlink = ctx->inputs[0];
  988. uint32_t code = 0, prev_code = 0;
  989. int x = 0, y = 0, i = 0, ret;
  990. int max_text_line_w = 0, len;
  991. int box_w, box_h;
  992. char *text;
  993. uint8_t *p;
  994. int y_min = 32000, y_max = -32000;
  995. int x_min = 32000, x_max = -32000;
  996. FT_Vector delta;
  997. Glyph *glyph = NULL, *prev_glyph = NULL;
  998. Glyph dummy = { 0 };
  999. time_t now = time(0);
  1000. struct tm ltime;
  1001. AVBPrint *bp = &s->expanded_text;
  1002. FFDrawColor fontcolor;
  1003. FFDrawColor shadowcolor;
  1004. FFDrawColor bordercolor;
  1005. FFDrawColor boxcolor;
  1006. av_bprint_clear(bp);
  1007. if(s->basetime != AV_NOPTS_VALUE)
  1008. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  1009. switch (s->exp_mode) {
  1010. case EXP_NONE:
  1011. av_bprintf(bp, "%s", s->text);
  1012. break;
  1013. case EXP_NORMAL:
  1014. if ((ret = expand_text(ctx, s->text, &s->expanded_text)) < 0)
  1015. return ret;
  1016. break;
  1017. case EXP_STRFTIME:
  1018. localtime_r(&now, &ltime);
  1019. av_bprint_strftime(bp, s->text, &ltime);
  1020. break;
  1021. }
  1022. if (s->tc_opt_string) {
  1023. char tcbuf[AV_TIMECODE_STR_SIZE];
  1024. av_timecode_make_string(&s->tc, tcbuf, inlink->frame_count);
  1025. av_bprint_clear(bp);
  1026. av_bprintf(bp, "%s%s", s->text, tcbuf);
  1027. }
  1028. if (!av_bprint_is_complete(bp))
  1029. return AVERROR(ENOMEM);
  1030. text = s->expanded_text.str;
  1031. if ((len = s->expanded_text.len) > s->nb_positions) {
  1032. if (!(s->positions =
  1033. av_realloc(s->positions, len*sizeof(*s->positions))))
  1034. return AVERROR(ENOMEM);
  1035. s->nb_positions = len;
  1036. }
  1037. if (s->fontcolor_expr[0]) {
  1038. /* If expression is set, evaluate and replace the static value */
  1039. av_bprint_clear(&s->expanded_fontcolor);
  1040. if ((ret = expand_text(ctx, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
  1041. return ret;
  1042. if (!av_bprint_is_complete(&s->expanded_fontcolor))
  1043. return AVERROR(ENOMEM);
  1044. av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
  1045. ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
  1046. if (ret)
  1047. return ret;
  1048. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  1049. }
  1050. x = 0;
  1051. y = 0;
  1052. /* load and cache glyphs */
  1053. for (i = 0, p = text; *p; i++) {
  1054. GET_UTF8(code, *p++, continue;);
  1055. /* get glyph */
  1056. dummy.code = code;
  1057. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1058. if (!glyph) {
  1059. ret = load_glyph(ctx, &glyph, code);
  1060. if (ret < 0)
  1061. return ret;
  1062. }
  1063. y_min = FFMIN(glyph->bbox.yMin, y_min);
  1064. y_max = FFMAX(glyph->bbox.yMax, y_max);
  1065. x_min = FFMIN(glyph->bbox.xMin, x_min);
  1066. x_max = FFMAX(glyph->bbox.xMax, x_max);
  1067. }
  1068. s->max_glyph_h = y_max - y_min;
  1069. s->max_glyph_w = x_max - x_min;
  1070. /* compute and save position for each glyph */
  1071. glyph = NULL;
  1072. for (i = 0, p = text; *p; i++) {
  1073. GET_UTF8(code, *p++, continue;);
  1074. /* skip the \n in the sequence \r\n */
  1075. if (prev_code == '\r' && code == '\n')
  1076. continue;
  1077. prev_code = code;
  1078. if (is_newline(code)) {
  1079. max_text_line_w = FFMAX(max_text_line_w, x);
  1080. y += s->max_glyph_h;
  1081. x = 0;
  1082. continue;
  1083. }
  1084. /* get glyph */
  1085. prev_glyph = glyph;
  1086. dummy.code = code;
  1087. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1088. /* kerning */
  1089. if (s->use_kerning && prev_glyph && glyph->code) {
  1090. FT_Get_Kerning(s->face, prev_glyph->code, glyph->code,
  1091. ft_kerning_default, &delta);
  1092. x += delta.x >> 6;
  1093. }
  1094. /* save position */
  1095. s->positions[i].x = x + glyph->bitmap_left;
  1096. s->positions[i].y = y - glyph->bitmap_top + y_max;
  1097. if (code == '\t') x = (x / s->tabsize + 1)*s->tabsize;
  1098. else x += glyph->advance;
  1099. }
  1100. max_text_line_w = FFMAX(x, max_text_line_w);
  1101. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = max_text_line_w;
  1102. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = y + s->max_glyph_h;
  1103. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  1104. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  1105. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT ] = y_max;
  1106. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = y_min;
  1107. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = s->max_glyph_h;
  1108. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1109. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  1110. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1111. update_alpha(s);
  1112. update_color_with_alpha(s, &fontcolor , s->fontcolor );
  1113. update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
  1114. update_color_with_alpha(s, &bordercolor, s->bordercolor);
  1115. update_color_with_alpha(s, &boxcolor , s->boxcolor );
  1116. box_w = FFMIN(width - 1 , max_text_line_w);
  1117. box_h = FFMIN(height - 1, y + s->max_glyph_h);
  1118. /* draw box */
  1119. if (s->draw_box)
  1120. ff_blend_rectangle(&s->dc, &boxcolor,
  1121. frame->data, frame->linesize, width, height,
  1122. s->x - s->boxborderw, s->y - s->boxborderw,
  1123. box_w + s->boxborderw * 2, box_h + s->boxborderw * 2);
  1124. if (s->shadowx || s->shadowy) {
  1125. if ((ret = draw_glyphs(s, frame, width, height,
  1126. &shadowcolor, s->shadowx, s->shadowy, 0)) < 0)
  1127. return ret;
  1128. }
  1129. if (s->borderw) {
  1130. if ((ret = draw_glyphs(s, frame, width, height,
  1131. &bordercolor, 0, 0, s->borderw)) < 0)
  1132. return ret;
  1133. }
  1134. if ((ret = draw_glyphs(s, frame, width, height,
  1135. &fontcolor, 0, 0, 0)) < 0)
  1136. return ret;
  1137. return 0;
  1138. }
  1139. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  1140. {
  1141. AVFilterContext *ctx = inlink->dst;
  1142. AVFilterLink *outlink = ctx->outputs[0];
  1143. DrawTextContext *s = ctx->priv;
  1144. int ret;
  1145. if (s->reload) {
  1146. if ((ret = load_textfile(ctx)) < 0) {
  1147. av_frame_free(&frame);
  1148. return ret;
  1149. }
  1150. #if CONFIG_LIBFRIBIDI
  1151. if (s->text_shaping)
  1152. if ((ret = shape_text(ctx)) < 0) {
  1153. av_frame_free(&frame);
  1154. return ret;
  1155. }
  1156. #endif
  1157. }
  1158. s->var_values[VAR_N] = inlink->frame_count+s->start_number;
  1159. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  1160. NAN : frame->pts * av_q2d(inlink->time_base);
  1161. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  1162. s->metadata = av_frame_get_metadata(frame);
  1163. draw_text(ctx, frame, frame->width, frame->height);
  1164. av_log(ctx, AV_LOG_DEBUG, "n:%d t:%f text_w:%d text_h:%d x:%d y:%d\n",
  1165. (int)s->var_values[VAR_N], s->var_values[VAR_T],
  1166. (int)s->var_values[VAR_TEXT_W], (int)s->var_values[VAR_TEXT_H],
  1167. s->x, s->y);
  1168. return ff_filter_frame(outlink, frame);
  1169. }
  1170. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  1171. {
  1172. .name = "default",
  1173. .type = AVMEDIA_TYPE_VIDEO,
  1174. .filter_frame = filter_frame,
  1175. .config_props = config_input,
  1176. .needs_writable = 1,
  1177. },
  1178. { NULL }
  1179. };
  1180. static const AVFilterPad avfilter_vf_drawtext_outputs[] = {
  1181. {
  1182. .name = "default",
  1183. .type = AVMEDIA_TYPE_VIDEO,
  1184. },
  1185. { NULL }
  1186. };
  1187. AVFilter ff_vf_drawtext = {
  1188. .name = "drawtext",
  1189. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  1190. .priv_size = sizeof(DrawTextContext),
  1191. .priv_class = &drawtext_class,
  1192. .init = init,
  1193. .uninit = uninit,
  1194. .query_formats = query_formats,
  1195. .inputs = avfilter_vf_drawtext_inputs,
  1196. .outputs = avfilter_vf_drawtext_outputs,
  1197. .process_command = command,
  1198. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
  1199. };