obs-text.cpp 30 KB

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