obs-text.cpp 33 KB

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