obs-text.cpp 31 KB

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