vf_drawtext.c 39 KB

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