vf_drawtext.c 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919
  1. /*
  2. * Copyright (c) 2023 Francesco Carusi
  3. * Copyright (c) 2011 Stefano Sabatini
  4. * Copyright (c) 2010 S.N. Hemanth Meenakshisundaram
  5. * Copyright (c) 2003 Gustavo Sverzut Barbieri <gsbarbieri@yahoo.com.br>
  6. *
  7. * This file is part of FFmpeg.
  8. *
  9. * FFmpeg is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU Lesser General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2.1 of the License, or (at your option) any later version.
  13. *
  14. * FFmpeg is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * Lesser General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU Lesser General Public
  20. * License along with FFmpeg; if not, write to the Free Software
  21. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  22. */
  23. /**
  24. * @file
  25. * drawtext filter, based on the original vhook/drawtext.c
  26. * filter by Gustavo Sverzut Barbieri
  27. */
  28. #include "config.h"
  29. #if HAVE_SYS_TIME_H
  30. #include <sys/time.h>
  31. #endif
  32. #include <sys/types.h>
  33. #include <sys/stat.h>
  34. #include <time.h>
  35. #if HAVE_UNISTD_H
  36. #include <unistd.h>
  37. #endif
  38. #include <fenv.h>
  39. #if CONFIG_LIBFONTCONFIG
  40. #include <fontconfig/fontconfig.h>
  41. #endif
  42. #include "libavutil/avstring.h"
  43. #include "libavutil/bprint.h"
  44. #include "libavutil/common.h"
  45. #include "libavutil/eval.h"
  46. #include "libavutil/mem.h"
  47. #include "libavutil/opt.h"
  48. #include "libavutil/random_seed.h"
  49. #include "libavutil/parseutils.h"
  50. #include "libavutil/time.h"
  51. #include "libavutil/timecode.h"
  52. #include "libavutil/time_internal.h"
  53. #include "libavutil/tree.h"
  54. #include "libavutil/lfg.h"
  55. #include "libavutil/detection_bbox.h"
  56. #include "avfilter.h"
  57. #include "drawutils.h"
  58. #include "filters.h"
  59. #include "formats.h"
  60. #include "textutils.h"
  61. #include "video.h"
  62. #if CONFIG_LIBFRIBIDI
  63. #include <fribidi.h>
  64. #endif
  65. #include <ft2build.h>
  66. #include FT_FREETYPE_H
  67. #include FT_GLYPH_H
  68. #include FT_STROKER_H
  69. #include <hb.h>
  70. #include <hb-ft.h>
  71. // Ceiling operation for positive integers division
  72. #define POS_CEIL(x, y) ((x)/(y) + ((x)%(y) != 0))
  73. static const char *const var_names[] = {
  74. "dar",
  75. "hsub", "vsub",
  76. "line_h", "lh", ///< line height
  77. "main_h", "h", "H", ///< height of the input video
  78. "main_w", "w", "W", ///< width of the input video
  79. "max_glyph_a", "ascent", ///< max glyph ascender
  80. "max_glyph_d", "descent", ///< min glyph descender
  81. "max_glyph_h", ///< max glyph height
  82. "max_glyph_w", ///< max glyph width
  83. "font_a", ///< font-defined ascent
  84. "font_d", ///< font-defined descent
  85. "top_a", ///< max glyph ascender of the top line
  86. "bottom_d", ///< max glyph descender of the bottom line
  87. "n", ///< number of frame
  88. "sar",
  89. "t", ///< timestamp expressed in seconds
  90. "text_h", "th", ///< height of the rendered text
  91. "text_w", "tw", ///< width of the rendered text
  92. "x",
  93. "y",
  94. "pict_type",
  95. #if FF_API_FRAME_PKT
  96. "pkt_pos",
  97. #endif
  98. #if FF_API_FRAME_PKT
  99. "pkt_size",
  100. #endif
  101. "duration",
  102. NULL
  103. };
  104. static const char *const fun2_names[] = {
  105. "rand"
  106. };
  107. static double drand(void *opaque, double min, double max)
  108. {
  109. return min + (max-min) / UINT_MAX * av_lfg_get(opaque);
  110. }
  111. typedef double (*eval_func2)(void *, double a, double b);
  112. static const eval_func2 fun2[] = {
  113. drand,
  114. NULL
  115. };
  116. enum var_name {
  117. VAR_DAR,
  118. VAR_HSUB, VAR_VSUB,
  119. VAR_LINE_H, VAR_LH,
  120. VAR_MAIN_H, VAR_h, VAR_H,
  121. VAR_MAIN_W, VAR_w, VAR_W,
  122. VAR_MAX_GLYPH_A, VAR_ASCENT,
  123. VAR_MAX_GLYPH_D, VAR_DESCENT,
  124. VAR_MAX_GLYPH_H,
  125. VAR_MAX_GLYPH_W,
  126. VAR_FONT_A,
  127. VAR_FONT_D,
  128. VAR_TOP_A,
  129. VAR_BOTTOM_D,
  130. VAR_N,
  131. VAR_SAR,
  132. VAR_T,
  133. VAR_TEXT_H, VAR_TH,
  134. VAR_TEXT_W, VAR_TW,
  135. VAR_X,
  136. VAR_Y,
  137. VAR_PICT_TYPE,
  138. #if FF_API_FRAME_PKT
  139. VAR_PKT_POS,
  140. #endif
  141. #if FF_API_FRAME_PKT
  142. VAR_PKT_SIZE,
  143. #endif
  144. VAR_DURATION,
  145. VAR_VARS_NB
  146. };
  147. enum expansion_mode {
  148. EXP_NONE,
  149. EXP_NORMAL,
  150. EXP_STRFTIME,
  151. };
  152. enum y_alignment {
  153. YA_TEXT,
  154. YA_BASELINE,
  155. YA_FONT,
  156. };
  157. enum text_alignment {
  158. TA_LEFT = (1 << 0),
  159. TA_RIGHT = (1 << 1),
  160. TA_TOP = (1 << 2),
  161. TA_BOTTOM = (1 << 3),
  162. };
  163. typedef struct HarfbuzzData {
  164. hb_buffer_t* buf;
  165. hb_font_t* font;
  166. unsigned int glyph_count;
  167. hb_glyph_info_t* glyph_info;
  168. hb_glyph_position_t* glyph_pos;
  169. } HarfbuzzData;
  170. /** Information about a single glyph in a text line */
  171. typedef struct GlyphInfo {
  172. uint32_t code; ///< the glyph code point
  173. int x; ///< the x position of the glyph
  174. int y; ///< the y position of the glyph
  175. int shift_x64; ///< the horizontal shift of the glyph in 26.6 units
  176. int shift_y64; ///< the vertical shift of the glyph in 26.6 units
  177. } GlyphInfo;
  178. /** Information about a single line of text */
  179. typedef struct TextLine {
  180. int offset_left64; ///< offset between the origin and
  181. /// the leftmost pixel of the first glyph
  182. int offset_right64; ///< maximum offset between the origin and
  183. /// the rightmost pixel of the last glyph
  184. int width64; ///< width of the line
  185. HarfbuzzData hb_data; ///< libharfbuzz data of this text line
  186. GlyphInfo* glyphs; ///< array of glyphs in this text line
  187. int cluster_offset; ///< the offset at which this line begins
  188. } TextLine;
  189. /** A glyph as loaded and rendered using libfreetype */
  190. typedef struct Glyph {
  191. FT_Glyph glyph;
  192. FT_Glyph border_glyph;
  193. uint32_t code;
  194. unsigned int fontsize;
  195. /** Glyph bitmaps with 1/4 pixel precision in both directions */
  196. FT_BitmapGlyph bglyph[16];
  197. /** Outlined glyph bitmaps with 1/4 pixel precision in both directions */
  198. FT_BitmapGlyph border_bglyph[16];
  199. FT_BBox bbox;
  200. } Glyph;
  201. /** Global text metrics */
  202. typedef struct TextMetrics {
  203. int offset_top64; ///< ascender amount of the first line (in 26.6 units)
  204. int offset_bottom64; ///< descender amount of the last line (in 26.6 units)
  205. int offset_left64; ///< maximum offset between the origin and
  206. /// the leftmost pixel of the first glyph
  207. /// of each line (in 26.6 units)
  208. int offset_right64; ///< maximum offset between the origin and
  209. /// the rightmost pixel of the last glyph
  210. /// of each line (in 26.6 units)
  211. int line_height64; ///< the font-defined line height
  212. int width; ///< width of the longest line - ceil(width64/64)
  213. int height; ///< total height of the text - ceil(height64/64)
  214. int min_y64; ///< minimum value of bbox.yMin among glyphs (in 26.6 units)
  215. int max_y64; ///< maximum value of bbox.yMax among glyphs (in 26.6 units)
  216. int min_x64; ///< minimum value of bbox.xMin among glyphs (in 26.6 units)
  217. int max_x64; ///< maximum value of bbox.xMax among glyphs (in 26.6 units)
  218. // Position of the background box (without borders)
  219. int rect_x; ///< x position of the box
  220. int rect_y; ///< y position of the box
  221. } TextMetrics;
  222. typedef struct DrawTextContext {
  223. const AVClass *class;
  224. int exp_mode; ///< expansion mode to use for the text
  225. FFExpandTextContext expand_text; ///< expand text in case exp_mode == NORMAL
  226. int reinit; ///< tells if the filter is being reinited
  227. #if CONFIG_LIBFONTCONFIG
  228. uint8_t *font; ///< font to be used
  229. #endif
  230. uint8_t *fontfile; ///< font to be used
  231. uint8_t *text; ///< text to be drawn
  232. AVBPrint expanded_text; ///< used to contain the expanded text
  233. uint8_t *fontcolor_expr; ///< fontcolor expression to evaluate
  234. AVBPrint expanded_fontcolor; ///< used to contain the expanded fontcolor spec
  235. int ft_load_flags; ///< flags used for loading fonts, see FT_LOAD_*
  236. char *textfile; ///< file with text to be drawn
  237. double x; ///< x position to start drawing text
  238. double y; ///< y position to start drawing text
  239. int max_glyph_w; ///< max glyph width
  240. int max_glyph_h; ///< max glyph height
  241. int shadowx, shadowy;
  242. int borderw; ///< border width
  243. char *fontsize_expr; ///< expression for fontsize
  244. AVExpr *fontsize_pexpr; ///< parsed expressions for fontsize
  245. unsigned int fontsize; ///< font size to use
  246. unsigned int default_fontsize; ///< default font size to use
  247. int line_spacing; ///< lines spacing in pixels
  248. short int draw_box; ///< draw box around text - true or false
  249. char *boxborderw; ///< box border width (padding)
  250. /// allowed formats: "all", "vert|oriz", "top|right|bottom|left"
  251. int bb_top; ///< the size of the top box border
  252. int bb_right; ///< the size of the right box border
  253. int bb_bottom; ///< the size of the bottom box border
  254. int bb_left; ///< the size of the left box border
  255. int box_width; ///< the width of box
  256. int box_height; ///< the height of box
  257. int tabsize; ///< tab size
  258. int fix_bounds; ///< do we let it go out of frame bounds - t/f
  259. FFDrawContext dc;
  260. FFDrawColor fontcolor; ///< foreground color
  261. FFDrawColor shadowcolor; ///< shadow color
  262. FFDrawColor bordercolor; ///< border color
  263. FFDrawColor boxcolor; ///< background color
  264. FT_Library library; ///< freetype font library handle
  265. FT_Face face; ///< freetype font face handle
  266. FT_Stroker stroker; ///< freetype stroker handle
  267. struct AVTreeNode *glyphs; ///< rendered glyphs, stored using the UTF-32 char code
  268. char *x_expr; ///< expression for x position
  269. char *y_expr; ///< expression for y position
  270. AVExpr *x_pexpr, *y_pexpr; ///< parsed expressions for x and y
  271. int64_t basetime; ///< base pts time in the real world for display
  272. double var_values[VAR_VARS_NB];
  273. char *a_expr;
  274. AVExpr *a_pexpr;
  275. int alpha;
  276. AVLFG prng; ///< random
  277. char *tc_opt_string; ///< specified timecode option string
  278. AVRational tc_rate; ///< frame rate for timecode
  279. AVTimecode tc; ///< timecode context
  280. int tc24hmax; ///< 1 if timecode is wrapped to 24 hours, 0 otherwise
  281. int reload; ///< reload text file at specified frame interval
  282. int start_number; ///< starting frame number for n/frame_num var
  283. char *text_source_string; ///< the string to specify text data source
  284. enum AVFrameSideDataType text_source;
  285. #if CONFIG_LIBFRIBIDI
  286. int text_shaping; ///< 1 to shape the text before drawing it
  287. #endif
  288. AVDictionary *metadata;
  289. int boxw; ///< the value of the boxw parameter
  290. int boxh; ///< the value of the boxh parameter
  291. int text_align; ///< the horizontal and vertical text alignment
  292. int y_align; ///< the value of the y_align parameter
  293. TextLine *lines; ///< computed information about text lines
  294. int line_count; ///< the number of text lines
  295. uint32_t *tab_clusters; ///< the position of tab characters in the text
  296. int tab_count; ///< the number of tab characters
  297. int blank_advance64; ///< the size of the space character
  298. int tab_warning_printed; ///< ensure the tab warning to be printed only once
  299. } DrawTextContext;
  300. #define OFFSET(x) offsetof(DrawTextContext, x)
  301. #define FLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM
  302. #define TFLAGS AV_OPT_FLAG_FILTERING_PARAM|AV_OPT_FLAG_VIDEO_PARAM|AV_OPT_FLAG_RUNTIME_PARAM
  303. static const AVOption drawtext_options[]= {
  304. {"fontfile", "set font file", OFFSET(fontfile), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
  305. {"text", "set text", OFFSET(text), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, TFLAGS},
  306. {"textfile", "set text file", OFFSET(textfile), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
  307. {"fontcolor", "set foreground color", OFFSET(fontcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, TFLAGS},
  308. {"fontcolor_expr", "set foreground color expression", OFFSET(fontcolor_expr), AV_OPT_TYPE_STRING, {.str=""}, 0, 0, FLAGS},
  309. {"boxcolor", "set box color", OFFSET(boxcolor.rgba), AV_OPT_TYPE_COLOR, {.str="white"}, 0, 0, TFLAGS},
  310. {"bordercolor", "set border color", OFFSET(bordercolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, TFLAGS},
  311. {"shadowcolor", "set shadow color", OFFSET(shadowcolor.rgba), AV_OPT_TYPE_COLOR, {.str="black"}, 0, 0, TFLAGS},
  312. {"box", "set box", OFFSET(draw_box), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, TFLAGS},
  313. {"boxborderw", "set box borders width", OFFSET(boxborderw), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, TFLAGS},
  314. {"line_spacing", "set line spacing in pixels", OFFSET(line_spacing), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
  315. {"fontsize", "set font size", OFFSET(fontsize_expr), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, TFLAGS},
  316. {"text_align", "set text alignment", OFFSET(text_align), AV_OPT_TYPE_FLAGS, {.i64=0}, 0, (TA_LEFT|TA_RIGHT|TA_TOP|TA_BOTTOM), TFLAGS, .unit = "text_align"},
  317. { "left", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_LEFT }, .flags = TFLAGS, .unit = "text_align" },
  318. { "L", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_LEFT }, .flags = TFLAGS, .unit = "text_align" },
  319. { "right", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_RIGHT }, .flags = TFLAGS, .unit = "text_align" },
  320. { "R", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_RIGHT }, .flags = TFLAGS, .unit = "text_align" },
  321. { "center", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_LEFT|TA_RIGHT) }, .flags = TFLAGS, .unit = "text_align" },
  322. { "C", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_LEFT|TA_RIGHT) }, .flags = TFLAGS, .unit = "text_align" },
  323. { "top", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_TOP }, .flags = TFLAGS, .unit = "text_align" },
  324. { "T", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_TOP }, .flags = TFLAGS, .unit = "text_align" },
  325. { "bottom", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_BOTTOM }, .flags = TFLAGS, .unit = "text_align" },
  326. { "B", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = TA_BOTTOM }, .flags = TFLAGS, .unit = "text_align" },
  327. { "middle", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_TOP|TA_BOTTOM) }, .flags = TFLAGS, .unit = "text_align" },
  328. { "M", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = (TA_TOP|TA_BOTTOM) }, .flags = TFLAGS, .unit = "text_align" },
  329. {"x", "set x expression", OFFSET(x_expr), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, TFLAGS},
  330. {"y", "set y expression", OFFSET(y_expr), AV_OPT_TYPE_STRING, {.str="0"}, 0, 0, TFLAGS},
  331. {"boxw", "set box width", OFFSET(boxw), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, TFLAGS},
  332. {"boxh", "set box height", OFFSET(boxh), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, TFLAGS},
  333. {"shadowx", "set shadow x offset", OFFSET(shadowx), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
  334. {"shadowy", "set shadow y offset", OFFSET(shadowy), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
  335. {"borderw", "set border width", OFFSET(borderw), AV_OPT_TYPE_INT, {.i64=0}, INT_MIN, INT_MAX, TFLAGS},
  336. {"tabsize", "set tab size", OFFSET(tabsize), AV_OPT_TYPE_INT, {.i64=4}, 0, INT_MAX, TFLAGS},
  337. {"basetime", "set base time", OFFSET(basetime), AV_OPT_TYPE_INT64, {.i64=AV_NOPTS_VALUE}, INT64_MIN, INT64_MAX, FLAGS},
  338. #if CONFIG_LIBFONTCONFIG
  339. { "font", "Font name", OFFSET(font), AV_OPT_TYPE_STRING, { .str = "Sans" }, .flags = FLAGS },
  340. #endif
  341. {"expansion", "set the expansion mode", OFFSET(exp_mode), AV_OPT_TYPE_INT, {.i64=EXP_NORMAL}, 0, 2, FLAGS, .unit = "expansion"},
  342. {"none", "set no expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NONE}, 0, 0, FLAGS, .unit = "expansion"},
  343. {"normal", "set normal expansion", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_NORMAL}, 0, 0, FLAGS, .unit = "expansion"},
  344. {"strftime", "set strftime expansion (deprecated)", OFFSET(exp_mode), AV_OPT_TYPE_CONST, {.i64=EXP_STRFTIME}, 0, 0, FLAGS, .unit = "expansion"},
  345. {"y_align", "set the y alignment", OFFSET(y_align), AV_OPT_TYPE_INT, {.i64=YA_TEXT}, 0, 2, TFLAGS, .unit = "y_align"},
  346. {"text", "y is referred to the top of the first text line", OFFSET(y_align), AV_OPT_TYPE_CONST, {.i64=YA_TEXT}, 0, 0, FLAGS, .unit = "y_align"},
  347. {"baseline", "y is referred to the baseline of the first line", OFFSET(y_align), AV_OPT_TYPE_CONST, {.i64=YA_BASELINE}, 0, 0, FLAGS, .unit = "y_align"},
  348. {"font", "y is referred to the font defined line metrics", OFFSET(y_align), AV_OPT_TYPE_CONST, {.i64=YA_FONT}, 0, 0, FLAGS, .unit = "y_align"},
  349. {"timecode", "set initial timecode", OFFSET(tc_opt_string), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 0, FLAGS},
  350. {"tc24hmax", "set 24 hours max (timecode only)", OFFSET(tc24hmax), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
  351. {"timecode_rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  352. {"r", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  353. {"rate", "set rate (timecode only)", OFFSET(tc_rate), AV_OPT_TYPE_RATIONAL, {.dbl=0}, 0, INT_MAX, FLAGS},
  354. {"reload", "reload text file at specified frame interval", OFFSET(reload), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
  355. {"alpha", "apply alpha while rendering", OFFSET(a_expr), AV_OPT_TYPE_STRING, {.str = "1"}, .flags = TFLAGS},
  356. {"fix_bounds", "check and fix text coords to avoid clipping", OFFSET(fix_bounds), AV_OPT_TYPE_BOOL, {.i64=0}, 0, 1, FLAGS},
  357. {"start_number", "start frame number for n/frame_num variable", OFFSET(start_number), AV_OPT_TYPE_INT, {.i64=0}, 0, INT_MAX, FLAGS},
  358. {"text_source", "the source of text", OFFSET(text_source_string), AV_OPT_TYPE_STRING, {.str=NULL}, 0, 1, FLAGS },
  359. #if CONFIG_LIBFRIBIDI
  360. {"text_shaping", "attempt to shape text before drawing", OFFSET(text_shaping), AV_OPT_TYPE_BOOL, {.i64=1}, 0, 1, FLAGS},
  361. #endif
  362. /* FT_LOAD_* flags */
  363. { "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, .unit = "ft_load_flags" },
  364. { "default", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_DEFAULT }, .flags = FLAGS, .unit = "ft_load_flags" },
  365. { "no_scale", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_SCALE }, .flags = FLAGS, .unit = "ft_load_flags" },
  366. { "no_hinting", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_HINTING }, .flags = FLAGS, .unit = "ft_load_flags" },
  367. { "render", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_RENDER }, .flags = FLAGS, .unit = "ft_load_flags" },
  368. { "no_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  369. { "vertical_layout", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_VERTICAL_LAYOUT }, .flags = FLAGS, .unit = "ft_load_flags" },
  370. { "force_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_FORCE_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  371. { "crop_bitmap", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_CROP_BITMAP }, .flags = FLAGS, .unit = "ft_load_flags" },
  372. { "pedantic", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_PEDANTIC }, .flags = FLAGS, .unit = "ft_load_flags" },
  373. { "ignore_global_advance_width", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_GLOBAL_ADVANCE_WIDTH }, .flags = FLAGS, .unit = "ft_load_flags" },
  374. { "no_recurse", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_RECURSE }, .flags = FLAGS, .unit = "ft_load_flags" },
  375. { "ignore_transform", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_IGNORE_TRANSFORM }, .flags = FLAGS, .unit = "ft_load_flags" },
  376. { "monochrome", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_MONOCHROME }, .flags = FLAGS, .unit = "ft_load_flags" },
  377. { "linear_design", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_LINEAR_DESIGN }, .flags = FLAGS, .unit = "ft_load_flags" },
  378. { "no_autohint", NULL, 0, AV_OPT_TYPE_CONST, { .i64 = FT_LOAD_NO_AUTOHINT }, .flags = FLAGS, .unit = "ft_load_flags" },
  379. { NULL }
  380. };
  381. AVFILTER_DEFINE_CLASS(drawtext);
  382. #undef __FTERRORS_H__
  383. #define FT_ERROR_START_LIST {
  384. #define FT_ERRORDEF(e, v, s) { (e), (s) },
  385. #define FT_ERROR_END_LIST { 0, NULL } };
  386. static const struct ft_error {
  387. int err;
  388. const char *err_msg;
  389. } ft_errors[] =
  390. #include FT_ERRORS_H
  391. #define FT_ERRMSG(e) ft_errors[e].err_msg
  392. static int glyph_cmp(const void *key, const void *b)
  393. {
  394. const Glyph *a = key, *bb = b;
  395. int64_t diff = (int64_t)a->code - (int64_t)bb->code;
  396. if (diff != 0)
  397. return diff > 0 ? 1 : -1;
  398. else
  399. return FFDIFFSIGN((int64_t)a->fontsize, (int64_t)bb->fontsize);
  400. }
  401. static av_cold int set_fontsize(AVFilterContext *ctx, unsigned int fontsize)
  402. {
  403. int err;
  404. DrawTextContext *s = ctx->priv;
  405. if ((err = FT_Set_Pixel_Sizes(s->face, 0, fontsize))) {
  406. av_log(ctx, AV_LOG_ERROR, "Could not set font size to %d pixels: %s\n",
  407. fontsize, FT_ERRMSG(err));
  408. return AVERROR(EINVAL);
  409. }
  410. s->fontsize = fontsize;
  411. return 0;
  412. }
  413. static av_cold int parse_fontsize(AVFilterContext *ctx)
  414. {
  415. DrawTextContext *s = ctx->priv;
  416. int err;
  417. if (s->fontsize_pexpr)
  418. return 0;
  419. if (s->fontsize_expr == NULL)
  420. return AVERROR(EINVAL);
  421. if ((err = av_expr_parse(&s->fontsize_pexpr, s->fontsize_expr, var_names,
  422. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0)
  423. return err;
  424. return 0;
  425. }
  426. static av_cold int update_fontsize(AVFilterContext *ctx)
  427. {
  428. DrawTextContext *s = ctx->priv;
  429. unsigned int fontsize = s->default_fontsize;
  430. int err;
  431. double size, roundedsize;
  432. // if no fontsize specified use the default
  433. if (s->fontsize_expr != NULL) {
  434. if ((err = parse_fontsize(ctx)) < 0)
  435. return err;
  436. size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
  437. if (!isnan(size)) {
  438. roundedsize = round(size);
  439. // test for overflow before cast
  440. if (!(roundedsize > INT_MIN && roundedsize < INT_MAX)) {
  441. av_log(ctx, AV_LOG_ERROR, "fontsize overflow\n");
  442. return AVERROR(EINVAL);
  443. }
  444. fontsize = roundedsize;
  445. }
  446. }
  447. if (fontsize == 0)
  448. fontsize = 1;
  449. // no change
  450. if (fontsize == s->fontsize)
  451. return 0;
  452. return set_fontsize(ctx, fontsize);
  453. }
  454. static int load_font_file(AVFilterContext *ctx, const char *path, int index)
  455. {
  456. DrawTextContext *s = ctx->priv;
  457. int err;
  458. err = FT_New_Face(s->library, path, index, &s->face);
  459. if (err) {
  460. #if !CONFIG_LIBFONTCONFIG
  461. av_log(ctx, AV_LOG_ERROR, "Could not load font \"%s\": %s\n",
  462. s->fontfile, FT_ERRMSG(err));
  463. #endif
  464. return AVERROR(EINVAL);
  465. }
  466. return 0;
  467. }
  468. #if CONFIG_LIBFONTCONFIG
  469. static int load_font_fontconfig(AVFilterContext *ctx)
  470. {
  471. DrawTextContext *s = ctx->priv;
  472. FcConfig *fontconfig;
  473. FcPattern *pat, *best;
  474. FcResult result = FcResultMatch;
  475. FcChar8 *filename;
  476. int index;
  477. double size;
  478. int err = AVERROR(ENOENT);
  479. int parse_err;
  480. fontconfig = FcInitLoadConfigAndFonts();
  481. if (!fontconfig) {
  482. av_log(ctx, AV_LOG_ERROR, "impossible to init fontconfig\n");
  483. return AVERROR_UNKNOWN;
  484. }
  485. pat = FcNameParse(s->fontfile ? s->fontfile :
  486. (uint8_t *)(intptr_t)"default");
  487. if (!pat) {
  488. av_log(ctx, AV_LOG_ERROR, "could not parse fontconfig pat");
  489. return AVERROR(EINVAL);
  490. }
  491. FcPatternAddString(pat, FC_FAMILY, s->font);
  492. parse_err = parse_fontsize(ctx);
  493. if (!parse_err) {
  494. double size = av_expr_eval(s->fontsize_pexpr, s->var_values, &s->prng);
  495. if (isnan(size)) {
  496. av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
  497. return AVERROR(EINVAL);
  498. }
  499. FcPatternAddDouble(pat, FC_SIZE, size);
  500. }
  501. FcDefaultSubstitute(pat);
  502. if (!FcConfigSubstitute(fontconfig, pat, FcMatchPattern)) {
  503. av_log(ctx, AV_LOG_ERROR, "could not substitue fontconfig options"); /* very unlikely */
  504. FcPatternDestroy(pat);
  505. return AVERROR(ENOMEM);
  506. }
  507. best = FcFontMatch(fontconfig, pat, &result);
  508. FcPatternDestroy(pat);
  509. if (!best || result != FcResultMatch) {
  510. av_log(ctx, AV_LOG_ERROR,
  511. "Cannot find a valid font for the family %s\n",
  512. s->font);
  513. goto fail;
  514. }
  515. if (
  516. FcPatternGetInteger(best, FC_INDEX, 0, &index ) != FcResultMatch ||
  517. FcPatternGetDouble (best, FC_SIZE, 0, &size ) != FcResultMatch) {
  518. av_log(ctx, AV_LOG_ERROR, "impossible to find font information");
  519. return AVERROR(EINVAL);
  520. }
  521. if (FcPatternGetString(best, FC_FILE, 0, &filename) != FcResultMatch) {
  522. av_log(ctx, AV_LOG_ERROR, "No file path for %s\n",
  523. s->font);
  524. goto fail;
  525. }
  526. av_log(ctx, AV_LOG_VERBOSE, "Using \"%s\"\n", filename);
  527. if (parse_err)
  528. s->default_fontsize = size + 0.5;
  529. err = load_font_file(ctx, filename, index);
  530. if (err)
  531. return err;
  532. FcConfigDestroy(fontconfig);
  533. fail:
  534. FcPatternDestroy(best);
  535. return err;
  536. }
  537. #endif
  538. static int load_font(AVFilterContext *ctx)
  539. {
  540. DrawTextContext *s = ctx->priv;
  541. int err;
  542. /* load the face, and set up the encoding, which is by default UTF-8 */
  543. err = load_font_file(ctx, s->fontfile, 0);
  544. if (!err)
  545. return 0;
  546. #if CONFIG_LIBFONTCONFIG
  547. err = load_font_fontconfig(ctx);
  548. if (!err)
  549. return 0;
  550. #endif
  551. return err;
  552. }
  553. #if CONFIG_LIBFRIBIDI
  554. static int shape_text(AVFilterContext *ctx)
  555. {
  556. DrawTextContext *s = ctx->priv;
  557. uint8_t *tmp;
  558. int ret = AVERROR(ENOMEM);
  559. static const FriBidiFlags flags = FRIBIDI_FLAGS_DEFAULT |
  560. FRIBIDI_FLAGS_ARABIC;
  561. FriBidiChar *unicodestr = NULL;
  562. FriBidiStrIndex len;
  563. FriBidiParType direction = FRIBIDI_PAR_LTR;
  564. FriBidiStrIndex line_start = 0;
  565. FriBidiStrIndex line_end = 0;
  566. FriBidiLevel *embedding_levels = NULL;
  567. FriBidiArabicProp *ar_props = NULL;
  568. FriBidiCharType *bidi_types = NULL;
  569. FriBidiStrIndex i,j;
  570. len = strlen(s->text);
  571. if (!(unicodestr = av_malloc_array(len, sizeof(*unicodestr)))) {
  572. goto out;
  573. }
  574. len = fribidi_charset_to_unicode(FRIBIDI_CHAR_SET_UTF8,
  575. s->text, len, unicodestr);
  576. bidi_types = av_malloc_array(len, sizeof(*bidi_types));
  577. if (!bidi_types) {
  578. goto out;
  579. }
  580. fribidi_get_bidi_types(unicodestr, len, bidi_types);
  581. embedding_levels = av_malloc_array(len, sizeof(*embedding_levels));
  582. if (!embedding_levels) {
  583. goto out;
  584. }
  585. if (!fribidi_get_par_embedding_levels(bidi_types, len, &direction,
  586. embedding_levels)) {
  587. goto out;
  588. }
  589. ar_props = av_malloc_array(len, sizeof(*ar_props));
  590. if (!ar_props) {
  591. goto out;
  592. }
  593. fribidi_get_joining_types(unicodestr, len, ar_props);
  594. fribidi_join_arabic(bidi_types, len, embedding_levels, ar_props);
  595. fribidi_shape(flags, embedding_levels, len, ar_props, unicodestr);
  596. for (line_end = 0, line_start = 0; line_end < len; line_end++) {
  597. if (ff_is_newline(unicodestr[line_end]) || line_end == len - 1) {
  598. if (!fribidi_reorder_line(flags, bidi_types,
  599. line_end - line_start + 1, line_start,
  600. direction, embedding_levels, unicodestr,
  601. NULL)) {
  602. goto out;
  603. }
  604. line_start = line_end + 1;
  605. }
  606. }
  607. /* Remove zero-width fill chars put in by libfribidi */
  608. for (i = 0, j = 0; i < len; i++)
  609. if (unicodestr[i] != FRIBIDI_CHAR_FILL)
  610. unicodestr[j++] = unicodestr[i];
  611. len = j;
  612. if (!(tmp = av_realloc(s->text, (len * 4 + 1) * sizeof(*s->text)))) {
  613. /* Use len * 4, as a unicode character can be up to 4 bytes in UTF-8 */
  614. goto out;
  615. }
  616. s->text = tmp;
  617. len = fribidi_unicode_to_charset(FRIBIDI_CHAR_SET_UTF8,
  618. unicodestr, len, s->text);
  619. ret = 0;
  620. out:
  621. av_free(unicodestr);
  622. av_free(embedding_levels);
  623. av_free(ar_props);
  624. av_free(bidi_types);
  625. return ret;
  626. }
  627. #endif
  628. static enum AVFrameSideDataType text_source_string_parse(const char *text_source_string)
  629. {
  630. av_assert0(text_source_string);
  631. if (!strcmp(text_source_string, "side_data_detection_bboxes")) {
  632. return AV_FRAME_DATA_DETECTION_BBOXES;
  633. } else {
  634. return AVERROR(EINVAL);
  635. }
  636. }
  637. static inline int get_subpixel_idx(int shift_x64, int shift_y64)
  638. {
  639. int idx = (shift_x64 >> 2) + (shift_y64 >> 4);
  640. return idx;
  641. }
  642. // Loads and (optionally) renders a glyph
  643. static int load_glyph(AVFilterContext *ctx, Glyph **glyph_ptr, uint32_t code, int8_t shift_x64, int8_t shift_y64)
  644. {
  645. DrawTextContext *s = ctx->priv;
  646. Glyph dummy = { 0 };
  647. Glyph *glyph;
  648. FT_Vector shift;
  649. struct AVTreeNode *node = NULL;
  650. int ret = 0;
  651. /* get glyph */
  652. dummy.code = code;
  653. dummy.fontsize = s->fontsize;
  654. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  655. if (!glyph) {
  656. if (FT_Load_Glyph(s->face, code, s->ft_load_flags)) {
  657. return AVERROR(EINVAL);
  658. }
  659. glyph = av_mallocz(sizeof(*glyph));
  660. if (!glyph) {
  661. ret = AVERROR(ENOMEM);
  662. goto error;
  663. }
  664. glyph->code = code;
  665. glyph->fontsize = s->fontsize;
  666. if (FT_Get_Glyph(s->face->glyph, &glyph->glyph)) {
  667. ret = AVERROR(EINVAL);
  668. goto error;
  669. }
  670. if (s->borderw) {
  671. glyph->border_glyph = glyph->glyph;
  672. if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0)) {
  673. ret = AVERROR_EXTERNAL;
  674. goto error;
  675. }
  676. }
  677. /* measure text height to calculate text_height (or the maximum text height) */
  678. FT_Glyph_Get_CBox(glyph->glyph, FT_GLYPH_BBOX_SUBPIXELS, &glyph->bbox);
  679. /* cache the newly created glyph */
  680. if (!(node = av_tree_node_alloc())) {
  681. ret = AVERROR(ENOMEM);
  682. goto error;
  683. }
  684. av_tree_insert(&s->glyphs, glyph, glyph_cmp, &node);
  685. } else {
  686. if (s->borderw && !glyph->border_glyph) {
  687. glyph->border_glyph = glyph->glyph;
  688. if (FT_Glyph_StrokeBorder(&glyph->border_glyph, s->stroker, 0, 0)) {
  689. ret = AVERROR_EXTERNAL;
  690. goto error;
  691. }
  692. }
  693. }
  694. // Check if a bitmap is needed
  695. if (shift_x64 >= 0 && shift_y64 >= 0) {
  696. // Get the bitmap subpixel index (0 -> 15)
  697. int idx = get_subpixel_idx(shift_x64, shift_y64);
  698. shift.x = shift_x64;
  699. shift.y = shift_y64;
  700. if (!glyph->bglyph[idx]) {
  701. FT_Glyph tmp_glyph = glyph->glyph;
  702. if (FT_Glyph_To_Bitmap(&tmp_glyph, FT_RENDER_MODE_NORMAL, &shift, 0)) {
  703. ret = AVERROR_EXTERNAL;
  704. goto error;
  705. }
  706. glyph->bglyph[idx] = (FT_BitmapGlyph)tmp_glyph;
  707. if (glyph->bglyph[idx]->bitmap.pixel_mode == FT_PIXEL_MODE_MONO) {
  708. av_log(ctx, AV_LOG_ERROR, "Monocromatic (1bpp) fonts are not supported.\n");
  709. ret = AVERROR(EINVAL);
  710. goto error;
  711. }
  712. }
  713. if (s->borderw && !glyph->border_bglyph[idx]) {
  714. FT_Glyph tmp_glyph = glyph->border_glyph;
  715. if (FT_Glyph_To_Bitmap(&tmp_glyph, FT_RENDER_MODE_NORMAL, &shift, 0)) {
  716. ret = AVERROR_EXTERNAL;
  717. goto error;
  718. }
  719. glyph->border_bglyph[idx] = (FT_BitmapGlyph)tmp_glyph;
  720. }
  721. }
  722. if (glyph_ptr) {
  723. *glyph_ptr = glyph;
  724. }
  725. return 0;
  726. error:
  727. if (glyph && glyph->glyph)
  728. FT_Done_Glyph(glyph->glyph);
  729. av_freep(&glyph);
  730. av_freep(&node);
  731. return ret;
  732. }
  733. // Convert a string formatted as "n1|n2|...|nN" into an integer array
  734. static int string_to_array(const char *source, int *result, int result_size)
  735. {
  736. int counter = 0, size = strlen(source) + 1;
  737. char *saveptr, *curval, *dup = av_malloc(size);
  738. if (!dup)
  739. return 0;
  740. av_strlcpy(dup, source, size);
  741. if (result_size > 0 && (curval = av_strtok(dup, "|", &saveptr))) {
  742. do {
  743. result[counter++] = atoi(curval);
  744. } while ((curval = av_strtok(NULL, "|", &saveptr)) && counter < result_size);
  745. }
  746. av_free(dup);
  747. return counter;
  748. }
  749. static int func_pict_type(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  750. {
  751. DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
  752. av_bprintf(bp, "%c", av_get_picture_type_char(s->var_values[VAR_PICT_TYPE]));
  753. return 0;
  754. }
  755. static int func_pts(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  756. {
  757. DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
  758. const char *fmt;
  759. const char *strftime_fmt = NULL;
  760. const char *delta = NULL;
  761. double pts = s->var_values[VAR_T];
  762. // argv: pts, FMT, [DELTA, 24HH | strftime_fmt]
  763. fmt = argc >= 1 ? argv[0] : "flt";
  764. if (argc >= 2) {
  765. delta = argv[1];
  766. }
  767. if (argc >= 3) {
  768. if (!strcmp(fmt, "hms")) {
  769. if (!strcmp(argv[2], "24HH")) {
  770. av_log(ctx, AV_LOG_WARNING, "pts third argument 24HH is deprected, use pts:hms24hh instead\n");
  771. fmt = "hms24";
  772. } else {
  773. av_log(ctx, AV_LOG_ERROR, "Invalid argument '%s', '24HH' was expected\n", argv[2]);
  774. return AVERROR(EINVAL);
  775. }
  776. } else {
  777. strftime_fmt = argv[2];
  778. }
  779. }
  780. return ff_print_pts(ctx, bp, pts, delta, fmt, strftime_fmt);
  781. }
  782. static int func_frame_num(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  783. {
  784. DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
  785. av_bprintf(bp, "%d", (int)s->var_values[VAR_N]);
  786. return 0;
  787. }
  788. static int func_metadata(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  789. {
  790. DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
  791. AVDictionaryEntry *e = av_dict_get(s->metadata, argv[0], NULL, 0);
  792. if (e && e->value)
  793. av_bprintf(bp, "%s", e->value);
  794. else if (argc >= 2)
  795. av_bprintf(bp, "%s", argv[1]);
  796. return 0;
  797. }
  798. static int func_strftime(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  799. {
  800. const char *strftime_fmt = argc ? argv[0] : NULL;
  801. return ff_print_time(ctx, bp, strftime_fmt, !strcmp(function_name, "localtime"));
  802. }
  803. static int func_eval_expr(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  804. {
  805. DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
  806. return ff_print_eval_expr(ctx, bp, argv[0],
  807. fun2_names, fun2,
  808. var_names, s->var_values, &s->prng);
  809. }
  810. static int func_eval_expr_int_format(void *ctx, AVBPrint *bp, const char *function_name, unsigned argc, char **argv)
  811. {
  812. DrawTextContext *s = ((AVFilterContext *)ctx)->priv;
  813. int ret;
  814. int positions = -1;
  815. /*
  816. * argv[0] expression to be converted to `int`
  817. * argv[1] format: 'x', 'X', 'd' or 'u'
  818. * argv[2] positions printed (optional)
  819. */
  820. if (argc == 3) {
  821. ret = sscanf(argv[2], "%u", &positions);
  822. if (ret != 1) {
  823. av_log(ctx, AV_LOG_ERROR, "expr_int_format(): Invalid number of positions"
  824. " to print: '%s'\n", argv[2]);
  825. return AVERROR(EINVAL);
  826. }
  827. }
  828. return ff_print_formatted_eval_expr(ctx, bp, argv[0],
  829. fun2_names, fun2,
  830. var_names, s->var_values,
  831. &s->prng,
  832. argv[1][0], positions);
  833. }
  834. static const FFExpandTextFunction expand_text_functions[] = {
  835. { "e", 1, 1, func_eval_expr },
  836. { "eif", 2, 3, func_eval_expr_int_format },
  837. { "expr", 1, 1, func_eval_expr },
  838. { "expr_int_format", 2, 3, func_eval_expr_int_format },
  839. { "frame_num", 0, 0, func_frame_num },
  840. { "gmtime", 0, 1, func_strftime },
  841. { "localtime", 0, 1, func_strftime },
  842. { "metadata", 1, 2, func_metadata },
  843. { "n", 0, 0, func_frame_num },
  844. { "pict_type", 0, 0, func_pict_type },
  845. { "pts", 0, 3, func_pts }
  846. };
  847. static av_cold int init(AVFilterContext *ctx)
  848. {
  849. int err;
  850. DrawTextContext *s = ctx->priv;
  851. av_expr_free(s->fontsize_pexpr);
  852. s->fontsize_pexpr = NULL;
  853. s->fontsize = 0;
  854. s->default_fontsize = 16;
  855. if (!s->fontfile && !CONFIG_LIBFONTCONFIG) {
  856. av_log(ctx, AV_LOG_ERROR, "No font filename provided\n");
  857. return AVERROR(EINVAL);
  858. }
  859. if (s->textfile) {
  860. if (s->text) {
  861. av_log(ctx, AV_LOG_ERROR,
  862. "Both text and text file provided. Please provide only one\n");
  863. return AVERROR(EINVAL);
  864. }
  865. if ((err = ff_load_textfile(ctx, (const char *)s->textfile, &s->text, NULL)) < 0)
  866. return err;
  867. }
  868. if (s->reload && !s->textfile)
  869. av_log(ctx, AV_LOG_WARNING, "No file to reload\n");
  870. if (s->tc_opt_string) {
  871. int ret = av_timecode_init_from_string(&s->tc, s->tc_rate,
  872. s->tc_opt_string, ctx);
  873. if (ret < 0)
  874. return ret;
  875. if (s->tc24hmax)
  876. s->tc.flags |= AV_TIMECODE_FLAG_24HOURSMAX;
  877. if (!s->text)
  878. s->text = av_strdup("");
  879. }
  880. if (s->text_source_string) {
  881. s->text_source = text_source_string_parse(s->text_source_string);
  882. if ((int)s->text_source < 0) {
  883. av_log(ctx, AV_LOG_ERROR, "Error text source: %s\n", s->text_source_string);
  884. return AVERROR(EINVAL);
  885. }
  886. }
  887. if (s->text_source == AV_FRAME_DATA_DETECTION_BBOXES) {
  888. if (s->text) {
  889. av_log(ctx, AV_LOG_WARNING, "Multiple texts provided, will use text_source only\n");
  890. av_free(s->text);
  891. }
  892. s->text = av_mallocz((AV_DETECTION_BBOX_LABEL_NAME_MAX_SIZE + 1) *
  893. (AV_NUM_DETECTION_BBOX_CLASSIFY + 1));
  894. if (!s->text)
  895. return AVERROR(ENOMEM);
  896. }
  897. if (!s->text) {
  898. av_log(ctx, AV_LOG_ERROR,
  899. "Either text, a valid file, a timecode or text source must be provided\n");
  900. return AVERROR(EINVAL);
  901. }
  902. s->expand_text = (FFExpandTextContext) {
  903. .log_ctx = ctx,
  904. .functions = expand_text_functions,
  905. .functions_nb = FF_ARRAY_ELEMS(expand_text_functions)
  906. };
  907. #if CONFIG_LIBFRIBIDI
  908. if (s->text_shaping)
  909. if ((err = shape_text(ctx)) < 0)
  910. return err;
  911. #endif
  912. if ((err = FT_Init_FreeType(&(s->library)))) {
  913. av_log(ctx, AV_LOG_ERROR,
  914. "Could not load FreeType: %s\n", FT_ERRMSG(err));
  915. return AVERROR(EINVAL);
  916. }
  917. if ((err = load_font(ctx)) < 0)
  918. return err;
  919. if ((err = update_fontsize(ctx)) < 0)
  920. return err;
  921. // Always init the stroker, may be needed if borderw is set via command
  922. if (FT_Stroker_New(s->library, &s->stroker)) {
  923. av_log(ctx, AV_LOG_ERROR, "Could not init FT stroker\n");
  924. return AVERROR_EXTERNAL;
  925. }
  926. if (s->borderw) {
  927. FT_Stroker_Set(s->stroker, s->borderw << 6, FT_STROKER_LINECAP_ROUND,
  928. FT_STROKER_LINEJOIN_ROUND, 0);
  929. }
  930. /* load the fallback glyph with code 0 */
  931. load_glyph(ctx, NULL, 0, 0, 0);
  932. if (s->exp_mode == EXP_STRFTIME &&
  933. (strchr(s->text, '%') || strchr(s->text, '\\')))
  934. av_log(ctx, AV_LOG_WARNING, "expansion=strftime is deprecated.\n");
  935. av_bprint_init(&s->expanded_text, 0, AV_BPRINT_SIZE_UNLIMITED);
  936. av_bprint_init(&s->expanded_fontcolor, 0, AV_BPRINT_SIZE_UNLIMITED);
  937. return 0;
  938. }
  939. static int query_formats(AVFilterContext *ctx)
  940. {
  941. return ff_set_common_formats(ctx, ff_draw_supported_pixel_formats(0));
  942. }
  943. static int glyph_enu_border_free(void *opaque, void *elem)
  944. {
  945. Glyph *glyph = elem;
  946. if (glyph->border_glyph != NULL) {
  947. for (int t = 0; t < 16; ++t) {
  948. if (glyph->border_bglyph[t] != NULL) {
  949. FT_Done_Glyph((FT_Glyph)glyph->border_bglyph[t]);
  950. glyph->border_bglyph[t] = NULL;
  951. }
  952. }
  953. FT_Done_Glyph(glyph->border_glyph);
  954. glyph->border_glyph = NULL;
  955. }
  956. return 0;
  957. }
  958. static int glyph_enu_free(void *opaque, void *elem)
  959. {
  960. Glyph *glyph = elem;
  961. FT_Done_Glyph(glyph->glyph);
  962. FT_Done_Glyph(glyph->border_glyph);
  963. for (int t = 0; t < 16; ++t) {
  964. if (glyph->bglyph[t] != NULL) {
  965. FT_Done_Glyph((FT_Glyph)glyph->bglyph[t]);
  966. }
  967. if (glyph->border_bglyph[t] != NULL) {
  968. FT_Done_Glyph((FT_Glyph)glyph->border_bglyph[t]);
  969. }
  970. }
  971. av_free(elem);
  972. return 0;
  973. }
  974. static av_cold void uninit(AVFilterContext *ctx)
  975. {
  976. DrawTextContext *s = ctx->priv;
  977. av_expr_free(s->x_pexpr);
  978. av_expr_free(s->y_pexpr);
  979. av_expr_free(s->a_pexpr);
  980. av_expr_free(s->fontsize_pexpr);
  981. s->x_pexpr = s->y_pexpr = s->a_pexpr = s->fontsize_pexpr = NULL;
  982. av_tree_enumerate(s->glyphs, NULL, NULL, glyph_enu_free);
  983. av_tree_destroy(s->glyphs);
  984. s->glyphs = NULL;
  985. FT_Done_Face(s->face);
  986. FT_Stroker_Done(s->stroker);
  987. FT_Done_FreeType(s->library);
  988. av_bprint_finalize(&s->expanded_text, NULL);
  989. av_bprint_finalize(&s->expanded_fontcolor, NULL);
  990. }
  991. static int config_input(AVFilterLink *inlink)
  992. {
  993. AVFilterContext *ctx = inlink->dst;
  994. DrawTextContext *s = ctx->priv;
  995. char *expr;
  996. int ret;
  997. ff_draw_init2(&s->dc, inlink->format, inlink->colorspace, inlink->color_range, FF_DRAW_PROCESS_ALPHA);
  998. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  999. ff_draw_color(&s->dc, &s->shadowcolor, s->shadowcolor.rgba);
  1000. ff_draw_color(&s->dc, &s->bordercolor, s->bordercolor.rgba);
  1001. ff_draw_color(&s->dc, &s->boxcolor, s->boxcolor.rgba);
  1002. s->var_values[VAR_w] = s->var_values[VAR_W] = s->var_values[VAR_MAIN_W] = inlink->w;
  1003. s->var_values[VAR_h] = s->var_values[VAR_H] = s->var_values[VAR_MAIN_H] = inlink->h;
  1004. s->var_values[VAR_SAR] = inlink->sample_aspect_ratio.num ? av_q2d(inlink->sample_aspect_ratio) : 1;
  1005. s->var_values[VAR_DAR] = (double)inlink->w / inlink->h * s->var_values[VAR_SAR];
  1006. s->var_values[VAR_HSUB] = 1 << s->dc.hsub_max;
  1007. s->var_values[VAR_VSUB] = 1 << s->dc.vsub_max;
  1008. s->var_values[VAR_X] = NAN;
  1009. s->var_values[VAR_Y] = NAN;
  1010. s->var_values[VAR_T] = NAN;
  1011. av_lfg_init(&s->prng, av_get_random_seed());
  1012. av_expr_free(s->x_pexpr);
  1013. av_expr_free(s->y_pexpr);
  1014. av_expr_free(s->a_pexpr);
  1015. s->x_pexpr = s->y_pexpr = s->a_pexpr = NULL;
  1016. if ((ret = av_expr_parse(&s->x_pexpr, expr = s->x_expr, var_names,
  1017. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  1018. (ret = av_expr_parse(&s->y_pexpr, expr = s->y_expr, var_names,
  1019. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0 ||
  1020. (ret = av_expr_parse(&s->a_pexpr, expr = s->a_expr, var_names,
  1021. NULL, NULL, fun2_names, fun2, 0, ctx)) < 0) {
  1022. av_log(ctx, AV_LOG_ERROR, "Failed to parse expression: %s \n", expr);
  1023. return AVERROR(EINVAL);
  1024. }
  1025. return 0;
  1026. }
  1027. static int command(AVFilterContext *ctx, const char *cmd, const char *arg, char *res, int res_len, int flags)
  1028. {
  1029. DrawTextContext *old = ctx->priv;
  1030. DrawTextContext *new = NULL;
  1031. int ret;
  1032. if (!strcmp(cmd, "reinit")) {
  1033. new = av_mallocz(sizeof(DrawTextContext));
  1034. if (!new)
  1035. return AVERROR(ENOMEM);
  1036. new->class = &drawtext_class;
  1037. ret = av_opt_copy(new, old);
  1038. if (ret < 0)
  1039. goto fail;
  1040. ctx->priv = new;
  1041. ret = av_set_options_string(ctx, arg, "=", ":");
  1042. if (ret < 0) {
  1043. ctx->priv = old;
  1044. goto fail;
  1045. }
  1046. ret = init(ctx);
  1047. if (ret < 0) {
  1048. uninit(ctx);
  1049. ctx->priv = old;
  1050. goto fail;
  1051. }
  1052. new->reinit = 1;
  1053. ctx->priv = old;
  1054. uninit(ctx);
  1055. av_opt_free(old);
  1056. av_freep(&old);
  1057. ctx->priv = new;
  1058. return config_input(ctx->inputs[0]);
  1059. } else {
  1060. int old_borderw = old->borderw;
  1061. if ((ret = ff_filter_process_command(ctx, cmd, arg, res, res_len, flags)) < 0) {
  1062. return ret;
  1063. }
  1064. if (old->borderw != old_borderw) {
  1065. FT_Stroker_Set(old->stroker, old->borderw << 6, FT_STROKER_LINECAP_ROUND,
  1066. FT_STROKER_LINEJOIN_ROUND, 0);
  1067. // Dispose the old border glyphs
  1068. av_tree_enumerate(old->glyphs, NULL, NULL, glyph_enu_border_free);
  1069. } else if (strcmp(cmd, "fontsize") == 0) {
  1070. av_expr_free(old->fontsize_pexpr);
  1071. old->fontsize_pexpr = NULL;
  1072. old->blank_advance64 = 0;
  1073. }
  1074. return config_input(ctx->inputs[0]);
  1075. }
  1076. fail:
  1077. av_log(ctx, AV_LOG_ERROR, "Failed to process command. Continuing with existing parameters.\n");
  1078. av_freep(&new);
  1079. return ret;
  1080. }
  1081. static void update_color_with_alpha(DrawTextContext *s, FFDrawColor *color, const FFDrawColor incolor)
  1082. {
  1083. *color = incolor;
  1084. color->rgba[3] = (color->rgba[3] * s->alpha) / 255;
  1085. ff_draw_color(&s->dc, color, color->rgba);
  1086. }
  1087. static void update_alpha(DrawTextContext *s)
  1088. {
  1089. double alpha = av_expr_eval(s->a_pexpr, s->var_values, &s->prng);
  1090. if (isnan(alpha))
  1091. return;
  1092. if (alpha >= 1.0)
  1093. s->alpha = 255;
  1094. else if (alpha <= 0)
  1095. s->alpha = 0;
  1096. else
  1097. s->alpha = 256 * alpha;
  1098. }
  1099. static int draw_glyphs(DrawTextContext *s, AVFrame *frame,
  1100. FFDrawColor *color,
  1101. TextMetrics *metrics,
  1102. int x, int y, int borderw)
  1103. {
  1104. int g, l, x1, y1, w1, h1, idx;
  1105. int dx = 0, dy = 0, pdx = 0;
  1106. GlyphInfo *info;
  1107. Glyph dummy = { 0 }, *glyph;
  1108. FT_Bitmap bitmap;
  1109. FT_BitmapGlyph b_glyph;
  1110. uint8_t j_left = 0, j_right = 0, j_top = 0, j_bottom = 0;
  1111. int line_w, offset_y = 0;
  1112. int clip_x = 0, clip_y = 0;
  1113. j_left = !!(s->text_align & TA_LEFT);
  1114. j_right = !!(s->text_align & TA_RIGHT);
  1115. j_top = !!(s->text_align & TA_TOP);
  1116. j_bottom = !!(s->text_align & TA_BOTTOM);
  1117. if (j_top && j_bottom) {
  1118. offset_y = (s->box_height - metrics->height) / 2;
  1119. } else if (j_bottom) {
  1120. offset_y = s->box_height - metrics->height;
  1121. }
  1122. if ((!j_left || j_right) && !s->tab_warning_printed && s->tab_count > 0) {
  1123. s->tab_warning_printed = 1;
  1124. av_log(s, AV_LOG_WARNING, "Tab characters are only supported with left horizontal alignment\n");
  1125. }
  1126. clip_x = FFMIN(metrics->rect_x + s->box_width + s->bb_right, frame->width);
  1127. clip_y = FFMIN(metrics->rect_y + s->box_height + s->bb_bottom, frame->height);
  1128. for (l = 0; l < s->line_count; ++l) {
  1129. TextLine *line = &s->lines[l];
  1130. line_w = POS_CEIL(line->width64, 64);
  1131. for (g = 0; g < line->hb_data.glyph_count; ++g) {
  1132. info = &line->glyphs[g];
  1133. dummy.fontsize = s->fontsize;
  1134. dummy.code = info->code;
  1135. glyph = av_tree_find(s->glyphs, &dummy, glyph_cmp, NULL);
  1136. if (!glyph) {
  1137. return AVERROR(EINVAL);
  1138. }
  1139. idx = get_subpixel_idx(info->shift_x64, info->shift_y64);
  1140. b_glyph = borderw ? glyph->border_bglyph[idx] : glyph->bglyph[idx];
  1141. bitmap = b_glyph->bitmap;
  1142. x1 = x + info->x + b_glyph->left;
  1143. y1 = y + info->y - b_glyph->top + offset_y;
  1144. w1 = bitmap.width;
  1145. h1 = bitmap.rows;
  1146. if (j_left && j_right) {
  1147. x1 += (s->box_width - line_w) / 2;
  1148. } else if (j_right) {
  1149. x1 += s->box_width - line_w;
  1150. }
  1151. // Offset of the glyph's bitmap in the visible region
  1152. dx = dy = 0;
  1153. if (x1 < metrics->rect_x - s->bb_left) {
  1154. dx = metrics->rect_x - s->bb_left - x1;
  1155. x1 = metrics->rect_x - s->bb_left;
  1156. }
  1157. if (y1 < metrics->rect_y - s->bb_top) {
  1158. dy = metrics->rect_y - s->bb_top - y1;
  1159. y1 = metrics->rect_y - s->bb_top;
  1160. }
  1161. // check if the glyph is empty or out of the clipping region
  1162. if (dx >= w1 || dy >= h1 || x1 >= clip_x || y1 >= clip_y) {
  1163. continue;
  1164. }
  1165. pdx = dx + dy * bitmap.pitch;
  1166. w1 = FFMIN(clip_x - x1, w1 - dx);
  1167. h1 = FFMIN(clip_y - y1, h1 - dy);
  1168. ff_blend_mask(&s->dc, color, frame->data, frame->linesize, clip_x, clip_y,
  1169. bitmap.buffer + pdx, bitmap.pitch, w1, h1, 3, 0, x1, y1);
  1170. }
  1171. }
  1172. return 0;
  1173. }
  1174. // Shapes a line of text using libharfbuzz
  1175. static int shape_text_hb(DrawTextContext *s, HarfbuzzData* hb, const char* text, int textLen)
  1176. {
  1177. hb->buf = hb_buffer_create();
  1178. if(!hb_buffer_allocation_successful(hb->buf)) {
  1179. return AVERROR(ENOMEM);
  1180. }
  1181. hb_buffer_set_direction(hb->buf, HB_DIRECTION_LTR);
  1182. hb_buffer_set_script(hb->buf, HB_SCRIPT_LATIN);
  1183. hb_buffer_set_language(hb->buf, hb_language_from_string("en", -1));
  1184. hb_buffer_guess_segment_properties(hb->buf);
  1185. hb->font = hb_ft_font_create(s->face, NULL);
  1186. if(hb->font == NULL) {
  1187. return AVERROR(ENOMEM);
  1188. }
  1189. hb_ft_font_set_funcs(hb->font);
  1190. hb_buffer_add_utf8(hb->buf, text, textLen, 0, -1);
  1191. hb_shape(hb->font, hb->buf, NULL, 0);
  1192. hb->glyph_info = hb_buffer_get_glyph_infos(hb->buf, &hb->glyph_count);
  1193. hb->glyph_pos = hb_buffer_get_glyph_positions(hb->buf, &hb->glyph_count);
  1194. return 0;
  1195. }
  1196. static void hb_destroy(HarfbuzzData *hb)
  1197. {
  1198. hb_buffer_destroy(hb->buf);
  1199. hb_font_destroy(hb->font);
  1200. hb->buf = NULL;
  1201. hb->font = NULL;
  1202. hb->glyph_info = NULL;
  1203. hb->glyph_pos = NULL;
  1204. }
  1205. static int measure_text(AVFilterContext *ctx, TextMetrics *metrics)
  1206. {
  1207. DrawTextContext *s = ctx->priv;
  1208. char *text = s->expanded_text.str;
  1209. char *textdup = NULL;
  1210. int width64 = 0, w64 = 0;
  1211. int cur_min_y64 = 0, first_max_y64 = -32000;
  1212. int first_min_x64 = 32000, last_max_x64 = -32000;
  1213. int min_y64 = 32000, max_y64 = -32000, min_x64 = 32000, max_x64 = -32000;
  1214. int line_count = 0;
  1215. uint32_t code = 0;
  1216. Glyph *glyph = NULL;
  1217. int i, tab_idx = 0, last_tab_idx = 0, line_offset = 0;
  1218. uint8_t *start, *p;
  1219. int ret = 0;
  1220. // Count the lines and the tab characters
  1221. s->tab_count = 0;
  1222. for (i = 0, p = text; 1; i++) {
  1223. GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_failed;);
  1224. continue_on_failed:
  1225. if (ff_is_newline(code) || code == 0) {
  1226. ++line_count;
  1227. if (code == 0) {
  1228. break;
  1229. }
  1230. } else if (code == '\t') {
  1231. ++s->tab_count;
  1232. }
  1233. }
  1234. // Evaluate the width of the space character if needed to replace tabs
  1235. if (s->tab_count > 0 && !s->blank_advance64) {
  1236. HarfbuzzData hb_data;
  1237. ret = shape_text_hb(s, &hb_data, " ", 1);
  1238. if(ret != 0) {
  1239. goto done;
  1240. }
  1241. s->blank_advance64 = hb_data.glyph_pos[0].x_advance;
  1242. hb_destroy(&hb_data);
  1243. }
  1244. s->line_count = line_count;
  1245. s->lines = av_mallocz(line_count * sizeof(TextLine));
  1246. s->tab_clusters = av_mallocz(s->tab_count * sizeof(uint32_t));
  1247. for (i = 0; i < s->tab_count; ++i) {
  1248. s->tab_clusters[i] = -1;
  1249. }
  1250. start = textdup = av_strdup(text);
  1251. if (textdup == NULL) {
  1252. ret = AVERROR(ENOMEM);
  1253. goto done;
  1254. }
  1255. line_count = 0;
  1256. for (i = 0, p = textdup; 1; i++) {
  1257. if (*p == '\t') {
  1258. s->tab_clusters[tab_idx++] = i;
  1259. *p = ' ';
  1260. }
  1261. GET_UTF8(code, *p ? *p++ : 0, code = 0xfffd; goto continue_on_failed2;);
  1262. continue_on_failed2:
  1263. if (ff_is_newline(code) || code == 0) {
  1264. TextLine *cur_line = &s->lines[line_count];
  1265. HarfbuzzData *hb = &cur_line->hb_data;
  1266. cur_line->cluster_offset = line_offset;
  1267. ret = shape_text_hb(s, hb, start, p - start);
  1268. if (ret != 0) {
  1269. goto done;
  1270. }
  1271. w64 = 0;
  1272. cur_min_y64 = 32000;
  1273. for (int t = 0; t < hb->glyph_count; ++t) {
  1274. uint8_t is_tab = last_tab_idx < s->tab_count &&
  1275. hb->glyph_info[t].cluster == s->tab_clusters[last_tab_idx] - line_offset;
  1276. if (is_tab) {
  1277. ++last_tab_idx;
  1278. }
  1279. ret = load_glyph(ctx, &glyph, hb->glyph_info[t].codepoint, -1, -1);
  1280. if (ret != 0) {
  1281. goto done;
  1282. }
  1283. if (line_count == 0) {
  1284. first_max_y64 = FFMAX(glyph->bbox.yMax, first_max_y64);
  1285. }
  1286. if (t == 0) {
  1287. cur_line->offset_left64 = glyph->bbox.xMin;
  1288. first_min_x64 = FFMIN(glyph->bbox.xMin, first_min_x64);
  1289. }
  1290. if (t == hb->glyph_count - 1) {
  1291. // The following code measures the width of the line up to the last
  1292. // character's horizontal advance
  1293. int last_char_width = hb->glyph_pos[t].x_advance;
  1294. // The following code measures the width of the line up to the rightmost
  1295. // visible pixel of the last character
  1296. // int last_char_width = glyph->bbox.xMax;
  1297. w64 += last_char_width;
  1298. last_max_x64 = FFMAX(last_char_width, last_max_x64);
  1299. cur_line->offset_right64 = last_char_width;
  1300. } else {
  1301. if (is_tab) {
  1302. int size = s->blank_advance64 * s->tabsize;
  1303. w64 = (w64 / size + 1) * size;
  1304. } else {
  1305. w64 += hb->glyph_pos[t].x_advance;
  1306. }
  1307. }
  1308. cur_min_y64 = FFMIN(glyph->bbox.yMin, cur_min_y64);
  1309. min_y64 = FFMIN(glyph->bbox.yMin, min_y64);
  1310. max_y64 = FFMAX(glyph->bbox.yMax, max_y64);
  1311. min_x64 = FFMIN(glyph->bbox.xMin, min_x64);
  1312. max_x64 = FFMAX(glyph->bbox.xMax, max_x64);
  1313. }
  1314. cur_line->width64 = w64;
  1315. av_log(s, AV_LOG_DEBUG, " Line: %d -- glyphs count: %d - width64: %d - offset_left64: %d - offset_right64: %d)\n",
  1316. line_count, hb->glyph_count, cur_line->width64, cur_line->offset_left64, cur_line->offset_right64);
  1317. if (w64 > width64) {
  1318. width64 = w64;
  1319. }
  1320. start = p;
  1321. ++line_count;
  1322. line_offset = i + 1;
  1323. }
  1324. if (code == 0) break;
  1325. }
  1326. metrics->line_height64 = s->face->size->metrics.height;
  1327. metrics->width = POS_CEIL(width64, 64);
  1328. if (s->y_align == YA_FONT) {
  1329. metrics->height = POS_CEIL(metrics->line_height64 * line_count, 64);
  1330. } else {
  1331. int height64 = (metrics->line_height64 + s->line_spacing * 64) *
  1332. (FFMAX(0, line_count - 1)) + first_max_y64 - cur_min_y64;
  1333. metrics->height = POS_CEIL(height64, 64);
  1334. }
  1335. metrics->offset_top64 = first_max_y64;
  1336. metrics->offset_right64 = last_max_x64;
  1337. metrics->offset_bottom64 = cur_min_y64;
  1338. metrics->offset_left64 = first_min_x64;
  1339. metrics->min_x64 = min_x64;
  1340. metrics->min_y64 = min_y64;
  1341. metrics->max_x64 = max_x64;
  1342. metrics->max_y64 = max_y64;
  1343. done:
  1344. av_free(textdup);
  1345. return ret;
  1346. }
  1347. static int draw_text(AVFilterContext *ctx, AVFrame *frame)
  1348. {
  1349. DrawTextContext *s = ctx->priv;
  1350. AVFilterLink *inlink = ctx->inputs[0];
  1351. FilterLink *inl = ff_filter_link(inlink);
  1352. int x = 0, y = 0, ret;
  1353. int shift_x64, shift_y64;
  1354. int x64, y64;
  1355. Glyph *glyph = NULL;
  1356. time_t now = time(0);
  1357. struct tm ltime;
  1358. AVBPrint *bp = &s->expanded_text;
  1359. FFDrawColor fontcolor;
  1360. FFDrawColor shadowcolor;
  1361. FFDrawColor bordercolor;
  1362. FFDrawColor boxcolor;
  1363. int width = frame->width;
  1364. int height = frame->height;
  1365. int rec_x = 0, rec_y = 0, rec_width = 0, rec_height = 0;
  1366. int is_outside = 0;
  1367. int last_tab_idx = 0;
  1368. TextMetrics metrics;
  1369. av_bprint_clear(bp);
  1370. if (s->basetime != AV_NOPTS_VALUE)
  1371. now= frame->pts*av_q2d(ctx->inputs[0]->time_base) + s->basetime/1000000;
  1372. switch (s->exp_mode) {
  1373. case EXP_NONE:
  1374. av_bprintf(bp, "%s", s->text);
  1375. break;
  1376. case EXP_NORMAL:
  1377. if ((ret = ff_expand_text(&s->expand_text, s->text, &s->expanded_text)) < 0)
  1378. return ret;
  1379. break;
  1380. case EXP_STRFTIME:
  1381. localtime_r(&now, &ltime);
  1382. av_bprint_strftime(bp, s->text, &ltime);
  1383. break;
  1384. }
  1385. if (s->tc_opt_string) {
  1386. char tcbuf[AV_TIMECODE_STR_SIZE];
  1387. av_timecode_make_string(&s->tc, tcbuf, inl->frame_count_out);
  1388. av_bprint_clear(bp);
  1389. av_bprintf(bp, "%s%s", s->text, tcbuf);
  1390. }
  1391. if (!av_bprint_is_complete(bp))
  1392. return AVERROR(ENOMEM);
  1393. if (s->fontcolor_expr[0]) {
  1394. /* If expression is set, evaluate and replace the static value */
  1395. av_bprint_clear(&s->expanded_fontcolor);
  1396. if ((ret = ff_expand_text(&s->expand_text, s->fontcolor_expr, &s->expanded_fontcolor)) < 0)
  1397. return ret;
  1398. if (!av_bprint_is_complete(&s->expanded_fontcolor))
  1399. return AVERROR(ENOMEM);
  1400. av_log(s, AV_LOG_DEBUG, "Evaluated fontcolor is '%s'\n", s->expanded_fontcolor.str);
  1401. ret = av_parse_color(s->fontcolor.rgba, s->expanded_fontcolor.str, -1, s);
  1402. if (ret)
  1403. return ret;
  1404. ff_draw_color(&s->dc, &s->fontcolor, s->fontcolor.rgba);
  1405. }
  1406. if ((ret = update_fontsize(ctx)) < 0) {
  1407. return ret;
  1408. }
  1409. if ((ret = measure_text(ctx, &metrics)) < 0) {
  1410. return ret;
  1411. }
  1412. s->max_glyph_h = POS_CEIL(metrics.max_y64 - metrics.min_y64, 64);
  1413. s->max_glyph_w = POS_CEIL(metrics.max_x64 - metrics.min_x64, 64);
  1414. s->var_values[VAR_TW] = s->var_values[VAR_TEXT_W] = metrics.width;
  1415. s->var_values[VAR_TH] = s->var_values[VAR_TEXT_H] = metrics.height;
  1416. s->var_values[VAR_MAX_GLYPH_W] = s->max_glyph_w;
  1417. s->var_values[VAR_MAX_GLYPH_H] = s->max_glyph_h;
  1418. s->var_values[VAR_MAX_GLYPH_A] = s->var_values[VAR_ASCENT] = POS_CEIL(metrics.max_y64, 64);
  1419. s->var_values[VAR_FONT_A] = s->face->size->metrics.ascender / 64;
  1420. s->var_values[VAR_MAX_GLYPH_D] = s->var_values[VAR_DESCENT] = POS_CEIL(metrics.min_y64, 64);
  1421. s->var_values[VAR_FONT_D] = -s->face->size->metrics.descender / 64;
  1422. s->var_values[VAR_TOP_A] = POS_CEIL(metrics.offset_top64, 64);
  1423. s->var_values[VAR_BOTTOM_D] = -POS_CEIL(metrics.offset_bottom64, 64);
  1424. s->var_values[VAR_LINE_H] = s->var_values[VAR_LH] = metrics.line_height64 / 64.;
  1425. if (s->text_source == AV_FRAME_DATA_DETECTION_BBOXES) {
  1426. s->var_values[VAR_X] = s->x;
  1427. s->var_values[VAR_Y] = s->y;
  1428. } else {
  1429. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1430. s->y = s->var_values[VAR_Y] = av_expr_eval(s->y_pexpr, s->var_values, &s->prng);
  1431. /* It is necessary if x is expressed from y */
  1432. s->x = s->var_values[VAR_X] = av_expr_eval(s->x_pexpr, s->var_values, &s->prng);
  1433. }
  1434. update_alpha(s);
  1435. update_color_with_alpha(s, &fontcolor , s->fontcolor );
  1436. update_color_with_alpha(s, &shadowcolor, s->shadowcolor);
  1437. update_color_with_alpha(s, &bordercolor, s->bordercolor);
  1438. update_color_with_alpha(s, &boxcolor , s->boxcolor );
  1439. if (s->draw_box && s->boxborderw) {
  1440. int bbsize[4];
  1441. int count;
  1442. count = string_to_array(s->boxborderw, bbsize, 4);
  1443. if (count == 1) {
  1444. s->bb_top = s->bb_right = s->bb_bottom = s->bb_left = bbsize[0];
  1445. } else if (count == 2) {
  1446. s->bb_top = s->bb_bottom = bbsize[0];
  1447. s->bb_right = s->bb_left = bbsize[1];
  1448. } else if (count == 3) {
  1449. s->bb_top = bbsize[0];
  1450. s->bb_right = s->bb_left = bbsize[1];
  1451. s->bb_bottom = bbsize[2];
  1452. } else if (count == 4) {
  1453. s->bb_top = bbsize[0];
  1454. s->bb_right = bbsize[1];
  1455. s->bb_bottom = bbsize[2];
  1456. s->bb_left = bbsize[3];
  1457. }
  1458. } else {
  1459. s->bb_top = s->bb_right = s->bb_bottom = s->bb_left = 0;
  1460. }
  1461. if (s->fix_bounds) {
  1462. /* calculate footprint of text effects */
  1463. int borderoffset = s->borderw ? FFMAX(s->borderw, 0) : 0;
  1464. int offsetleft = FFMAX3(FFMAX(s->bb_left, 0), borderoffset,
  1465. (s->shadowx < 0 ? FFABS(s->shadowx) : 0));
  1466. int offsettop = FFMAX3(FFMAX(s->bb_top, 0), borderoffset,
  1467. (s->shadowy < 0 ? FFABS(s->shadowy) : 0));
  1468. int offsetright = FFMAX3(FFMAX(s->bb_right, 0), borderoffset,
  1469. (s->shadowx > 0 ? s->shadowx : 0));
  1470. int offsetbottom = FFMAX3(FFMAX(s->bb_bottom, 0), borderoffset,
  1471. (s->shadowy > 0 ? s->shadowy : 0));
  1472. if (s->x - offsetleft < 0) s->x = offsetleft;
  1473. if (s->y - offsettop < 0) s->y = offsettop;
  1474. if (s->x + metrics.width + offsetright > width)
  1475. s->x = FFMAX(width - metrics.width - offsetright, 0);
  1476. if (s->y + metrics.height + offsetbottom > height)
  1477. s->y = FFMAX(height - metrics.height - offsetbottom, 0);
  1478. }
  1479. x = 0;
  1480. y = 0;
  1481. x64 = (int)(s->x * 64.);
  1482. if (s->y_align == YA_FONT) {
  1483. y64 = (int)(s->y * 64. + s->face->size->metrics.ascender);
  1484. } else if (s->y_align == YA_BASELINE) {
  1485. y64 = (int)(s->y * 64.);
  1486. } else {
  1487. y64 = (int)(s->y * 64. + metrics.offset_top64);
  1488. }
  1489. for (int l = 0; l < s->line_count; ++l) {
  1490. TextLine *line = &s->lines[l];
  1491. HarfbuzzData *hb = &line->hb_data;
  1492. line->glyphs = av_mallocz(hb->glyph_count * sizeof(GlyphInfo));
  1493. for (int t = 0; t < hb->glyph_count; ++t) {
  1494. GlyphInfo *g_info = &line->glyphs[t];
  1495. uint8_t is_tab = last_tab_idx < s->tab_count &&
  1496. hb->glyph_info[t].cluster == s->tab_clusters[last_tab_idx] - line->cluster_offset;
  1497. int true_x, true_y;
  1498. if (is_tab) {
  1499. ++last_tab_idx;
  1500. }
  1501. true_x = x + hb->glyph_pos[t].x_offset;
  1502. true_y = y + hb->glyph_pos[t].y_offset;
  1503. shift_x64 = (((x64 + true_x) >> 4) & 0b0011) << 4;
  1504. shift_y64 = ((4 - (((y64 + true_y) >> 4) & 0b0011)) & 0b0011) << 4;
  1505. ret = load_glyph(ctx, &glyph, hb->glyph_info[t].codepoint, shift_x64, shift_y64);
  1506. if (ret != 0) {
  1507. return ret;
  1508. }
  1509. g_info->code = hb->glyph_info[t].codepoint;
  1510. g_info->x = (x64 + true_x) >> 6;
  1511. g_info->y = ((y64 + true_y) >> 6) + (shift_y64 > 0 ? 1 : 0);
  1512. g_info->shift_x64 = shift_x64;
  1513. g_info->shift_y64 = shift_y64;
  1514. if (!is_tab) {
  1515. x += hb->glyph_pos[t].x_advance;
  1516. } else {
  1517. int size = s->blank_advance64 * s->tabsize;
  1518. x = (x / size + 1) * size;
  1519. }
  1520. y += hb->glyph_pos[t].y_advance;
  1521. }
  1522. y += metrics.line_height64 + s->line_spacing * 64;
  1523. x = 0;
  1524. }
  1525. metrics.rect_x = s->x;
  1526. if (s->y_align == YA_BASELINE) {
  1527. metrics.rect_y = s->y - metrics.offset_top64 / 64;
  1528. } else {
  1529. metrics.rect_y = s->y;
  1530. }
  1531. s->box_width = s->boxw == 0 ? metrics.width : s->boxw;
  1532. s->box_height = s->boxh == 0 ? metrics.height : s->boxh;
  1533. if (!s->draw_box) {
  1534. // Create a border for the clipping region to take into account subpixel
  1535. // errors in text measurement and effects.
  1536. int borderoffset = s->borderw ? FFMAX(s->borderw, 0) : 0;
  1537. s->bb_left = borderoffset + (s->shadowx < 0 ? FFABS(s->shadowx) : 0) + 1;
  1538. s->bb_top = borderoffset + (s->shadowy < 0 ? FFABS(s->shadowy) : 0) + 1;
  1539. s->bb_right = borderoffset + (s->shadowx > 0 ? s->shadowx : 0) + 1;
  1540. s->bb_bottom = borderoffset + (s->shadowy > 0 ? s->shadowy : 0) + 1;
  1541. }
  1542. /* Check if the whole box is out of the frame */
  1543. is_outside = metrics.rect_x - s->bb_left >= width ||
  1544. metrics.rect_y - s->bb_top >= height ||
  1545. metrics.rect_x + s->box_width + s->bb_right <= 0 ||
  1546. metrics.rect_y + s->box_height + s->bb_bottom <= 0;
  1547. if (!is_outside) {
  1548. /* draw box */
  1549. if (s->draw_box) {
  1550. rec_x = metrics.rect_x - s->bb_left;
  1551. rec_y = metrics.rect_y - s->bb_top;
  1552. rec_width = s->box_width + s->bb_right + s->bb_left;
  1553. rec_height = s->box_height + s->bb_bottom + s->bb_top;
  1554. ff_blend_rectangle(&s->dc, &boxcolor,
  1555. frame->data, frame->linesize, width, height,
  1556. rec_x, rec_y, rec_width, rec_height);
  1557. }
  1558. if (s->shadowx || s->shadowy) {
  1559. if ((ret = draw_glyphs(s, frame, &shadowcolor, &metrics,
  1560. s->shadowx, s->shadowy, s->borderw)) < 0) {
  1561. return ret;
  1562. }
  1563. }
  1564. if (s->borderw) {
  1565. if ((ret = draw_glyphs(s, frame, &bordercolor, &metrics,
  1566. 0, 0, s->borderw)) < 0) {
  1567. return ret;
  1568. }
  1569. }
  1570. if ((ret = draw_glyphs(s, frame, &fontcolor, &metrics, 0,
  1571. 0, 0)) < 0) {
  1572. return ret;
  1573. }
  1574. }
  1575. // FREE data structures
  1576. for (int l = 0; l < s->line_count; ++l) {
  1577. TextLine *line = &s->lines[l];
  1578. av_freep(&line->glyphs);
  1579. hb_destroy(&line->hb_data);
  1580. }
  1581. av_freep(&s->lines);
  1582. av_freep(&s->tab_clusters);
  1583. return 0;
  1584. }
  1585. static int filter_frame(AVFilterLink *inlink, AVFrame *frame)
  1586. {
  1587. FilterLink *inl = ff_filter_link(inlink);
  1588. AVFilterContext *ctx = inlink->dst;
  1589. AVFilterLink *outlink = ctx->outputs[0];
  1590. DrawTextContext *s = ctx->priv;
  1591. int ret;
  1592. const AVDetectionBBoxHeader *header = NULL;
  1593. const AVDetectionBBox *bbox;
  1594. AVFrameSideData *sd;
  1595. int loop = 1;
  1596. if (s->text_source == AV_FRAME_DATA_DETECTION_BBOXES) {
  1597. sd = av_frame_get_side_data(frame, AV_FRAME_DATA_DETECTION_BBOXES);
  1598. if (sd) {
  1599. header = (AVDetectionBBoxHeader *)sd->data;
  1600. loop = header->nb_bboxes;
  1601. } else {
  1602. av_log(s, AV_LOG_WARNING, "No detection bboxes.\n");
  1603. return ff_filter_frame(outlink, frame);
  1604. }
  1605. }
  1606. if (s->reload && !(inl->frame_count_out % s->reload)) {
  1607. if ((ret = ff_load_textfile(ctx, (const char *)s->textfile, &s->text, NULL)) < 0) {
  1608. av_frame_free(&frame);
  1609. return ret;
  1610. }
  1611. #if CONFIG_LIBFRIBIDI
  1612. if (s->text_shaping)
  1613. if ((ret = shape_text(ctx)) < 0) {
  1614. av_frame_free(&frame);
  1615. return ret;
  1616. }
  1617. #endif
  1618. }
  1619. s->var_values[VAR_N] = inl->frame_count_out + s->start_number;
  1620. s->var_values[VAR_T] = frame->pts == AV_NOPTS_VALUE ?
  1621. NAN : frame->pts * av_q2d(inlink->time_base);
  1622. s->var_values[VAR_PICT_TYPE] = frame->pict_type;
  1623. #if FF_API_FRAME_PKT
  1624. FF_DISABLE_DEPRECATION_WARNINGS
  1625. s->var_values[VAR_PKT_POS] = frame->pkt_pos;
  1626. s->var_values[VAR_PKT_SIZE] = frame->pkt_size;
  1627. FF_ENABLE_DEPRECATION_WARNINGS
  1628. #endif
  1629. s->var_values[VAR_DURATION] = frame->duration * av_q2d(inlink->time_base);
  1630. s->metadata = frame->metadata;
  1631. for (int i = 0; i < loop; i++) {
  1632. if (header) {
  1633. bbox = av_get_detection_bbox(header, i);
  1634. strcpy(s->text, bbox->detect_label);
  1635. for (int j = 0; j < bbox->classify_count; j++) {
  1636. strcat(s->text, ", ");
  1637. strcat(s->text, bbox->classify_labels[j]);
  1638. }
  1639. s->x = bbox->x;
  1640. s->y = bbox->y - s->fontsize;
  1641. }
  1642. draw_text(ctx, frame);
  1643. }
  1644. return ff_filter_frame(outlink, frame);
  1645. }
  1646. static const AVFilterPad avfilter_vf_drawtext_inputs[] = {
  1647. {
  1648. .name = "default",
  1649. .type = AVMEDIA_TYPE_VIDEO,
  1650. .flags = AVFILTERPAD_FLAG_NEEDS_WRITABLE,
  1651. .filter_frame = filter_frame,
  1652. .config_props = config_input,
  1653. },
  1654. };
  1655. const AVFilter ff_vf_drawtext = {
  1656. .name = "drawtext",
  1657. .description = NULL_IF_CONFIG_SMALL("Draw text on top of video frames using libfreetype library."),
  1658. .priv_size = sizeof(DrawTextContext),
  1659. .priv_class = &drawtext_class,
  1660. .init = init,
  1661. .uninit = uninit,
  1662. FILTER_INPUTS(avfilter_vf_drawtext_inputs),
  1663. FILTER_OUTPUTS(ff_video_default_filterpad),
  1664. FILTER_QUERY_FUNC(query_formats),
  1665. .process_command = command,
  1666. .flags = AVFILTER_FLAG_SUPPORT_TIMELINE_GENERIC,
  1667. };