vf_drawtext.c 47 KB

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