obs-text.cpp 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165
  1. #include <graphics/math-defs.h>
  2. #include <util/platform.h>
  3. #include <util/util.hpp>
  4. #include <obs-module.h>
  5. #include <sys/stat.h>
  6. #include <combaseapi.h>
  7. #include <gdiplus.h>
  8. #include <algorithm>
  9. #include <string>
  10. #include <memory>
  11. #include <locale>
  12. using namespace std;
  13. using namespace Gdiplus;
  14. #define warning(format, ...) blog(LOG_WARNING, "[%s] " format, obs_source_get_name(source), ##__VA_ARGS__)
  15. #define warn_stat(call) \
  16. do { \
  17. if (stat != Ok) \
  18. warning("%s: %s failed (%d)", __FUNCTION__, call, (int)stat); \
  19. } while (false)
  20. #ifndef clamp
  21. #define clamp(val, min_val, max_val) \
  22. if (val < min_val) \
  23. val = min_val; \
  24. else if (val > max_val) \
  25. val = max_val;
  26. #endif
  27. #define MIN_SIZE_CX 2
  28. #define MIN_SIZE_CY 2
  29. #define MAX_SIZE_CX 16384
  30. #define MAX_SIZE_CY 16384
  31. #define MAX_AREA (4096LL * 4096LL)
  32. /* ------------------------------------------------------------------------- */
  33. /* clang-format off */
  34. #define S_FONT "font"
  35. #define S_USE_FILE "read_from_file"
  36. #define S_FILE "file"
  37. #define S_TEXT "text"
  38. #define S_COLOR "color"
  39. #define S_GRADIENT "gradient"
  40. #define S_GRADIENT_COLOR "gradient_color"
  41. #define S_GRADIENT_DIR "gradient_dir"
  42. #define S_GRADIENT_OPACITY "gradient_opacity"
  43. #define S_ALIGN "align"
  44. #define S_VALIGN "valign"
  45. #define S_OPACITY "opacity"
  46. #define S_BKCOLOR "bk_color"
  47. #define S_BKOPACITY "bk_opacity"
  48. #define S_VERTICAL "vertical"
  49. #define S_OUTLINE "outline"
  50. #define S_OUTLINE_SIZE "outline_size"
  51. #define S_OUTLINE_COLOR "outline_color"
  52. #define S_OUTLINE_OPACITY "outline_opacity"
  53. #define S_CHATLOG_MODE "chatlog"
  54. #define S_CHATLOG_LINES "chatlog_lines"
  55. #define S_EXTENTS "extents"
  56. #define S_EXTENTS_WRAP "extents_wrap"
  57. #define S_EXTENTS_CX "extents_cx"
  58. #define S_EXTENTS_CY "extents_cy"
  59. #define S_TRANSFORM "transform"
  60. #define S_ANTIALIASING "antialiasing"
  61. #define S_ALIGN_LEFT "left"
  62. #define S_ALIGN_CENTER "center"
  63. #define S_ALIGN_RIGHT "right"
  64. #define S_VALIGN_TOP "top"
  65. #define S_VALIGN_CENTER S_ALIGN_CENTER
  66. #define S_VALIGN_BOTTOM "bottom"
  67. #define S_TRANSFORM_NONE 0
  68. #define S_TRANSFORM_UPPERCASE 1
  69. #define S_TRANSFORM_LOWERCASE 2
  70. #define S_TRANSFORM_STARTCASE 3
  71. #define T_(v) obs_module_text(v)
  72. #define T_FONT T_("Font")
  73. #define T_USE_FILE T_("ReadFromFile")
  74. #define T_FILE T_("TextFile")
  75. #define T_TEXT T_("Text")
  76. #define T_COLOR T_("Color")
  77. #define T_GRADIENT T_("Gradient")
  78. #define T_GRADIENT_COLOR T_("Gradient.Color")
  79. #define T_GRADIENT_DIR T_("Gradient.Direction")
  80. #define T_GRADIENT_OPACITY T_("Gradient.Opacity")
  81. #define T_ALIGN T_("Alignment")
  82. #define T_VALIGN T_("VerticalAlignment")
  83. #define T_OPACITY T_("Opacity")
  84. #define T_BKCOLOR T_("BkColor")
  85. #define T_BKOPACITY T_("BkOpacity")
  86. #define T_VERTICAL T_("Vertical")
  87. #define T_OUTLINE T_("Outline")
  88. #define T_OUTLINE_SIZE T_("Outline.Size")
  89. #define T_OUTLINE_COLOR T_("Outline.Color")
  90. #define T_OUTLINE_OPACITY T_("Outline.Opacity")
  91. #define T_CHATLOG_MODE T_("ChatlogMode")
  92. #define T_CHATLOG_LINES T_("ChatlogMode.Lines")
  93. #define T_EXTENTS T_("UseCustomExtents")
  94. #define T_EXTENTS_WRAP T_("UseCustomExtents.Wrap")
  95. #define T_EXTENTS_CX T_("Width")
  96. #define T_EXTENTS_CY T_("Height")
  97. #define T_TRANSFORM T_("Transform")
  98. #define T_ANTIALIASING T_("Antialiasing")
  99. #define T_FILTER_TEXT_FILES T_("Filter.TextFiles")
  100. #define T_FILTER_ALL_FILES T_("Filter.AllFiles")
  101. #define T_ALIGN_LEFT T_("Alignment.Left")
  102. #define T_ALIGN_CENTER T_("Alignment.Center")
  103. #define T_ALIGN_RIGHT T_("Alignment.Right")
  104. #define T_VALIGN_TOP T_("VerticalAlignment.Top")
  105. #define T_VALIGN_CENTER T_ALIGN_CENTER
  106. #define T_VALIGN_BOTTOM T_("VerticalAlignment.Bottom")
  107. #define T_TRANSFORM_NONE T_("Transform.None")
  108. #define T_TRANSFORM_UPPERCASE T_("Transform.Uppercase")
  109. #define T_TRANSFORM_LOWERCASE T_("Transform.Lowercase")
  110. #define T_TRANSFORM_STARTCASE T_("Transform.Startcase")
  111. /* clang-format on */
  112. /* ------------------------------------------------------------------------- */
  113. static inline DWORD get_alpha_val(uint32_t opacity)
  114. {
  115. return ((opacity * 255 / 100) & 0xFF) << 24;
  116. }
  117. static inline DWORD calc_color(uint32_t color, uint32_t opacity)
  118. {
  119. return color & 0xFFFFFF | get_alpha_val(opacity);
  120. }
  121. static inline wstring to_wide(const char *utf8)
  122. {
  123. wstring text;
  124. size_t len = os_utf8_to_wcs(utf8, 0, nullptr, 0);
  125. text.resize(len);
  126. if (len)
  127. os_utf8_to_wcs(utf8, 0, &text[0], len + 1);
  128. return text;
  129. }
  130. static inline uint32_t rgb_to_bgr(uint32_t rgb)
  131. {
  132. return ((rgb & 0xFF) << 16) | (rgb & 0xFF00) | ((rgb & 0xFF0000) >> 16);
  133. }
  134. /* ------------------------------------------------------------------------- */
  135. template<typename T, typename T2, BOOL WINAPI deleter(T2)> class GDIObj {
  136. T obj = nullptr;
  137. inline GDIObj &Replace(T obj_)
  138. {
  139. if (obj)
  140. deleter(obj);
  141. obj = obj_;
  142. return *this;
  143. }
  144. public:
  145. inline GDIObj() {}
  146. inline GDIObj(T obj_) : obj(obj_) {}
  147. inline ~GDIObj() { deleter(obj); }
  148. inline T operator=(T obj_)
  149. {
  150. Replace(obj_);
  151. return obj;
  152. }
  153. inline operator T() const { return obj; }
  154. inline bool operator==(T obj_) const { return obj == obj_; }
  155. inline bool operator!=(T obj_) const { return obj != obj_; }
  156. };
  157. using HDCObj = GDIObj<HDC, HDC, DeleteDC>;
  158. using HFONTObj = GDIObj<HFONT, HGDIOBJ, DeleteObject>;
  159. using HBITMAPObj = GDIObj<HBITMAP, HGDIOBJ, DeleteObject>;
  160. /* ------------------------------------------------------------------------- */
  161. enum class Align {
  162. Left,
  163. Center,
  164. Right,
  165. };
  166. enum class VAlign {
  167. Top,
  168. Center,
  169. Bottom,
  170. };
  171. struct TextSource {
  172. obs_source_t *source = nullptr;
  173. gs_texture_t *tex = nullptr;
  174. uint32_t cx = 0;
  175. uint32_t cy = 0;
  176. HDCObj hdc;
  177. Graphics graphics;
  178. HFONTObj hfont;
  179. unique_ptr<Font> font;
  180. bool read_from_file = false;
  181. string file;
  182. time_t file_timestamp = 0;
  183. bool update_file = false;
  184. float update_time_elapsed = 0.0f;
  185. wstring text;
  186. wstring face;
  187. int face_size = 0;
  188. uint32_t color = 0xFFFFFF;
  189. uint32_t color2 = 0xFFFFFF;
  190. float gradient_dir = 0;
  191. uint32_t opacity = 100;
  192. uint32_t opacity2 = 100;
  193. uint32_t bk_color = 0;
  194. uint32_t bk_opacity = 0;
  195. Align align = Align::Left;
  196. VAlign valign = VAlign::Top;
  197. bool gradient = false;
  198. bool bold = false;
  199. bool italic = false;
  200. bool underline = false;
  201. bool strikeout = false;
  202. bool antialiasing = true;
  203. bool vertical = false;
  204. bool use_outline = false;
  205. float outline_size = 0.0f;
  206. uint32_t outline_color = 0;
  207. uint32_t outline_opacity = 100;
  208. bool use_extents = false;
  209. bool old_extents = false;
  210. bool wrap = false;
  211. uint32_t extents_cx = 0;
  212. uint32_t extents_cy = 0;
  213. int text_transform = S_TRANSFORM_NONE;
  214. bool chatlog_mode = false;
  215. int chatlog_lines = 6;
  216. /* --------------------------- */
  217. inline TextSource(obs_source_t *source_, obs_data_t *settings, bool old_extents_)
  218. : source(source_),
  219. hdc(CreateCompatibleDC(nullptr)),
  220. graphics(hdc),
  221. old_extents(old_extents_)
  222. {
  223. obs_source_update(source, settings);
  224. }
  225. inline ~TextSource()
  226. {
  227. if (tex) {
  228. obs_enter_graphics();
  229. gs_texture_destroy(tex);
  230. obs_leave_graphics();
  231. }
  232. }
  233. void UpdateFont();
  234. void GetStringFormat(StringFormat &format);
  235. void RemoveNewlinePadding(const StringFormat &format, RectF &box);
  236. void CalculateTextSizes(const StringFormat &format, RectF &bounding_box, SIZE &text_size);
  237. void RenderOutlineText(Graphics &graphics, const GraphicsPath &path, const Brush &brush);
  238. void RenderText();
  239. void LoadFileText();
  240. void TransformText();
  241. void SetAntiAliasing(Graphics &graphics_bitmap);
  242. const char *GetMainString(const char *str);
  243. inline void Update(obs_data_t *settings);
  244. inline void Tick(float seconds);
  245. inline void Render();
  246. };
  247. static time_t get_modified_timestamp(const char *filename)
  248. {
  249. struct stat stats;
  250. if (os_stat(filename, &stats) != 0)
  251. return -1;
  252. return stats.st_mtime;
  253. }
  254. void TextSource::UpdateFont()
  255. {
  256. hfont = nullptr;
  257. font.reset(nullptr);
  258. LOGFONT lf = {};
  259. lf.lfHeight = face_size;
  260. lf.lfWeight = bold ? FW_BOLD : FW_DONTCARE;
  261. lf.lfItalic = italic;
  262. lf.lfUnderline = underline;
  263. lf.lfStrikeOut = strikeout;
  264. lf.lfQuality = ANTIALIASED_QUALITY;
  265. lf.lfCharSet = DEFAULT_CHARSET;
  266. if (!face.empty()) {
  267. wcscpy(lf.lfFaceName, face.c_str());
  268. hfont = CreateFontIndirect(&lf);
  269. }
  270. if (!hfont) {
  271. wcscpy(lf.lfFaceName, L"Arial");
  272. hfont = CreateFontIndirect(&lf);
  273. }
  274. if (hfont)
  275. font.reset(new Font(hdc, hfont));
  276. }
  277. void TextSource::GetStringFormat(StringFormat &format)
  278. {
  279. UINT flags = StringFormatFlagsNoFitBlackBox;
  280. if (!use_extents || old_extents)
  281. flags |= StringFormatFlagsMeasureTrailingSpaces;
  282. if (vertical)
  283. flags |= StringFormatFlagsDirectionVertical | StringFormatFlagsDirectionRightToLeft;
  284. format.SetFormatFlags(flags);
  285. format.SetTrimming(StringTrimmingWord);
  286. switch (align) {
  287. case Align::Left:
  288. if (vertical)
  289. format.SetLineAlignment(StringAlignmentFar);
  290. else
  291. format.SetAlignment(StringAlignmentNear);
  292. break;
  293. case Align::Center:
  294. if (vertical)
  295. format.SetLineAlignment(StringAlignmentCenter);
  296. else
  297. format.SetAlignment(StringAlignmentCenter);
  298. break;
  299. case Align::Right:
  300. if (vertical)
  301. format.SetLineAlignment(StringAlignmentNear);
  302. else
  303. format.SetAlignment(StringAlignmentFar);
  304. }
  305. switch (valign) {
  306. case VAlign::Top:
  307. if (vertical)
  308. format.SetAlignment(StringAlignmentNear);
  309. else
  310. format.SetLineAlignment(StringAlignmentNear);
  311. break;
  312. case VAlign::Center:
  313. if (vertical)
  314. format.SetAlignment(StringAlignmentCenter);
  315. else
  316. format.SetLineAlignment(StringAlignmentCenter);
  317. break;
  318. case VAlign::Bottom:
  319. if (vertical)
  320. format.SetAlignment(StringAlignmentFar);
  321. else
  322. format.SetLineAlignment(StringAlignmentFar);
  323. }
  324. }
  325. /* GDI+ treats '\n' as an extra character with an actual render size when
  326. * calculating the texture size, so we have to calculate the size of '\n' to
  327. * remove the padding. Because we always add a newline to the string, we
  328. * also remove the extra unused newline. */
  329. void TextSource::RemoveNewlinePadding(const StringFormat &format, RectF &box)
  330. {
  331. RectF before;
  332. RectF after;
  333. Status stat;
  334. stat = graphics.MeasureString(L"W", 2, font.get(), PointF(0.0f, 0.0f), &format, &before);
  335. warn_stat("MeasureString (without newline)");
  336. stat = graphics.MeasureString(L"W\n", 3, font.get(), PointF(0.0f, 0.0f), &format, &after);
  337. warn_stat("MeasureString (with newline)");
  338. float offset_cx = after.Width - before.Width;
  339. float offset_cy = after.Height - before.Height;
  340. if (!vertical) {
  341. if (offset_cx >= 1.0f)
  342. offset_cx -= 1.0f;
  343. if (valign == VAlign::Center)
  344. box.Y -= offset_cy * 0.5f;
  345. else if (valign == VAlign::Bottom)
  346. box.Y -= offset_cy;
  347. } else {
  348. if (offset_cy >= 1.0f)
  349. offset_cy -= 1.0f;
  350. if (align == Align::Center)
  351. box.X -= offset_cx * 0.5f;
  352. else if (align == Align::Right)
  353. box.X -= offset_cx;
  354. }
  355. box.Width -= offset_cx;
  356. box.Height -= offset_cy;
  357. }
  358. void TextSource::CalculateTextSizes(const StringFormat &format, RectF &bounding_box, SIZE &text_size)
  359. {
  360. RectF layout_box;
  361. RectF temp_box;
  362. Status stat;
  363. if (!text.empty()) {
  364. if (use_extents && wrap) {
  365. layout_box.X = layout_box.Y = 0;
  366. layout_box.Width = float(extents_cx);
  367. layout_box.Height = float(extents_cy);
  368. if (use_outline) {
  369. layout_box.Width -= outline_size;
  370. layout_box.Height -= outline_size;
  371. }
  372. stat = graphics.MeasureString(text.c_str(), (int)text.size() + 1, font.get(), layout_box,
  373. &format, &bounding_box);
  374. warn_stat("MeasureString (wrapped)");
  375. temp_box = bounding_box;
  376. } else {
  377. stat = graphics.MeasureString(text.c_str(), (int)text.size() + 1, font.get(),
  378. PointF(0.0f, 0.0f), &format, &bounding_box);
  379. warn_stat("MeasureString (non-wrapped)");
  380. temp_box = bounding_box;
  381. bounding_box.X = 0.0f;
  382. bounding_box.Y = 0.0f;
  383. RemoveNewlinePadding(format, bounding_box);
  384. if (use_outline) {
  385. bounding_box.Width += outline_size;
  386. bounding_box.Height += outline_size;
  387. }
  388. }
  389. }
  390. if (vertical) {
  391. if (bounding_box.Width < face_size) {
  392. text_size.cx = face_size;
  393. bounding_box.Width = float(face_size);
  394. } else {
  395. text_size.cx = LONG(bounding_box.Width + EPSILON);
  396. }
  397. text_size.cy = LONG(bounding_box.Height + EPSILON);
  398. } else {
  399. if (bounding_box.Height < face_size) {
  400. text_size.cy = face_size;
  401. bounding_box.Height = float(face_size);
  402. } else {
  403. text_size.cy = LONG(bounding_box.Height + EPSILON);
  404. }
  405. text_size.cx = LONG(bounding_box.Width + EPSILON);
  406. }
  407. if (use_extents) {
  408. text_size.cx = extents_cx;
  409. text_size.cy = extents_cy;
  410. if (!old_extents && !wrap) {
  411. if (align == Align::Center) {
  412. bounding_box.X += (extents_cx - bounding_box.Width) / 2;
  413. } else if (align == Align::Right) {
  414. bounding_box.X += extents_cx - bounding_box.Width;
  415. }
  416. if (valign == VAlign::Center) {
  417. bounding_box.Y += (extents_cy - bounding_box.Height) / 2;
  418. } else if (valign == VAlign::Bottom) {
  419. bounding_box.Y += extents_cy - bounding_box.Height;
  420. }
  421. }
  422. }
  423. text_size.cx += text_size.cx % 2;
  424. text_size.cy += text_size.cy % 2;
  425. int64_t total_size = int64_t(text_size.cx) * int64_t(text_size.cy);
  426. /* GPUs typically have texture size limitations */
  427. clamp(text_size.cx, MIN_SIZE_CX, MAX_SIZE_CX);
  428. clamp(text_size.cy, MIN_SIZE_CY, MAX_SIZE_CY);
  429. /* avoid taking up too much VRAM */
  430. if (total_size > MAX_AREA) {
  431. if (text_size.cx > text_size.cy)
  432. text_size.cx = (LONG)MAX_AREA / text_size.cy;
  433. else
  434. text_size.cy = (LONG)MAX_AREA / text_size.cx;
  435. }
  436. /* the internal text-rendering bounding box for is reset to
  437. * its internal value in case the texture gets cut off */
  438. bounding_box.Width = temp_box.Width;
  439. bounding_box.Height = temp_box.Height;
  440. }
  441. void TextSource::RenderOutlineText(Graphics &graphics, const GraphicsPath &path, const Brush &brush)
  442. {
  443. DWORD outline_rgba = calc_color(outline_color, outline_opacity);
  444. Status stat;
  445. Pen pen(Color(outline_rgba), outline_size);
  446. stat = pen.SetLineJoin(LineJoinRound);
  447. warn_stat("pen.SetLineJoin");
  448. stat = graphics.DrawPath(&pen, &path);
  449. warn_stat("graphics.DrawPath");
  450. stat = graphics.FillPath(&brush, &path);
  451. warn_stat("graphics.FillPath");
  452. }
  453. void TextSource::RenderText()
  454. {
  455. StringFormat format(StringFormat::GenericTypographic());
  456. Status stat;
  457. RectF box;
  458. SIZE size;
  459. GetStringFormat(format);
  460. CalculateTextSizes(format, box, size);
  461. unique_ptr<uint8_t[]> bits(new uint8_t[size.cx * size.cy * 4]);
  462. Bitmap bitmap(size.cx, size.cy, 4 * size.cx, PixelFormat32bppARGB, bits.get());
  463. Graphics graphics_bitmap(&bitmap);
  464. LinearGradientBrush brush(RectF(0, 0, (float)size.cx, (float)size.cy), Color(calc_color(color, opacity)),
  465. Color(calc_color(color2, opacity2)), gradient_dir, 1);
  466. DWORD full_bk_color = bk_color & 0xFFFFFF;
  467. if (!text.empty() || use_extents)
  468. full_bk_color |= get_alpha_val(bk_opacity);
  469. if ((size.cx > box.Width || size.cy > box.Height) && !use_extents) {
  470. stat = graphics_bitmap.Clear(Color(0));
  471. warn_stat("graphics_bitmap.Clear");
  472. SolidBrush bk_brush = Color(full_bk_color);
  473. stat = graphics_bitmap.FillRectangle(&bk_brush, box);
  474. warn_stat("graphics_bitmap.FillRectangle");
  475. } else {
  476. stat = graphics_bitmap.Clear(Color(full_bk_color));
  477. warn_stat("graphics_bitmap.Clear");
  478. }
  479. graphics_bitmap.SetCompositingMode(CompositingModeSourceOver);
  480. SetAntiAliasing(graphics_bitmap);
  481. if (!text.empty()) {
  482. if (use_outline) {
  483. box.Offset(outline_size / 2, outline_size / 2);
  484. FontFamily family;
  485. GraphicsPath path;
  486. font->GetFamily(&family);
  487. stat = path.AddString(text.c_str(), (int)text.size(), &family, font->GetStyle(),
  488. font->GetSize(), box, &format);
  489. warn_stat("path.AddString");
  490. RenderOutlineText(graphics_bitmap, path, brush);
  491. } else {
  492. stat = graphics_bitmap.DrawString(text.c_str(), (int)text.size(), font.get(), box, &format,
  493. &brush);
  494. warn_stat("graphics_bitmap.DrawString");
  495. }
  496. }
  497. if (!tex || (LONG)cx != size.cx || (LONG)cy != size.cy) {
  498. obs_enter_graphics();
  499. if (tex)
  500. gs_texture_destroy(tex);
  501. const uint8_t *data = (uint8_t *)bits.get();
  502. tex = gs_texture_create(size.cx, size.cy, GS_BGRA, 1, &data, GS_DYNAMIC);
  503. obs_leave_graphics();
  504. cx = (uint32_t)size.cx;
  505. cy = (uint32_t)size.cy;
  506. } else if (tex) {
  507. obs_enter_graphics();
  508. gs_texture_set_image(tex, bits.get(), size.cx * 4, false);
  509. obs_leave_graphics();
  510. }
  511. }
  512. const char *TextSource::GetMainString(const char *str)
  513. {
  514. if (!str)
  515. return "";
  516. if (!chatlog_mode || !chatlog_lines)
  517. return str;
  518. int lines = chatlog_lines;
  519. size_t len = strlen(str);
  520. if (!len)
  521. return str;
  522. const char *temp = str + len;
  523. while (temp != str) {
  524. temp--;
  525. if (temp[0] == '\n' && temp[1] != 0) {
  526. if (!--lines)
  527. break;
  528. }
  529. }
  530. return *temp == '\n' ? temp + 1 : temp;
  531. }
  532. void TextSource::LoadFileText()
  533. {
  534. BPtr<char> file_text = os_quick_read_utf8_file(file.c_str());
  535. text = to_wide(GetMainString(file_text));
  536. if (!text.empty() && text.back() != '\n')
  537. text.push_back('\n');
  538. }
  539. void TextSource::TransformText()
  540. {
  541. const locale loc = locale(obs_get_locale());
  542. const ctype<wchar_t> &f = use_facet<ctype<wchar_t>>(loc);
  543. if (text_transform == S_TRANSFORM_UPPERCASE)
  544. f.toupper(&text[0], &text[0] + text.size());
  545. else if (text_transform == S_TRANSFORM_LOWERCASE)
  546. f.tolower(&text[0], &text[0] + text.size());
  547. else if (text_transform == S_TRANSFORM_STARTCASE) {
  548. bool upper = true;
  549. for (wstring::iterator it = text.begin(); it != text.end(); ++it) {
  550. const wchar_t upper_char = f.toupper(*it);
  551. const wchar_t lower_char = f.tolower(*it);
  552. if (upper && lower_char != upper_char) {
  553. upper = false;
  554. *it = upper_char;
  555. } else if (lower_char != upper_char) {
  556. *it = lower_char;
  557. } else {
  558. upper = iswspace(*it);
  559. }
  560. }
  561. }
  562. }
  563. void TextSource::SetAntiAliasing(Graphics &graphics_bitmap)
  564. {
  565. if (!antialiasing) {
  566. graphics_bitmap.SetTextRenderingHint(TextRenderingHintSingleBitPerPixel);
  567. graphics_bitmap.SetSmoothingMode(SmoothingModeNone);
  568. return;
  569. }
  570. graphics_bitmap.SetTextRenderingHint(TextRenderingHintAntiAlias);
  571. graphics_bitmap.SetSmoothingMode(SmoothingModeAntiAlias);
  572. }
  573. #define obs_data_get_uint32 (uint32_t) obs_data_get_int
  574. inline void TextSource::Update(obs_data_t *s)
  575. {
  576. const char *new_text = obs_data_get_string(s, S_TEXT);
  577. obs_data_t *font_obj = obs_data_get_obj(s, S_FONT);
  578. const char *align_str = obs_data_get_string(s, S_ALIGN);
  579. const char *valign_str = obs_data_get_string(s, S_VALIGN);
  580. uint32_t new_color = obs_data_get_uint32(s, S_COLOR);
  581. uint32_t new_opacity = obs_data_get_uint32(s, S_OPACITY);
  582. bool gradient = obs_data_get_bool(s, S_GRADIENT);
  583. uint32_t new_color2 = obs_data_get_uint32(s, S_GRADIENT_COLOR);
  584. uint32_t new_opacity2 = obs_data_get_uint32(s, S_GRADIENT_OPACITY);
  585. float new_grad_dir = (float)obs_data_get_double(s, S_GRADIENT_DIR);
  586. bool new_vertical = obs_data_get_bool(s, S_VERTICAL);
  587. bool new_outline = obs_data_get_bool(s, S_OUTLINE);
  588. uint32_t new_o_color = obs_data_get_uint32(s, S_OUTLINE_COLOR);
  589. uint32_t new_o_opacity = obs_data_get_uint32(s, S_OUTLINE_OPACITY);
  590. uint32_t new_o_size = obs_data_get_uint32(s, S_OUTLINE_SIZE);
  591. bool new_use_file = obs_data_get_bool(s, S_USE_FILE);
  592. const char *new_file = obs_data_get_string(s, S_FILE);
  593. bool new_chat_mode = obs_data_get_bool(s, S_CHATLOG_MODE);
  594. int new_chat_lines = (int)obs_data_get_int(s, S_CHATLOG_LINES);
  595. bool new_extents = obs_data_get_bool(s, S_EXTENTS);
  596. bool new_extents_wrap = obs_data_get_bool(s, S_EXTENTS_WRAP);
  597. uint32_t n_extents_cx = obs_data_get_uint32(s, S_EXTENTS_CX);
  598. uint32_t n_extents_cy = obs_data_get_uint32(s, S_EXTENTS_CY);
  599. int new_text_transform = (int)obs_data_get_int(s, S_TRANSFORM);
  600. bool new_antialiasing = obs_data_get_bool(s, S_ANTIALIASING);
  601. const char *font_face = obs_data_get_string(font_obj, "face");
  602. int font_size = (int)obs_data_get_int(font_obj, "size");
  603. int64_t font_flags = obs_data_get_int(font_obj, "flags");
  604. bool new_bold = (font_flags & OBS_FONT_BOLD) != 0;
  605. bool new_italic = (font_flags & OBS_FONT_ITALIC) != 0;
  606. bool new_underline = (font_flags & OBS_FONT_UNDERLINE) != 0;
  607. bool new_strikeout = (font_flags & OBS_FONT_STRIKEOUT) != 0;
  608. uint32_t new_bk_color = obs_data_get_uint32(s, S_BKCOLOR);
  609. uint32_t new_bk_opacity = obs_data_get_uint32(s, S_BKOPACITY);
  610. /* ----------------------------- */
  611. wstring new_face = to_wide(font_face);
  612. if (new_face != face || face_size != font_size || new_bold != bold || new_italic != italic ||
  613. new_underline != underline || new_strikeout != strikeout) {
  614. face = new_face;
  615. face_size = font_size;
  616. bold = new_bold;
  617. italic = new_italic;
  618. underline = new_underline;
  619. strikeout = new_strikeout;
  620. UpdateFont();
  621. }
  622. /* ----------------------------- */
  623. new_color = rgb_to_bgr(new_color);
  624. new_color2 = rgb_to_bgr(new_color2);
  625. new_o_color = rgb_to_bgr(new_o_color);
  626. new_bk_color = rgb_to_bgr(new_bk_color);
  627. color = new_color;
  628. opacity = new_opacity;
  629. color2 = new_color2;
  630. opacity2 = new_opacity2;
  631. gradient_dir = new_grad_dir;
  632. vertical = new_vertical;
  633. bk_color = new_bk_color;
  634. bk_opacity = new_bk_opacity;
  635. use_extents = new_extents;
  636. wrap = new_extents_wrap;
  637. extents_cx = n_extents_cx;
  638. extents_cy = n_extents_cy;
  639. text_transform = new_text_transform;
  640. antialiasing = new_antialiasing;
  641. if (!gradient) {
  642. color2 = color;
  643. opacity2 = opacity;
  644. }
  645. read_from_file = new_use_file;
  646. chatlog_mode = new_chat_mode;
  647. chatlog_lines = new_chat_lines;
  648. if (read_from_file) {
  649. file = new_file;
  650. file_timestamp = get_modified_timestamp(new_file);
  651. LoadFileText();
  652. } else {
  653. text = to_wide(GetMainString(new_text));
  654. /* all text should end with newlines due to the fact that GDI+
  655. * treats strings without newlines differently in terms of
  656. * render size */
  657. if (!text.empty())
  658. text.push_back('\n');
  659. }
  660. TransformText();
  661. use_outline = new_outline;
  662. outline_color = new_o_color;
  663. outline_opacity = new_o_opacity;
  664. outline_size = roundf(float(new_o_size));
  665. if (strcmp(align_str, S_ALIGN_CENTER) == 0)
  666. align = Align::Center;
  667. else if (strcmp(align_str, S_ALIGN_RIGHT) == 0)
  668. align = Align::Right;
  669. else
  670. align = Align::Left;
  671. if (strcmp(valign_str, S_VALIGN_CENTER) == 0)
  672. valign = VAlign::Center;
  673. else if (strcmp(valign_str, S_VALIGN_BOTTOM) == 0)
  674. valign = VAlign::Bottom;
  675. else
  676. valign = VAlign::Top;
  677. RenderText();
  678. update_time_elapsed = 0.0f;
  679. /* ----------------------------- */
  680. obs_data_release(font_obj);
  681. }
  682. inline void TextSource::Tick(float seconds)
  683. {
  684. if (!read_from_file)
  685. return;
  686. update_time_elapsed += seconds;
  687. if (update_time_elapsed >= 1.0f) {
  688. time_t t = get_modified_timestamp(file.c_str());
  689. update_time_elapsed = 0.0f;
  690. if (update_file) {
  691. LoadFileText();
  692. TransformText();
  693. RenderText();
  694. update_file = false;
  695. }
  696. if (file_timestamp != t) {
  697. file_timestamp = t;
  698. update_file = true;
  699. }
  700. }
  701. }
  702. inline void TextSource::Render()
  703. {
  704. if (!tex)
  705. return;
  706. gs_effect_t *effect = obs_get_base_effect(OBS_EFFECT_DEFAULT);
  707. gs_technique_t *tech = gs_effect_get_technique(effect, "Draw");
  708. const bool previous = gs_framebuffer_srgb_enabled();
  709. gs_enable_framebuffer_srgb(true);
  710. gs_technique_begin(tech);
  711. gs_technique_begin_pass(tech, 0);
  712. gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), tex);
  713. gs_draw_sprite(tex, 0, cx, cy);
  714. gs_technique_end_pass(tech);
  715. gs_technique_end(tech);
  716. gs_enable_framebuffer_srgb(previous);
  717. }
  718. /* ------------------------------------------------------------------------- */
  719. static ULONG_PTR gdip_token = 0;
  720. OBS_DECLARE_MODULE()
  721. OBS_MODULE_USE_DEFAULT_LOCALE("obs-text", "en-US")
  722. MODULE_EXPORT const char *obs_module_description(void)
  723. {
  724. return "Windows GDI+ text source";
  725. }
  726. #define set_vis(var, val, show) \
  727. do { \
  728. p = obs_properties_get(props, val); \
  729. obs_property_set_visible(p, var == show); \
  730. } while (false)
  731. static bool use_file_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s)
  732. {
  733. bool use_file = obs_data_get_bool(s, S_USE_FILE);
  734. set_vis(use_file, S_TEXT, false);
  735. set_vis(use_file, S_FILE, true);
  736. return true;
  737. }
  738. static bool outline_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s)
  739. {
  740. bool outline = obs_data_get_bool(s, S_OUTLINE);
  741. set_vis(outline, S_OUTLINE_SIZE, true);
  742. set_vis(outline, S_OUTLINE_COLOR, true);
  743. set_vis(outline, S_OUTLINE_OPACITY, true);
  744. return true;
  745. }
  746. static bool chatlog_mode_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s)
  747. {
  748. bool chatlog_mode = obs_data_get_bool(s, S_CHATLOG_MODE);
  749. set_vis(chatlog_mode, S_CHATLOG_LINES, true);
  750. return true;
  751. }
  752. static bool gradient_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s)
  753. {
  754. bool gradient = obs_data_get_bool(s, S_GRADIENT);
  755. set_vis(gradient, S_GRADIENT_COLOR, true);
  756. set_vis(gradient, S_GRADIENT_OPACITY, true);
  757. set_vis(gradient, S_GRADIENT_DIR, true);
  758. return true;
  759. }
  760. static bool extents_modified(obs_properties_t *props, obs_property_t *p, obs_data_t *s)
  761. {
  762. bool use_extents = obs_data_get_bool(s, S_EXTENTS);
  763. set_vis(use_extents, S_EXTENTS_WRAP, true);
  764. set_vis(use_extents, S_EXTENTS_CX, true);
  765. set_vis(use_extents, S_EXTENTS_CY, true);
  766. return true;
  767. }
  768. #undef set_vis
  769. static obs_properties_t *get_properties(void *data)
  770. {
  771. TextSource *s = reinterpret_cast<TextSource *>(data);
  772. string path;
  773. obs_properties_t *props = obs_properties_create();
  774. obs_property_t *p;
  775. obs_properties_add_font(props, S_FONT, T_FONT);
  776. p = obs_properties_add_bool(props, S_USE_FILE, T_USE_FILE);
  777. obs_property_set_modified_callback(p, use_file_changed);
  778. string filter;
  779. filter += T_FILTER_TEXT_FILES;
  780. filter += " (*.txt);;";
  781. filter += T_FILTER_ALL_FILES;
  782. filter += " (*.*)";
  783. if (s && !s->file.empty()) {
  784. const char *slash;
  785. path = s->file;
  786. replace(path.begin(), path.end(), '\\', '/');
  787. slash = strrchr(path.c_str(), '/');
  788. if (slash)
  789. path.resize(slash - path.c_str() + 1);
  790. }
  791. obs_properties_add_text(props, S_TEXT, T_TEXT, OBS_TEXT_MULTILINE);
  792. obs_properties_add_path(props, S_FILE, T_FILE, OBS_PATH_FILE, filter.c_str(), path.c_str());
  793. obs_properties_add_bool(props, S_ANTIALIASING, T_ANTIALIASING);
  794. p = obs_properties_add_list(props, S_TRANSFORM, T_TRANSFORM, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT);
  795. obs_property_list_add_int(p, T_TRANSFORM_NONE, S_TRANSFORM_NONE);
  796. obs_property_list_add_int(p, T_TRANSFORM_UPPERCASE, S_TRANSFORM_UPPERCASE);
  797. obs_property_list_add_int(p, T_TRANSFORM_LOWERCASE, S_TRANSFORM_LOWERCASE);
  798. obs_property_list_add_int(p, T_TRANSFORM_STARTCASE, S_TRANSFORM_STARTCASE);
  799. obs_properties_add_bool(props, S_VERTICAL, T_VERTICAL);
  800. obs_properties_add_color(props, S_COLOR, T_COLOR);
  801. p = obs_properties_add_int_slider(props, S_OPACITY, T_OPACITY, 0, 100, 1);
  802. obs_property_int_set_suffix(p, "%");
  803. p = obs_properties_add_bool(props, S_GRADIENT, T_GRADIENT);
  804. obs_property_set_modified_callback(p, gradient_changed);
  805. obs_properties_add_color(props, S_GRADIENT_COLOR, T_GRADIENT_COLOR);
  806. p = obs_properties_add_int_slider(props, S_GRADIENT_OPACITY, T_GRADIENT_OPACITY, 0, 100, 1);
  807. obs_property_int_set_suffix(p, "%");
  808. obs_properties_add_float_slider(props, S_GRADIENT_DIR, T_GRADIENT_DIR, 0, 360, 0.1);
  809. obs_properties_add_color(props, S_BKCOLOR, T_BKCOLOR);
  810. p = obs_properties_add_int_slider(props, S_BKOPACITY, T_BKOPACITY, 0, 100, 1);
  811. obs_property_int_set_suffix(p, "%");
  812. p = obs_properties_add_list(props, S_ALIGN, T_ALIGN, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  813. obs_property_list_add_string(p, T_ALIGN_LEFT, S_ALIGN_LEFT);
  814. obs_property_list_add_string(p, T_ALIGN_CENTER, S_ALIGN_CENTER);
  815. obs_property_list_add_string(p, T_ALIGN_RIGHT, S_ALIGN_RIGHT);
  816. p = obs_properties_add_list(props, S_VALIGN, T_VALIGN, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING);
  817. obs_property_list_add_string(p, T_VALIGN_TOP, S_VALIGN_TOP);
  818. obs_property_list_add_string(p, T_VALIGN_CENTER, S_VALIGN_CENTER);
  819. obs_property_list_add_string(p, T_VALIGN_BOTTOM, S_VALIGN_BOTTOM);
  820. p = obs_properties_add_bool(props, S_OUTLINE, T_OUTLINE);
  821. obs_property_set_modified_callback(p, outline_changed);
  822. obs_properties_add_int(props, S_OUTLINE_SIZE, T_OUTLINE_SIZE, 1, 20, 1);
  823. obs_properties_add_color(props, S_OUTLINE_COLOR, T_OUTLINE_COLOR);
  824. p = obs_properties_add_int_slider(props, S_OUTLINE_OPACITY, T_OUTLINE_OPACITY, 0, 100, 1);
  825. obs_property_int_set_suffix(p, "%");
  826. p = obs_properties_add_bool(props, S_CHATLOG_MODE, T_CHATLOG_MODE);
  827. obs_property_set_modified_callback(p, chatlog_mode_changed);
  828. obs_properties_add_int(props, S_CHATLOG_LINES, T_CHATLOG_LINES, 1, 1000, 1);
  829. p = obs_properties_add_bool(props, S_EXTENTS, T_EXTENTS);
  830. obs_property_set_modified_callback(p, extents_modified);
  831. obs_properties_add_int(props, S_EXTENTS_CX, T_EXTENTS_CX, 32, 8000, 1);
  832. obs_properties_add_int(props, S_EXTENTS_CY, T_EXTENTS_CY, 32, 8000, 1);
  833. obs_properties_add_bool(props, S_EXTENTS_WRAP, T_EXTENTS_WRAP);
  834. return props;
  835. }
  836. static void defaults(obs_data_t *settings, int ver)
  837. {
  838. obs_data_t *font_obj = obs_data_create();
  839. obs_data_set_default_string(font_obj, "face", "Arial");
  840. obs_data_set_default_int(font_obj, "size", ver == 1 ? 36 : 256);
  841. obs_data_set_default_obj(settings, S_FONT, font_obj);
  842. obs_data_set_default_string(settings, S_ALIGN, S_ALIGN_LEFT);
  843. obs_data_set_default_string(settings, S_VALIGN, S_VALIGN_TOP);
  844. obs_data_set_default_int(settings, S_COLOR, 0xFFFFFF);
  845. obs_data_set_default_int(settings, S_OPACITY, 100);
  846. obs_data_set_default_int(settings, S_GRADIENT_COLOR, 0xFFFFFF);
  847. obs_data_set_default_int(settings, S_GRADIENT_OPACITY, 100);
  848. obs_data_set_default_double(settings, S_GRADIENT_DIR, 90.0);
  849. obs_data_set_default_int(settings, S_BKCOLOR, 0x000000);
  850. obs_data_set_default_int(settings, S_BKOPACITY, 0);
  851. obs_data_set_default_int(settings, S_OUTLINE_SIZE, 2);
  852. obs_data_set_default_int(settings, S_OUTLINE_COLOR, 0xFFFFFF);
  853. obs_data_set_default_int(settings, S_OUTLINE_OPACITY, 100);
  854. obs_data_set_default_int(settings, S_CHATLOG_LINES, 6);
  855. obs_data_set_default_bool(settings, S_EXTENTS_WRAP, true);
  856. obs_data_set_default_int(settings, S_EXTENTS_CX, 100);
  857. obs_data_set_default_int(settings, S_EXTENTS_CY, 100);
  858. obs_data_set_default_int(settings, S_TRANSFORM, S_TRANSFORM_NONE);
  859. obs_data_set_default_bool(settings, S_ANTIALIASING, true);
  860. obs_data_release(font_obj);
  861. };
  862. static void missing_file_callback(void *src, const char *new_path, void *data)
  863. {
  864. TextSource *s = reinterpret_cast<TextSource *>(src);
  865. obs_source_t *source = s->source;
  866. obs_data_t *settings = obs_source_get_settings(source);
  867. obs_data_set_string(settings, S_FILE, new_path);
  868. obs_source_update(source, settings);
  869. obs_data_release(settings);
  870. UNUSED_PARAMETER(data);
  871. }
  872. bool obs_module_load(void)
  873. {
  874. obs_source_info si = {};
  875. si.id = "text_gdiplus";
  876. si.type = OBS_SOURCE_TYPE_INPUT;
  877. si.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_CAP_OBSOLETE | OBS_SOURCE_SRGB;
  878. si.get_properties = get_properties;
  879. si.icon_type = OBS_ICON_TYPE_TEXT;
  880. si.get_name = [](void *) {
  881. return obs_module_text("TextGDIPlus");
  882. };
  883. si.create = [](obs_data_t *settings, obs_source_t *source) {
  884. return (void *)new TextSource(source, settings, true);
  885. };
  886. si.destroy = [](void *data) {
  887. delete reinterpret_cast<TextSource *>(data);
  888. };
  889. si.get_width = [](void *data) {
  890. return reinterpret_cast<TextSource *>(data)->cx;
  891. };
  892. si.get_height = [](void *data) {
  893. return reinterpret_cast<TextSource *>(data)->cy;
  894. };
  895. si.get_defaults = [](obs_data_t *settings) {
  896. defaults(settings, 1);
  897. };
  898. si.update = [](void *data, obs_data_t *settings) {
  899. reinterpret_cast<TextSource *>(data)->Update(settings);
  900. };
  901. si.video_tick = [](void *data, float seconds) {
  902. reinterpret_cast<TextSource *>(data)->Tick(seconds);
  903. };
  904. si.video_render = [](void *data, gs_effect_t *) {
  905. reinterpret_cast<TextSource *>(data)->Render();
  906. };
  907. si.missing_files = [](void *data) {
  908. TextSource *s = reinterpret_cast<TextSource *>(data);
  909. obs_missing_files_t *files = obs_missing_files_create();
  910. obs_source_t *source = s->source;
  911. obs_data_t *settings = obs_source_get_settings(source);
  912. bool read = obs_data_get_bool(settings, S_USE_FILE);
  913. const char *path = obs_data_get_string(settings, S_FILE);
  914. if (read && strcmp(path, "") != 0) {
  915. if (!os_file_exists(path)) {
  916. obs_missing_file_t *file = obs_missing_file_create(
  917. path, missing_file_callback, OBS_MISSING_FILE_SOURCE, s->source, NULL);
  918. obs_missing_files_add_file(files, file);
  919. }
  920. }
  921. obs_data_release(settings);
  922. return files;
  923. };
  924. obs_source_info si_v2 = si;
  925. si_v2.version = 2;
  926. si_v2.get_defaults = [](obs_data_t *settings) {
  927. defaults(settings, 2);
  928. };
  929. obs_source_info si_v3 = si_v2;
  930. si_v3.version = 3;
  931. si_v3.output_flags &= ~OBS_SOURCE_CAP_OBSOLETE;
  932. si_v3.create = [](obs_data_t *settings, obs_source_t *source) {
  933. return (void *)new TextSource(source, settings, false);
  934. };
  935. obs_register_source(&si);
  936. obs_register_source(&si_v2);
  937. obs_register_source(&si_v3);
  938. const GdiplusStartupInput gdip_input;
  939. GdiplusStartup(&gdip_token, &gdip_input, nullptr);
  940. return true;
  941. }
  942. void obs_module_unload(void)
  943. {
  944. GdiplusShutdown(gdip_token);
  945. }