vf_drawtext.c 52 KB

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