obs-text.cpp 30 KB

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