obs-text.cpp 32 KB

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