obs-text.cpp 31 KB

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