obs-app.cpp 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <time.h>
  15. #include <stdio.h>
  16. #include <wchar.h>
  17. #include <chrono>
  18. #include <ratio>
  19. #include <string>
  20. #include <sstream>
  21. #include <mutex>
  22. #include <util/bmem.h>
  23. #include <util/dstr.hpp>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <util/cf-parser.h>
  27. #include <obs-config.h>
  28. #include <obs.hpp>
  29. #include <QGuiApplication>
  30. #include <QProxyStyle>
  31. #include <QScreen>
  32. #include "qt-wrappers.hpp"
  33. #include "obs-app.hpp"
  34. #include "window-basic-main.hpp"
  35. #include "window-basic-settings.hpp"
  36. #include "crash-report.hpp"
  37. #include "platform.hpp"
  38. #include <fstream>
  39. #include <curl/curl.h>
  40. #ifdef _WIN32
  41. #include <windows.h>
  42. #else
  43. #include <signal.h>
  44. #include <pthread.h>
  45. #endif
  46. #include <iostream>
  47. #include "ui-config.h"
  48. using namespace std;
  49. static log_handler_t def_log_handler;
  50. static string currentLogFile;
  51. static string lastLogFile;
  52. static string lastCrashLogFile;
  53. bool portable_mode = false;
  54. static bool multi = false;
  55. static bool log_verbose = false;
  56. static bool unfiltered_log = false;
  57. bool opt_start_streaming = false;
  58. bool opt_start_recording = false;
  59. bool opt_studio_mode = false;
  60. bool opt_start_replaybuffer = false;
  61. bool opt_minimize_tray = false;
  62. bool opt_allow_opengl = false;
  63. bool opt_always_on_top = false;
  64. string opt_starting_collection;
  65. string opt_starting_profile;
  66. string opt_starting_scene;
  67. bool remuxAfterRecord = false;
  68. string remuxFilename;
  69. // GPU hint exports for AMD/NVIDIA laptops
  70. #ifdef _MSC_VER
  71. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  72. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  73. #endif
  74. QObject *CreateShortcutFilter()
  75. {
  76. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  77. auto mouse_event = [](QMouseEvent &event) {
  78. if (!App()->HotkeysEnabledInFocus() &&
  79. event.button() != Qt::LeftButton)
  80. return true;
  81. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  82. bool pressed = event.type() == QEvent::MouseButtonPress;
  83. switch (event.button()) {
  84. case Qt::NoButton:
  85. case Qt::LeftButton:
  86. case Qt::RightButton:
  87. case Qt::AllButtons:
  88. case Qt::MouseButtonMask:
  89. return false;
  90. case Qt::MidButton:
  91. hotkey.key = OBS_KEY_MOUSE3;
  92. break;
  93. #define MAP_BUTTON(i, j) \
  94. case Qt::ExtraButton##i: \
  95. hotkey.key = OBS_KEY_MOUSE##j; \
  96. break;
  97. MAP_BUTTON(1, 4);
  98. MAP_BUTTON(2, 5);
  99. MAP_BUTTON(3, 6);
  100. MAP_BUTTON(4, 7);
  101. MAP_BUTTON(5, 8);
  102. MAP_BUTTON(6, 9);
  103. MAP_BUTTON(7, 10);
  104. MAP_BUTTON(8, 11);
  105. MAP_BUTTON(9, 12);
  106. MAP_BUTTON(10, 13);
  107. MAP_BUTTON(11, 14);
  108. MAP_BUTTON(12, 15);
  109. MAP_BUTTON(13, 16);
  110. MAP_BUTTON(14, 17);
  111. MAP_BUTTON(15, 18);
  112. MAP_BUTTON(16, 19);
  113. MAP_BUTTON(17, 20);
  114. MAP_BUTTON(18, 21);
  115. MAP_BUTTON(19, 22);
  116. MAP_BUTTON(20, 23);
  117. MAP_BUTTON(21, 24);
  118. MAP_BUTTON(22, 25);
  119. MAP_BUTTON(23, 26);
  120. MAP_BUTTON(24, 27);
  121. #undef MAP_BUTTON
  122. }
  123. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  124. event.modifiers());
  125. obs_hotkey_inject_event(hotkey, pressed);
  126. return true;
  127. };
  128. auto key_event = [&](QKeyEvent *event) {
  129. if (!App()->HotkeysEnabledInFocus())
  130. return true;
  131. QDialog *dialog = qobject_cast<QDialog *>(obj);
  132. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  133. bool pressed = event->type() == QEvent::KeyPress;
  134. switch (event->key()) {
  135. case Qt::Key_Shift:
  136. case Qt::Key_Control:
  137. case Qt::Key_Alt:
  138. case Qt::Key_Meta:
  139. break;
  140. #ifdef __APPLE__
  141. case Qt::Key_CapsLock:
  142. // kVK_CapsLock == 57
  143. hotkey.key = obs_key_from_virtual_key(57);
  144. pressed = true;
  145. break;
  146. #endif
  147. case Qt::Key_Enter:
  148. case Qt::Key_Escape:
  149. case Qt::Key_Return:
  150. if (dialog && pressed)
  151. return false;
  152. /* Falls through. */
  153. default:
  154. hotkey.key = obs_key_from_virtual_key(
  155. event->nativeVirtualKey());
  156. }
  157. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  158. event->modifiers());
  159. obs_hotkey_inject_event(hotkey, pressed);
  160. return true;
  161. };
  162. switch (event->type()) {
  163. case QEvent::MouseButtonPress:
  164. case QEvent::MouseButtonRelease:
  165. return mouse_event(*static_cast<QMouseEvent *>(event));
  166. /*case QEvent::MouseButtonDblClick:
  167. case QEvent::Wheel:*/
  168. case QEvent::KeyPress:
  169. case QEvent::KeyRelease:
  170. return key_event(static_cast<QKeyEvent *>(event));
  171. default:
  172. return false;
  173. }
  174. });
  175. }
  176. string CurrentTimeString()
  177. {
  178. using namespace std::chrono;
  179. struct tm tstruct;
  180. char buf[80];
  181. auto tp = system_clock::now();
  182. auto now = system_clock::to_time_t(tp);
  183. tstruct = *localtime(&now);
  184. size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
  185. if (ratio_less<system_clock::period, seconds::period>::value &&
  186. written && (sizeof(buf) - written) > 5) {
  187. auto tp_secs = time_point_cast<seconds>(tp);
  188. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  189. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  190. static_cast<unsigned>(millis));
  191. }
  192. return buf;
  193. }
  194. string CurrentDateTimeString()
  195. {
  196. time_t now = time(0);
  197. struct tm tstruct;
  198. char buf[80];
  199. tstruct = *localtime(&now);
  200. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  201. return buf;
  202. }
  203. static inline void LogString(fstream &logFile, const char *timeString,
  204. char *str)
  205. {
  206. logFile << timeString << str << endl;
  207. }
  208. static inline void LogStringChunk(fstream &logFile, char *str)
  209. {
  210. char *nextLine = str;
  211. string timeString = CurrentTimeString();
  212. timeString += ": ";
  213. while (*nextLine) {
  214. char *nextLine = strchr(str, '\n');
  215. if (!nextLine)
  216. break;
  217. if (nextLine != str && nextLine[-1] == '\r') {
  218. nextLine[-1] = 0;
  219. } else {
  220. nextLine[0] = 0;
  221. }
  222. LogString(logFile, timeString.c_str(), str);
  223. nextLine++;
  224. str = nextLine;
  225. }
  226. LogString(logFile, timeString.c_str(), str);
  227. }
  228. #define MAX_REPEATED_LINES 30
  229. #define MAX_CHAR_VARIATION (255 * 3)
  230. static inline int sum_chars(const char *str)
  231. {
  232. int val = 0;
  233. for (; *str != 0; str++)
  234. val += *str;
  235. return val;
  236. }
  237. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  238. const char *output_str)
  239. {
  240. static mutex log_mutex;
  241. static const char *last_msg_ptr = nullptr;
  242. static int last_char_sum = 0;
  243. static char cmp_str[4096];
  244. static int rep_count = 0;
  245. int new_sum = sum_chars(output_str);
  246. lock_guard<mutex> guard(log_mutex);
  247. if (unfiltered_log) {
  248. return false;
  249. }
  250. if (last_msg_ptr == msg) {
  251. int diff = std::abs(new_sum - last_char_sum);
  252. if (diff < MAX_CHAR_VARIATION) {
  253. return (rep_count++ >= MAX_REPEATED_LINES);
  254. }
  255. }
  256. if (rep_count > MAX_REPEATED_LINES) {
  257. logFile << CurrentTimeString()
  258. << ": Last log entry repeated for "
  259. << to_string(rep_count - MAX_REPEATED_LINES)
  260. << " more lines" << endl;
  261. }
  262. last_msg_ptr = msg;
  263. strcpy(cmp_str, output_str);
  264. last_char_sum = new_sum;
  265. rep_count = 0;
  266. return false;
  267. }
  268. static void do_log(int log_level, const char *msg, va_list args, void *param)
  269. {
  270. fstream &logFile = *static_cast<fstream *>(param);
  271. char str[4096];
  272. #ifndef _WIN32
  273. va_list args2;
  274. va_copy(args2, args);
  275. #endif
  276. vsnprintf(str, 4095, msg, args);
  277. #ifdef _WIN32
  278. if (IsDebuggerPresent()) {
  279. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  280. if (wNum > 1) {
  281. static wstring wide_buf;
  282. static mutex wide_mutex;
  283. lock_guard<mutex> lock(wide_mutex);
  284. wide_buf.reserve(wNum + 1);
  285. wide_buf.resize(wNum - 1);
  286. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  287. wNum);
  288. wide_buf.push_back('\n');
  289. OutputDebugStringW(wide_buf.c_str());
  290. }
  291. }
  292. #else
  293. def_log_handler(log_level, msg, args2, nullptr);
  294. va_end(args2);
  295. #endif
  296. if (log_level <= LOG_INFO || log_verbose) {
  297. if (too_many_repeated_entries(logFile, msg, str))
  298. return;
  299. LogStringChunk(logFile, str);
  300. }
  301. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  302. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  303. __debugbreak();
  304. #endif
  305. }
  306. #define DEFAULT_LANG "en-US"
  307. bool OBSApp::InitGlobalConfigDefaults()
  308. {
  309. config_set_default_string(globalConfig, "General", "Language",
  310. DEFAULT_LANG);
  311. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  312. config_set_default_int(globalConfig, "General", "InfoIncrement", -1);
  313. config_set_default_string(globalConfig, "General", "ProcessPriority",
  314. "Normal");
  315. config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
  316. true);
  317. #if _WIN32
  318. config_set_default_string(globalConfig, "Video", "Renderer",
  319. "Direct3D 11");
  320. #else
  321. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  322. #endif
  323. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  324. true);
  325. config_set_default_bool(globalConfig, "BasicWindow",
  326. "PreviewProgramMode", false);
  327. config_set_default_bool(globalConfig, "BasicWindow",
  328. "SceneDuplicationMode", true);
  329. config_set_default_bool(globalConfig, "BasicWindow", "SwapScenesMode",
  330. true);
  331. config_set_default_bool(globalConfig, "BasicWindow", "SnappingEnabled",
  332. true);
  333. config_set_default_bool(globalConfig, "BasicWindow", "ScreenSnapping",
  334. true);
  335. config_set_default_bool(globalConfig, "BasicWindow", "SourceSnapping",
  336. true);
  337. config_set_default_bool(globalConfig, "BasicWindow", "CenterSnapping",
  338. false);
  339. config_set_default_double(globalConfig, "BasicWindow", "SnapDistance",
  340. 10.0);
  341. config_set_default_bool(globalConfig, "BasicWindow",
  342. "RecordWhenStreaming", false);
  343. config_set_default_bool(globalConfig, "BasicWindow",
  344. "KeepRecordingWhenStreamStops", false);
  345. config_set_default_bool(globalConfig, "BasicWindow", "SysTrayEnabled",
  346. true);
  347. config_set_default_bool(globalConfig, "BasicWindow",
  348. "SysTrayWhenStarted", false);
  349. config_set_default_bool(globalConfig, "BasicWindow", "SaveProjectors",
  350. false);
  351. config_set_default_bool(globalConfig, "BasicWindow", "ShowTransitions",
  352. true);
  353. config_set_default_bool(globalConfig, "BasicWindow",
  354. "ShowListboxToolbars", true);
  355. config_set_default_bool(globalConfig, "BasicWindow", "ShowStatusBar",
  356. true);
  357. config_set_default_bool(globalConfig, "BasicWindow", "ShowSourceIcons",
  358. true);
  359. config_set_default_bool(globalConfig, "BasicWindow", "StudioModeLabels",
  360. true);
  361. if (!config_get_bool(globalConfig, "General", "Pre21Defaults")) {
  362. config_set_default_string(globalConfig, "General",
  363. "CurrentTheme", DEFAULT_THEME);
  364. }
  365. config_set_default_string(globalConfig, "General", "HotkeyFocusType",
  366. "NeverDisableHotkeys");
  367. config_set_default_bool(globalConfig, "BasicWindow",
  368. "VerticalVolControl", false);
  369. config_set_default_bool(globalConfig, "BasicWindow",
  370. "MultiviewMouseSwitch", true);
  371. config_set_default_bool(globalConfig, "BasicWindow",
  372. "MultiviewDrawNames", true);
  373. config_set_default_bool(globalConfig, "BasicWindow",
  374. "MultiviewDrawAreas", true);
  375. #ifdef _WIN32
  376. uint32_t winver = GetWindowsVersion();
  377. config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
  378. true);
  379. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  380. winver > 0x601);
  381. #endif
  382. #ifdef __APPLE__
  383. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  384. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  385. true);
  386. #endif
  387. return true;
  388. }
  389. static bool do_mkdir(const char *path)
  390. {
  391. if (os_mkdirs(path) == MKDIR_ERROR) {
  392. OBSErrorBox(NULL, "Failed to create directory %s", path);
  393. return false;
  394. }
  395. return true;
  396. }
  397. static bool MakeUserDirs()
  398. {
  399. char path[512];
  400. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  401. return false;
  402. if (!do_mkdir(path))
  403. return false;
  404. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  405. return false;
  406. if (!do_mkdir(path))
  407. return false;
  408. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  409. return false;
  410. if (!do_mkdir(path))
  411. return false;
  412. #ifdef _WIN32
  413. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  414. return false;
  415. if (!do_mkdir(path))
  416. return false;
  417. if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  418. return false;
  419. if (!do_mkdir(path))
  420. return false;
  421. #endif
  422. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  423. return false;
  424. if (!do_mkdir(path))
  425. return false;
  426. return true;
  427. }
  428. static bool MakeUserProfileDirs()
  429. {
  430. char path[512];
  431. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  432. return false;
  433. if (!do_mkdir(path))
  434. return false;
  435. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  436. return false;
  437. if (!do_mkdir(path))
  438. return false;
  439. return true;
  440. }
  441. static string GetProfileDirFromName(const char *name)
  442. {
  443. string outputPath;
  444. os_glob_t *glob;
  445. char path[512];
  446. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  447. return outputPath;
  448. strcat(path, "/*");
  449. if (os_glob(path, 0, &glob) != 0)
  450. return outputPath;
  451. for (size_t i = 0; i < glob->gl_pathc; i++) {
  452. struct os_globent ent = glob->gl_pathv[i];
  453. if (!ent.directory)
  454. continue;
  455. strcpy(path, ent.path);
  456. strcat(path, "/basic.ini");
  457. ConfigFile config;
  458. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  459. continue;
  460. const char *curName =
  461. config_get_string(config, "General", "Name");
  462. if (astrcmpi(curName, name) == 0) {
  463. outputPath = ent.path;
  464. break;
  465. }
  466. }
  467. os_globfree(glob);
  468. if (!outputPath.empty()) {
  469. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  470. const char *start = strrchr(outputPath.c_str(), '/');
  471. if (start)
  472. outputPath.erase(0, start - outputPath.c_str() + 1);
  473. }
  474. return outputPath;
  475. }
  476. static string GetSceneCollectionFileFromName(const char *name)
  477. {
  478. string outputPath;
  479. os_glob_t *glob;
  480. char path[512];
  481. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  482. return outputPath;
  483. strcat(path, "/*.json");
  484. if (os_glob(path, 0, &glob) != 0)
  485. return outputPath;
  486. for (size_t i = 0; i < glob->gl_pathc; i++) {
  487. struct os_globent ent = glob->gl_pathv[i];
  488. if (ent.directory)
  489. continue;
  490. obs_data_t *data =
  491. obs_data_create_from_json_file_safe(ent.path, "bak");
  492. const char *curName = obs_data_get_string(data, "name");
  493. if (astrcmpi(name, curName) == 0) {
  494. outputPath = ent.path;
  495. obs_data_release(data);
  496. break;
  497. }
  498. obs_data_release(data);
  499. }
  500. os_globfree(glob);
  501. if (!outputPath.empty()) {
  502. outputPath.resize(outputPath.size() - 5);
  503. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  504. const char *start = strrchr(outputPath.c_str(), '/');
  505. if (start)
  506. outputPath.erase(0, start - outputPath.c_str() + 1);
  507. }
  508. return outputPath;
  509. }
  510. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  511. {
  512. if (!layout)
  513. return false;
  514. if (astrcmpi(layout, "horizontaltop") == 0) {
  515. config_set_int(
  516. globalConfig, "BasicWindow", "MultiviewLayout",
  517. static_cast<int>(
  518. MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  519. return true;
  520. }
  521. if (astrcmpi(layout, "horizontalbottom") == 0) {
  522. config_set_int(
  523. globalConfig, "BasicWindow", "MultiviewLayout",
  524. static_cast<int>(
  525. MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  526. return true;
  527. }
  528. if (astrcmpi(layout, "verticalleft") == 0) {
  529. config_set_int(
  530. globalConfig, "BasicWindow", "MultiviewLayout",
  531. static_cast<int>(
  532. MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  533. return true;
  534. }
  535. if (astrcmpi(layout, "verticalright") == 0) {
  536. config_set_int(
  537. globalConfig, "BasicWindow", "MultiviewLayout",
  538. static_cast<int>(
  539. MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  540. return true;
  541. }
  542. return false;
  543. }
  544. bool OBSApp::InitGlobalConfig()
  545. {
  546. char path[512];
  547. bool changed = false;
  548. int len = GetConfigPath(path, sizeof(path), "obs-studio/global.ini");
  549. if (len <= 0) {
  550. return false;
  551. }
  552. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  553. if (errorcode != CONFIG_SUCCESS) {
  554. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  555. return false;
  556. }
  557. if (!opt_starting_collection.empty()) {
  558. string path = GetSceneCollectionFileFromName(
  559. opt_starting_collection.c_str());
  560. if (!path.empty()) {
  561. config_set_string(globalConfig, "Basic",
  562. "SceneCollection",
  563. opt_starting_collection.c_str());
  564. config_set_string(globalConfig, "Basic",
  565. "SceneCollectionFile", path.c_str());
  566. changed = true;
  567. }
  568. }
  569. if (!opt_starting_profile.empty()) {
  570. string path =
  571. GetProfileDirFromName(opt_starting_profile.c_str());
  572. if (!path.empty()) {
  573. config_set_string(globalConfig, "Basic", "Profile",
  574. opt_starting_profile.c_str());
  575. config_set_string(globalConfig, "Basic", "ProfileDir",
  576. path.c_str());
  577. changed = true;
  578. }
  579. }
  580. uint32_t lastVersion =
  581. config_get_int(globalConfig, "General", "LastVersion");
  582. if (!config_has_user_value(globalConfig, "General", "Pre19Defaults")) {
  583. bool useOldDefaults = lastVersion &&
  584. lastVersion <
  585. MAKE_SEMANTIC_VERSION(19, 0, 0);
  586. config_set_bool(globalConfig, "General", "Pre19Defaults",
  587. useOldDefaults);
  588. changed = true;
  589. }
  590. if (!config_has_user_value(globalConfig, "General", "Pre21Defaults")) {
  591. bool useOldDefaults = lastVersion &&
  592. lastVersion <
  593. MAKE_SEMANTIC_VERSION(21, 0, 0);
  594. config_set_bool(globalConfig, "General", "Pre21Defaults",
  595. useOldDefaults);
  596. changed = true;
  597. }
  598. if (!config_has_user_value(globalConfig, "General", "Pre23Defaults")) {
  599. bool useOldDefaults = lastVersion &&
  600. lastVersion <
  601. MAKE_SEMANTIC_VERSION(23, 0, 0);
  602. config_set_bool(globalConfig, "General", "Pre23Defaults",
  603. useOldDefaults);
  604. changed = true;
  605. }
  606. #define PRE_24_1_DEFS "Pre24.1Defaults"
  607. if (!config_has_user_value(globalConfig, "General", PRE_24_1_DEFS)) {
  608. bool useOldDefaults = lastVersion &&
  609. lastVersion <
  610. MAKE_SEMANTIC_VERSION(24, 1, 0);
  611. config_set_bool(globalConfig, "General", PRE_24_1_DEFS,
  612. useOldDefaults);
  613. changed = true;
  614. }
  615. #undef PRE_24_1_DEFS
  616. if (config_has_user_value(globalConfig, "BasicWindow",
  617. "MultiviewLayout")) {
  618. const char *layout = config_get_string(
  619. globalConfig, "BasicWindow", "MultiviewLayout");
  620. changed |= UpdatePre22MultiviewLayout(layout);
  621. }
  622. if (lastVersion && lastVersion < MAKE_SEMANTIC_VERSION(24, 0, 0)) {
  623. bool disableHotkeysInFocus = config_get_bool(
  624. globalConfig, "General", "DisableHotkeysInFocus");
  625. if (disableHotkeysInFocus)
  626. config_set_string(globalConfig, "General",
  627. "HotkeyFocusType",
  628. "DisableHotkeysInFocus");
  629. changed = true;
  630. }
  631. if (changed)
  632. config_save_safe(globalConfig, "tmp", nullptr);
  633. return InitGlobalConfigDefaults();
  634. }
  635. bool OBSApp::InitLocale()
  636. {
  637. ProfileScope("OBSApp::InitLocale");
  638. const char *lang =
  639. config_get_string(globalConfig, "General", "Language");
  640. locale = lang;
  641. string englishPath;
  642. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  643. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  644. return false;
  645. }
  646. textLookup = text_lookup_create(englishPath.c_str());
  647. if (!textLookup) {
  648. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  649. englishPath.c_str());
  650. return false;
  651. }
  652. bool userLocale =
  653. config_has_user_value(globalConfig, "General", "Language");
  654. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  655. if (userLocale && defaultLang)
  656. return true;
  657. if (!userLocale && defaultLang) {
  658. for (auto &locale_ : GetPreferredLocales()) {
  659. if (locale_ == lang)
  660. return true;
  661. stringstream file;
  662. file << "locale/" << locale_ << ".ini";
  663. string path;
  664. if (!GetDataFilePath(file.str().c_str(), path))
  665. continue;
  666. if (!text_lookup_add(textLookup, path.c_str()))
  667. continue;
  668. blog(LOG_INFO, "Using preferred locale '%s'",
  669. locale_.c_str());
  670. locale = locale_;
  671. return true;
  672. }
  673. return true;
  674. }
  675. stringstream file;
  676. file << "locale/" << lang << ".ini";
  677. string path;
  678. if (GetDataFilePath(file.str().c_str(), path)) {
  679. if (!text_lookup_add(textLookup, path.c_str()))
  680. blog(LOG_ERROR, "Failed to add locale file '%s'",
  681. path.c_str());
  682. } else {
  683. blog(LOG_ERROR, "Could not find locale file '%s'",
  684. file.str().c_str());
  685. }
  686. return true;
  687. }
  688. void OBSApp::AddExtraThemeColor(QPalette &pal, int group, const char *name,
  689. uint32_t color)
  690. {
  691. std::function<void(QPalette::ColorGroup)> func;
  692. #define DEF_PALETTE_ASSIGN(name) \
  693. do { \
  694. func = [&](QPalette::ColorGroup group) { \
  695. pal.setColor(group, QPalette::name, \
  696. QColor::fromRgb(color)); \
  697. }; \
  698. } while (false)
  699. if (astrcmpi(name, "alternateBase") == 0) {
  700. DEF_PALETTE_ASSIGN(AlternateBase);
  701. } else if (astrcmpi(name, "base") == 0) {
  702. DEF_PALETTE_ASSIGN(Base);
  703. } else if (astrcmpi(name, "brightText") == 0) {
  704. DEF_PALETTE_ASSIGN(BrightText);
  705. } else if (astrcmpi(name, "button") == 0) {
  706. DEF_PALETTE_ASSIGN(Button);
  707. } else if (astrcmpi(name, "buttonText") == 0) {
  708. DEF_PALETTE_ASSIGN(ButtonText);
  709. } else if (astrcmpi(name, "brightText") == 0) {
  710. DEF_PALETTE_ASSIGN(BrightText);
  711. } else if (astrcmpi(name, "dark") == 0) {
  712. DEF_PALETTE_ASSIGN(Dark);
  713. } else if (astrcmpi(name, "highlight") == 0) {
  714. DEF_PALETTE_ASSIGN(Highlight);
  715. } else if (astrcmpi(name, "highlightedText") == 0) {
  716. DEF_PALETTE_ASSIGN(HighlightedText);
  717. } else if (astrcmpi(name, "light") == 0) {
  718. DEF_PALETTE_ASSIGN(Light);
  719. } else if (astrcmpi(name, "link") == 0) {
  720. DEF_PALETTE_ASSIGN(Link);
  721. } else if (astrcmpi(name, "linkVisited") == 0) {
  722. DEF_PALETTE_ASSIGN(LinkVisited);
  723. } else if (astrcmpi(name, "mid") == 0) {
  724. DEF_PALETTE_ASSIGN(Mid);
  725. } else if (astrcmpi(name, "midlight") == 0) {
  726. DEF_PALETTE_ASSIGN(Midlight);
  727. } else if (astrcmpi(name, "shadow") == 0) {
  728. DEF_PALETTE_ASSIGN(Shadow);
  729. } else if (astrcmpi(name, "text") == 0 ||
  730. astrcmpi(name, "foreground") == 0) {
  731. DEF_PALETTE_ASSIGN(Text);
  732. } else if (astrcmpi(name, "toolTipBase") == 0) {
  733. DEF_PALETTE_ASSIGN(ToolTipBase);
  734. } else if (astrcmpi(name, "toolTipText") == 0) {
  735. DEF_PALETTE_ASSIGN(ToolTipText);
  736. } else if (astrcmpi(name, "windowText") == 0) {
  737. DEF_PALETTE_ASSIGN(WindowText);
  738. } else if (astrcmpi(name, "window") == 0 ||
  739. astrcmpi(name, "background") == 0) {
  740. DEF_PALETTE_ASSIGN(Window);
  741. } else {
  742. return;
  743. }
  744. #undef DEF_PALETTE_ASSIGN
  745. switch (group) {
  746. case QPalette::Disabled:
  747. case QPalette::Active:
  748. case QPalette::Inactive:
  749. func((QPalette::ColorGroup)group);
  750. break;
  751. default:
  752. func((QPalette::ColorGroup)QPalette::Disabled);
  753. func((QPalette::ColorGroup)QPalette::Active);
  754. func((QPalette::ColorGroup)QPalette::Inactive);
  755. }
  756. }
  757. struct CFParser {
  758. cf_parser cfp = {};
  759. inline ~CFParser() { cf_parser_free(&cfp); }
  760. inline operator cf_parser *() { return &cfp; }
  761. inline cf_parser *operator->() { return &cfp; }
  762. };
  763. void OBSApp::ParseExtraThemeData(const char *path)
  764. {
  765. BPtr<char> data = os_quick_read_utf8_file(path);
  766. QPalette pal = palette();
  767. CFParser cfp;
  768. int ret;
  769. cf_parser_parse(cfp, data, path);
  770. while (cf_go_to_token(cfp, "OBSTheme", nullptr)) {
  771. if (!cf_next_token(cfp))
  772. return;
  773. int group = -1;
  774. if (cf_token_is(cfp, ":")) {
  775. ret = cf_next_token_should_be(cfp, ":", nullptr,
  776. nullptr);
  777. if (ret != PARSE_SUCCESS)
  778. continue;
  779. if (!cf_next_token(cfp))
  780. return;
  781. if (cf_token_is(cfp, "disabled")) {
  782. group = QPalette::Disabled;
  783. } else if (cf_token_is(cfp, "active")) {
  784. group = QPalette::Active;
  785. } else if (cf_token_is(cfp, "inactive")) {
  786. group = QPalette::Inactive;
  787. } else {
  788. continue;
  789. }
  790. if (!cf_next_token(cfp))
  791. return;
  792. }
  793. if (!cf_token_is(cfp, "{"))
  794. continue;
  795. for (;;) {
  796. if (!cf_next_token(cfp))
  797. return;
  798. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name",
  799. nullptr);
  800. if (ret != PARSE_SUCCESS)
  801. break;
  802. DStr name;
  803. dstr_copy_strref(name, &cfp->cur_token->str);
  804. ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
  805. if (ret != PARSE_SUCCESS)
  806. continue;
  807. if (!cf_next_token(cfp))
  808. return;
  809. const char *array;
  810. uint32_t color = 0;
  811. if (cf_token_is(cfp, "#")) {
  812. array = cfp->cur_token->str.array;
  813. color = strtol(array + 1, nullptr, 16);
  814. } else if (cf_token_is(cfp, "rgb")) {
  815. ret = cf_next_token_should_be(cfp, "(", ";",
  816. nullptr);
  817. if (ret != PARSE_SUCCESS)
  818. continue;
  819. if (!cf_next_token(cfp))
  820. return;
  821. array = cfp->cur_token->str.array;
  822. color |= strtol(array, nullptr, 10) << 16;
  823. ret = cf_next_token_should_be(cfp, ",", ";",
  824. nullptr);
  825. if (ret != PARSE_SUCCESS)
  826. continue;
  827. if (!cf_next_token(cfp))
  828. return;
  829. array = cfp->cur_token->str.array;
  830. color |= strtol(array, nullptr, 10) << 8;
  831. ret = cf_next_token_should_be(cfp, ",", ";",
  832. nullptr);
  833. if (ret != PARSE_SUCCESS)
  834. continue;
  835. if (!cf_next_token(cfp))
  836. return;
  837. array = cfp->cur_token->str.array;
  838. color |= strtol(array, nullptr, 10);
  839. } else if (cf_token_is(cfp, "white")) {
  840. color = 0xFFFFFF;
  841. } else if (cf_token_is(cfp, "black")) {
  842. color = 0;
  843. }
  844. if (!cf_go_to_token(cfp, ";", nullptr))
  845. return;
  846. AddExtraThemeColor(pal, group, name->array, color);
  847. }
  848. ret = cf_token_should_be(cfp, "}", "}", nullptr);
  849. if (ret != PARSE_SUCCESS)
  850. continue;
  851. }
  852. setPalette(pal);
  853. }
  854. bool OBSApp::SetTheme(std::string name, std::string path)
  855. {
  856. theme = name;
  857. /* Check user dir first, then preinstalled themes. */
  858. if (path == "") {
  859. char userDir[512];
  860. name = "themes/" + name + ".qss";
  861. string temp = "obs-studio/" + name;
  862. int ret = GetConfigPath(userDir, sizeof(userDir), temp.c_str());
  863. if (ret > 0 && QFile::exists(userDir)) {
  864. path = string(userDir);
  865. } else if (!GetDataFilePath(name.c_str(), path)) {
  866. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  867. return false;
  868. }
  869. }
  870. QString mpath = QString("file:///") + path.c_str();
  871. setPalette(defaultPalette);
  872. setStyleSheet(mpath);
  873. ParseExtraThemeData(path.c_str());
  874. emit StyleChanged();
  875. return true;
  876. }
  877. bool OBSApp::InitTheme()
  878. {
  879. defaultPalette = palette();
  880. const char *themeName =
  881. config_get_string(globalConfig, "General", "CurrentTheme2");
  882. if (!themeName)
  883. /* Use deprecated "CurrentTheme" value if available */
  884. themeName = config_get_string(globalConfig, "General",
  885. "CurrentTheme");
  886. if (!themeName)
  887. /* Use deprecated "Theme" value if available */
  888. themeName = config_get_string(globalConfig, "General", "Theme");
  889. if (!themeName)
  890. themeName = DEFAULT_THEME;
  891. if (!themeName)
  892. themeName = "Dark";
  893. if (strcmp(themeName, "Default") == 0)
  894. themeName = "System";
  895. if (strcmp(themeName, "System") != 0 && SetTheme(themeName))
  896. return true;
  897. return SetTheme("System");
  898. }
  899. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  900. : QApplication(argc, argv), profilerNameStore(store)
  901. {
  902. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  903. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  904. }
  905. OBSApp::~OBSApp()
  906. {
  907. #ifdef _WIN32
  908. bool disableAudioDucking =
  909. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  910. if (disableAudioDucking)
  911. DisableAudioDucking(false);
  912. #endif
  913. #ifdef __APPLE__
  914. bool vsyncDiabled =
  915. config_get_bool(globalConfig, "Video", "DisableOSXVSync");
  916. bool resetVSync =
  917. config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
  918. if (vsyncDiabled && resetVSync)
  919. EnableOSXVSync(true);
  920. #endif
  921. os_inhibit_sleep_set_active(sleepInhibitor, false);
  922. os_inhibit_sleep_destroy(sleepInhibitor);
  923. }
  924. static void move_basic_to_profiles(void)
  925. {
  926. char path[512];
  927. char new_path[512];
  928. os_glob_t *glob;
  929. /* if not first time use */
  930. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  931. return;
  932. if (!os_file_exists(path))
  933. return;
  934. /* if the profiles directory doesn't already exist */
  935. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  936. return;
  937. if (os_file_exists(new_path))
  938. return;
  939. if (os_mkdir(new_path) == MKDIR_ERROR)
  940. return;
  941. strcat(new_path, "/");
  942. strcat(new_path, Str("Untitled"));
  943. if (os_mkdir(new_path) == MKDIR_ERROR)
  944. return;
  945. strcat(path, "/*.*");
  946. if (os_glob(path, 0, &glob) != 0)
  947. return;
  948. strcpy(path, new_path);
  949. for (size_t i = 0; i < glob->gl_pathc; i++) {
  950. struct os_globent ent = glob->gl_pathv[i];
  951. char *file;
  952. if (ent.directory)
  953. continue;
  954. file = strrchr(ent.path, '/');
  955. if (!file++)
  956. continue;
  957. if (astrcmpi(file, "scenes.json") == 0)
  958. continue;
  959. strcpy(new_path, path);
  960. strcat(new_path, "/");
  961. strcat(new_path, file);
  962. os_rename(ent.path, new_path);
  963. }
  964. os_globfree(glob);
  965. }
  966. static void move_basic_to_scene_collections(void)
  967. {
  968. char path[512];
  969. char new_path[512];
  970. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  971. return;
  972. if (!os_file_exists(path))
  973. return;
  974. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  975. return;
  976. if (os_file_exists(new_path))
  977. return;
  978. if (os_mkdir(new_path) == MKDIR_ERROR)
  979. return;
  980. strcat(path, "/scenes.json");
  981. strcat(new_path, "/");
  982. strcat(new_path, Str("Untitled"));
  983. strcat(new_path, ".json");
  984. os_rename(path, new_path);
  985. }
  986. void OBSApp::AppInit()
  987. {
  988. ProfileScope("OBSApp::AppInit");
  989. if (!InitApplicationBundle())
  990. throw "Failed to initialize application bundle";
  991. if (!MakeUserDirs())
  992. throw "Failed to create required user directories";
  993. if (!InitGlobalConfig())
  994. throw "Failed to initialize global config";
  995. if (!InitLocale())
  996. throw "Failed to load locale";
  997. if (!InitTheme())
  998. throw "Failed to load theme";
  999. config_set_default_string(globalConfig, "Basic", "Profile",
  1000. Str("Untitled"));
  1001. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  1002. Str("Untitled"));
  1003. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  1004. Str("Untitled"));
  1005. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  1006. Str("Untitled"));
  1007. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  1008. config_set_string(globalConfig, "Basic", "Profile",
  1009. Str("Untitled"));
  1010. config_set_string(globalConfig, "Basic", "ProfileDir",
  1011. Str("Untitled"));
  1012. }
  1013. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  1014. config_set_string(globalConfig, "Basic", "SceneCollection",
  1015. Str("Untitled"));
  1016. config_set_string(globalConfig, "Basic", "SceneCollectionFile",
  1017. Str("Untitled"));
  1018. }
  1019. #ifdef _WIN32
  1020. bool disableAudioDucking =
  1021. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  1022. if (disableAudioDucking)
  1023. DisableAudioDucking(true);
  1024. #endif
  1025. #ifdef __APPLE__
  1026. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  1027. EnableOSXVSync(false);
  1028. #endif
  1029. UpdateHotkeyFocusSetting(false);
  1030. move_basic_to_profiles();
  1031. move_basic_to_scene_collections();
  1032. if (!MakeUserProfileDirs())
  1033. throw "Failed to create profile directories";
  1034. }
  1035. const char *OBSApp::GetRenderModule() const
  1036. {
  1037. const char *renderer =
  1038. config_get_string(globalConfig, "Video", "Renderer");
  1039. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1040. }
  1041. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1042. {
  1043. char path[512];
  1044. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1045. return false;
  1046. return obs_startup(locale, path, store);
  1047. }
  1048. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1049. {
  1050. obs_hotkey_enable_background_press(
  1051. (inFocus && enableHotkeysInFocus) ||
  1052. (!inFocus && enableHotkeysOutOfFocus));
  1053. }
  1054. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1055. {
  1056. enableHotkeysInFocus = true;
  1057. enableHotkeysOutOfFocus = true;
  1058. const char *hotkeyFocusType =
  1059. config_get_string(globalConfig, "General", "HotkeyFocusType");
  1060. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1061. enableHotkeysInFocus = false;
  1062. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1063. enableHotkeysOutOfFocus = false;
  1064. }
  1065. if (resetState)
  1066. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1067. }
  1068. void OBSApp::DisableHotkeys()
  1069. {
  1070. enableHotkeysInFocus = false;
  1071. enableHotkeysOutOfFocus = false;
  1072. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1073. }
  1074. Q_DECLARE_METATYPE(VoidFunc)
  1075. void OBSApp::Exec(VoidFunc func)
  1076. {
  1077. func();
  1078. }
  1079. bool OBSApp::OBSInit()
  1080. {
  1081. ProfileScope("OBSApp::OBSInit");
  1082. setAttribute(Qt::AA_UseHighDpiPixmaps);
  1083. qRegisterMetaType<VoidFunc>();
  1084. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1085. return false;
  1086. #ifdef _WIN32
  1087. bool browserHWAccel =
  1088. config_get_bool(globalConfig, "General", "BrowserHWAccel");
  1089. obs_data_t *settings = obs_data_create();
  1090. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1091. obs_apply_private_data(settings);
  1092. obs_data_release(settings);
  1093. blog(LOG_INFO, "Current Date/Time: %s",
  1094. CurrentDateTimeString().c_str());
  1095. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1096. browserHWAccel ? "true" : "false");
  1097. #endif
  1098. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1099. setQuitOnLastWindowClosed(false);
  1100. mainWindow = new OBSBasic();
  1101. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1102. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1103. mainWindow->OBSInit();
  1104. connect(this, &QGuiApplication::applicationStateChanged,
  1105. [this](Qt::ApplicationState state) {
  1106. ResetHotkeyState(state == Qt::ApplicationActive);
  1107. });
  1108. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1109. return true;
  1110. }
  1111. string OBSApp::GetVersionString() const
  1112. {
  1113. stringstream ver;
  1114. #ifdef HAVE_OBSCONFIG_H
  1115. ver << OBS_VERSION;
  1116. #else
  1117. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1118. << LIBOBS_API_PATCH_VER;
  1119. #endif
  1120. ver << " (";
  1121. #ifdef _WIN32
  1122. if (sizeof(void *) == 8)
  1123. ver << "64-bit, ";
  1124. else
  1125. ver << "32-bit, ";
  1126. ver << "windows)";
  1127. #elif __APPLE__
  1128. ver << "mac)";
  1129. #elif __FreeBSD__
  1130. ver << "freebsd)";
  1131. #else /* assume linux for the time being */
  1132. ver << "linux)";
  1133. #endif
  1134. return ver.str();
  1135. }
  1136. bool OBSApp::IsPortableMode()
  1137. {
  1138. return portable_mode;
  1139. }
  1140. #ifdef __APPLE__
  1141. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1142. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1143. #elif _WIN32
  1144. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1145. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1146. #else
  1147. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1148. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1149. #endif
  1150. const char *OBSApp::InputAudioSource() const
  1151. {
  1152. return INPUT_AUDIO_SOURCE;
  1153. }
  1154. const char *OBSApp::OutputAudioSource() const
  1155. {
  1156. return OUTPUT_AUDIO_SOURCE;
  1157. }
  1158. const char *OBSApp::GetLastLog() const
  1159. {
  1160. return lastLogFile.c_str();
  1161. }
  1162. const char *OBSApp::GetCurrentLog() const
  1163. {
  1164. return currentLogFile.c_str();
  1165. }
  1166. const char *OBSApp::GetLastCrashLog() const
  1167. {
  1168. return lastCrashLogFile.c_str();
  1169. }
  1170. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1171. {
  1172. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1173. if (cb(lookupVal, out))
  1174. return true;
  1175. }
  1176. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1177. }
  1178. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1179. const char *disambiguation, int n) const
  1180. {
  1181. const char *out = nullptr;
  1182. if (!App()->TranslateString(sourceText, &out))
  1183. return QString(sourceText);
  1184. UNUSED_PARAMETER(context);
  1185. UNUSED_PARAMETER(disambiguation);
  1186. UNUSED_PARAMETER(n);
  1187. return QT_UTF8(out);
  1188. }
  1189. static bool get_token(lexer *lex, string &str, base_token_type type)
  1190. {
  1191. base_token token;
  1192. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1193. return false;
  1194. if (token.type != type)
  1195. return false;
  1196. str.assign(token.text.array, token.text.len);
  1197. return true;
  1198. }
  1199. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1200. {
  1201. base_token token;
  1202. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1203. return false;
  1204. if (token.type != type)
  1205. return false;
  1206. return strref_cmp(&token.text, str) == 0;
  1207. }
  1208. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1209. {
  1210. BaseLexer lex;
  1211. string year, month, day, hour, minute, second;
  1212. lexer_start(lex, name);
  1213. if (has_prefix) {
  1214. string temp;
  1215. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1216. return 0;
  1217. }
  1218. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1219. return 0;
  1220. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1221. return 0;
  1222. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1223. return 0;
  1224. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1225. return 0;
  1226. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1227. return 0;
  1228. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1229. return 0;
  1230. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1231. return 0;
  1232. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1233. return 0;
  1234. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1235. return 0;
  1236. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1237. return 0;
  1238. stringstream timestring;
  1239. timestring << year << month << day << hour << minute << second;
  1240. return std::stoull(timestring.str());
  1241. }
  1242. static void delete_oldest_file(bool has_prefix, const char *location)
  1243. {
  1244. BPtr<char> logDir(GetConfigPathPtr(location));
  1245. string oldestLog;
  1246. uint64_t oldest_ts = (uint64_t)-1;
  1247. struct os_dirent *entry;
  1248. unsigned int maxLogs = (unsigned int)config_get_uint(
  1249. App()->GlobalConfig(), "General", "MaxLogs");
  1250. os_dir_t *dir = os_opendir(logDir);
  1251. if (dir) {
  1252. unsigned int count = 0;
  1253. while ((entry = os_readdir(dir)) != NULL) {
  1254. if (entry->directory || *entry->d_name == '.')
  1255. continue;
  1256. uint64_t ts =
  1257. convert_log_name(has_prefix, entry->d_name);
  1258. if (ts) {
  1259. if (ts < oldest_ts) {
  1260. oldestLog = entry->d_name;
  1261. oldest_ts = ts;
  1262. }
  1263. count++;
  1264. }
  1265. }
  1266. os_closedir(dir);
  1267. if (count > maxLogs) {
  1268. stringstream delPath;
  1269. delPath << logDir << "/" << oldestLog;
  1270. os_unlink(delPath.str().c_str());
  1271. }
  1272. }
  1273. }
  1274. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1275. std::string &last)
  1276. {
  1277. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1278. struct os_dirent *entry;
  1279. os_dir_t *dir = os_opendir(logDir);
  1280. uint64_t highest_ts = 0;
  1281. if (dir) {
  1282. while ((entry = os_readdir(dir)) != NULL) {
  1283. if (entry->directory || *entry->d_name == '.')
  1284. continue;
  1285. uint64_t ts =
  1286. convert_log_name(has_prefix, entry->d_name);
  1287. if (ts > highest_ts) {
  1288. last = entry->d_name;
  1289. highest_ts = ts;
  1290. }
  1291. }
  1292. os_closedir(dir);
  1293. }
  1294. }
  1295. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1296. {
  1297. time_t now = time(0);
  1298. char file[256] = {};
  1299. struct tm *cur_time;
  1300. cur_time = localtime(&now);
  1301. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1302. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1303. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1304. cur_time->tm_min, cur_time->tm_sec, extension);
  1305. return string(file);
  1306. }
  1307. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1308. const char *format)
  1309. {
  1310. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1311. bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux");
  1312. if ((strcmp(extension, "mp4") == 0) && autoRemux)
  1313. extension = "mkv";
  1314. BPtr<char> filename =
  1315. os_generate_formatted_filename(extension, !noSpace, format);
  1316. remuxFilename = string(filename);
  1317. remuxAfterRecord = autoRemux;
  1318. return string(filename);
  1319. }
  1320. vector<pair<string, string>> GetLocaleNames()
  1321. {
  1322. string path;
  1323. if (!GetDataFilePath("locale.ini", path))
  1324. throw "Could not find locale.ini path";
  1325. ConfigFile ini;
  1326. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1327. throw "Could not open locale.ini";
  1328. size_t sections = config_num_sections(ini);
  1329. vector<pair<string, string>> names;
  1330. names.reserve(sections);
  1331. for (size_t i = 0; i < sections; i++) {
  1332. const char *tag = config_get_section(ini, i);
  1333. const char *name = config_get_string(ini, tag, "Name");
  1334. names.emplace_back(tag, name);
  1335. }
  1336. return names;
  1337. }
  1338. static void create_log_file(fstream &logFile)
  1339. {
  1340. stringstream dst;
  1341. get_last_log(false, "obs-studio/logs", lastLogFile);
  1342. #ifdef _WIN32
  1343. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1344. #endif
  1345. currentLogFile = GenerateTimeDateFilename("txt");
  1346. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1347. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1348. #ifdef _WIN32
  1349. BPtr<wchar_t> wpath;
  1350. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1351. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1352. #else
  1353. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1354. #endif
  1355. if (logFile.is_open()) {
  1356. delete_oldest_file(false, "obs-studio/logs");
  1357. base_set_log_handler(do_log, &logFile);
  1358. } else {
  1359. blog(LOG_ERROR, "Failed to open log file");
  1360. }
  1361. }
  1362. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1363. profiler_name_store_free(store);
  1364. };
  1365. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1366. decltype(ProfilerNameStoreRelease)>;
  1367. ProfilerNameStore CreateNameStore()
  1368. {
  1369. return ProfilerNameStore{profiler_name_store_create(),
  1370. ProfilerNameStoreRelease};
  1371. }
  1372. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1373. profile_snapshot_free(snap);
  1374. };
  1375. using ProfilerSnapshot =
  1376. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1377. ProfilerSnapshot GetSnapshot()
  1378. {
  1379. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1380. }
  1381. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1382. {
  1383. if (currentLogFile.empty())
  1384. return;
  1385. auto pos = currentLogFile.rfind('.');
  1386. if (pos == currentLogFile.npos)
  1387. return;
  1388. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1389. ostringstream dst;
  1390. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1391. dst.write(currentLogFile.c_str(), pos);
  1392. dst.write(LITERAL_SIZE(".csv.gz"));
  1393. #undef LITERAL_SIZE
  1394. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1395. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1396. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1397. static_cast<const char *>(path));
  1398. }
  1399. static auto ProfilerFree = [](void *) {
  1400. profiler_stop();
  1401. auto snap = GetSnapshot();
  1402. profiler_print(snap.get());
  1403. profiler_print_time_between_calls(snap.get());
  1404. SaveProfilerData(snap);
  1405. profiler_free();
  1406. };
  1407. static const char *run_program_init = "run_program_init";
  1408. static int run_program(fstream &logFile, int argc, char *argv[])
  1409. {
  1410. int ret = -1;
  1411. auto profilerNameStore = CreateNameStore();
  1412. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1413. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1414. profiler_start();
  1415. profile_register_root(run_program_init, 0);
  1416. ScopeProfiler prof{run_program_init};
  1417. #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  1418. QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
  1419. #endif
  1420. QCoreApplication::addLibraryPath(".");
  1421. #if __APPLE__
  1422. InstallNSApplicationSubclass();
  1423. #endif
  1424. OBSApp program(argc, argv, profilerNameStore.get());
  1425. try {
  1426. bool created_log = false;
  1427. program.AppInit();
  1428. delete_oldest_file(false, "obs-studio/profiler_data");
  1429. OBSTranslator translator;
  1430. program.installTranslator(&translator);
  1431. #ifdef _WIN32
  1432. /* --------------------------------------- */
  1433. /* check and warn if already running */
  1434. bool cancel_launch = false;
  1435. bool already_running = false;
  1436. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1437. if (!already_running) {
  1438. goto run;
  1439. }
  1440. if (!multi) {
  1441. QMessageBox::StandardButtons buttons(
  1442. QMessageBox::Yes | QMessageBox::Cancel);
  1443. QMessageBox mb(QMessageBox::Question,
  1444. QTStr("AlreadyRunning.Title"),
  1445. QTStr("AlreadyRunning.Text"), buttons,
  1446. nullptr);
  1447. mb.setButtonText(QMessageBox::Yes,
  1448. QTStr("AlreadyRunning.LaunchAnyway"));
  1449. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1450. mb.setDefaultButton(QMessageBox::Cancel);
  1451. QMessageBox::StandardButton button;
  1452. button = (QMessageBox::StandardButton)mb.exec();
  1453. cancel_launch = button == QMessageBox::Cancel;
  1454. }
  1455. if (cancel_launch)
  1456. return 0;
  1457. if (!created_log) {
  1458. create_log_file(logFile);
  1459. created_log = true;
  1460. }
  1461. if (multi) {
  1462. blog(LOG_INFO, "User enabled --multi flag and is now "
  1463. "running multiple instances of OBS.");
  1464. } else {
  1465. blog(LOG_WARNING, "================================");
  1466. blog(LOG_WARNING, "Warning: OBS is already running!");
  1467. blog(LOG_WARNING, "================================");
  1468. blog(LOG_WARNING, "User is now running multiple "
  1469. "instances of OBS!");
  1470. }
  1471. /* --------------------------------------- */
  1472. run:
  1473. #endif
  1474. if (!created_log) {
  1475. create_log_file(logFile);
  1476. created_log = true;
  1477. }
  1478. if (argc > 1) {
  1479. stringstream stor;
  1480. stor << argv[1];
  1481. for (int i = 2; i < argc; ++i) {
  1482. stor << " " << argv[i];
  1483. }
  1484. blog(LOG_INFO, "Command Line Arguments: %s",
  1485. stor.str().c_str());
  1486. }
  1487. if (!program.OBSInit())
  1488. return 0;
  1489. prof.Stop();
  1490. return program.exec();
  1491. } catch (const char *error) {
  1492. blog(LOG_ERROR, "%s", error);
  1493. OBSErrorBox(nullptr, "%s", error);
  1494. }
  1495. return ret;
  1496. }
  1497. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1498. #ifdef _WIN32
  1499. #define CRASH_MESSAGE \
  1500. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1501. "to the clipboard? (Crash logs will still be saved to the " \
  1502. "%appdata%\\obs-studio\\crashes directory)"
  1503. static void main_crash_handler(const char *format, va_list args, void *param)
  1504. {
  1505. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1506. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1507. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1508. delete_oldest_file(true, "obs-studio/crashes");
  1509. string name = "obs-studio/crashes/Crash ";
  1510. name += GenerateTimeDateFilename("txt");
  1511. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1512. fstream file;
  1513. #ifdef _WIN32
  1514. BPtr<wchar_t> wpath;
  1515. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1516. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1517. ios_base::binary);
  1518. #else
  1519. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1520. ios_base::binary);
  1521. #endif
  1522. file << text;
  1523. file.close();
  1524. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1525. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1526. if (ret == IDYES) {
  1527. size_t len = strlen(text);
  1528. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1529. memcpy(GlobalLock(mem), text, len);
  1530. GlobalUnlock(mem);
  1531. OpenClipboard(0);
  1532. EmptyClipboard();
  1533. SetClipboardData(CF_TEXT, mem);
  1534. CloseClipboard();
  1535. }
  1536. exit(-1);
  1537. UNUSED_PARAMETER(param);
  1538. }
  1539. static void load_debug_privilege(void)
  1540. {
  1541. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1542. TOKEN_PRIVILEGES tp;
  1543. HANDLE token;
  1544. LUID val;
  1545. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1546. return;
  1547. }
  1548. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1549. tp.PrivilegeCount = 1;
  1550. tp.Privileges[0].Luid = val;
  1551. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1552. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1553. NULL);
  1554. }
  1555. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1556. tp.PrivilegeCount = 1;
  1557. tp.Privileges[0].Luid = val;
  1558. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1559. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1560. NULL)) {
  1561. blog(LOG_INFO, "Could not set privilege to "
  1562. "increase GPU priority");
  1563. }
  1564. }
  1565. CloseHandle(token);
  1566. }
  1567. #endif
  1568. #ifdef __APPLE__
  1569. #define BASE_PATH ".."
  1570. #else
  1571. #define BASE_PATH "../.."
  1572. #endif
  1573. #define CONFIG_PATH BASE_PATH "/config"
  1574. #ifndef OBS_UNIX_STRUCTURE
  1575. #define OBS_UNIX_STRUCTURE 0
  1576. #endif
  1577. int GetConfigPath(char *path, size_t size, const char *name)
  1578. {
  1579. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1580. if (name && *name) {
  1581. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1582. } else {
  1583. return snprintf(path, size, CONFIG_PATH);
  1584. }
  1585. } else {
  1586. return os_get_config_path(path, size, name);
  1587. }
  1588. }
  1589. char *GetConfigPathPtr(const char *name)
  1590. {
  1591. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1592. char path[512];
  1593. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1594. return bstrdup(path);
  1595. } else {
  1596. return NULL;
  1597. }
  1598. } else {
  1599. return os_get_config_path_ptr(name);
  1600. }
  1601. }
  1602. int GetProgramDataPath(char *path, size_t size, const char *name)
  1603. {
  1604. return os_get_program_data_path(path, size, name);
  1605. }
  1606. char *GetProgramDataPathPtr(const char *name)
  1607. {
  1608. return os_get_program_data_path_ptr(name);
  1609. }
  1610. bool GetFileSafeName(const char *name, std::string &file)
  1611. {
  1612. size_t base_len = strlen(name);
  1613. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1614. std::wstring wfile;
  1615. if (!len)
  1616. return false;
  1617. wfile.resize(len);
  1618. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1619. for (size_t i = wfile.size(); i > 0; i--) {
  1620. size_t im1 = i - 1;
  1621. if (iswspace(wfile[im1])) {
  1622. wfile[im1] = '_';
  1623. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1624. wfile.erase(im1, 1);
  1625. }
  1626. }
  1627. if (wfile.size() == 0)
  1628. wfile = L"characters_only";
  1629. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1630. if (!len)
  1631. return false;
  1632. file.resize(len);
  1633. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1634. return true;
  1635. }
  1636. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1637. {
  1638. size_t len = path.size();
  1639. if (extension) {
  1640. path += ".";
  1641. path += extension;
  1642. }
  1643. if (!os_file_exists(path.c_str()))
  1644. return true;
  1645. int index = 1;
  1646. do {
  1647. path.resize(len);
  1648. path += std::to_string(++index);
  1649. if (extension) {
  1650. path += ".";
  1651. path += extension;
  1652. }
  1653. } while (os_file_exists(path.c_str()));
  1654. return true;
  1655. }
  1656. bool WindowPositionValid(QRect rect)
  1657. {
  1658. for (QScreen *screen : QGuiApplication::screens()) {
  1659. if (screen->availableGeometry().intersects(rect))
  1660. return true;
  1661. }
  1662. return false;
  1663. }
  1664. static inline bool arg_is(const char *arg, const char *long_form,
  1665. const char *short_form)
  1666. {
  1667. return (long_form && strcmp(arg, long_form) == 0) ||
  1668. (short_form && strcmp(arg, short_form) == 0);
  1669. }
  1670. #if !defined(_WIN32) && !defined(__APPLE__)
  1671. #define IS_UNIX 1
  1672. #endif
  1673. /* if using XDG and was previously using an older build of OBS, move config
  1674. * files to XDG directory */
  1675. #if defined(USE_XDG) && defined(IS_UNIX)
  1676. static void move_to_xdg(void)
  1677. {
  1678. char old_path[512];
  1679. char new_path[512];
  1680. char *home = getenv("HOME");
  1681. if (!home)
  1682. return;
  1683. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1684. return;
  1685. /* make base xdg path if it doesn't already exist */
  1686. if (GetConfigPath(new_path, 512, "") <= 0)
  1687. return;
  1688. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1689. return;
  1690. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1691. return;
  1692. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1693. rename(old_path, new_path);
  1694. }
  1695. }
  1696. #endif
  1697. static bool update_ffmpeg_output(ConfigFile &config)
  1698. {
  1699. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1700. return false;
  1701. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1702. if (!url)
  1703. return false;
  1704. bool isActualURL = strstr(url, "://") != nullptr;
  1705. if (isActualURL)
  1706. return false;
  1707. string urlStr = url;
  1708. string extension;
  1709. for (size_t i = urlStr.length(); i > 0; i--) {
  1710. size_t idx = i - 1;
  1711. if (urlStr[idx] == '.') {
  1712. extension = &urlStr[i];
  1713. }
  1714. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1715. urlStr[idx] = 0;
  1716. break;
  1717. }
  1718. }
  1719. if (urlStr.empty() || extension.empty())
  1720. return false;
  1721. config_remove_value(config, "AdvOut", "FFURL");
  1722. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1723. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1724. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1725. return true;
  1726. }
  1727. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1728. {
  1729. bool changed = false;
  1730. if (config_has_user_value(config, sec, "Reconnect")) {
  1731. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1732. config_set_bool(config, "Output", "Reconnect", reconnect);
  1733. changed = true;
  1734. }
  1735. if (config_has_user_value(config, sec, "RetryDelay")) {
  1736. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1737. config_set_uint(config, "Output", "RetryDelay", delay);
  1738. changed = true;
  1739. }
  1740. if (config_has_user_value(config, sec, "MaxRetries")) {
  1741. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1742. config_set_uint(config, "Output", "MaxRetries", retries);
  1743. changed = true;
  1744. }
  1745. return changed;
  1746. }
  1747. static bool update_reconnect(ConfigFile &config)
  1748. {
  1749. if (!config_has_user_value(config, "Output", "Mode"))
  1750. return false;
  1751. const char *mode = config_get_string(config, "Output", "Mode");
  1752. if (!mode)
  1753. return false;
  1754. const char *section = (strcmp(mode, "Advanced") == 0) ? "AdvOut"
  1755. : "SimpleOutput";
  1756. if (move_reconnect_settings(config, section)) {
  1757. config_remove_value(config, "SimpleOutput", "Reconnect");
  1758. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1759. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1760. config_remove_value(config, "AdvOut", "Reconnect");
  1761. config_remove_value(config, "AdvOut", "RetryDelay");
  1762. config_remove_value(config, "AdvOut", "MaxRetries");
  1763. return true;
  1764. }
  1765. return false;
  1766. }
  1767. static void convert_x264_settings(obs_data_t *data)
  1768. {
  1769. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1770. if (use_bufsize) {
  1771. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1772. if (buffer_size == 0)
  1773. obs_data_set_string(data, "rate_control", "CRF");
  1774. }
  1775. }
  1776. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1777. {
  1778. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1779. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1780. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1781. bool modified = false;
  1782. bool cbr = true;
  1783. if (cbr_item) {
  1784. cbr = obs_data_item_get_bool(cbr_item);
  1785. obs_data_item_unset_user_value(cbr_item);
  1786. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1787. modified = true;
  1788. }
  1789. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1790. if (!cbr_item)
  1791. obs_data_set_string(data, "rate_control", "CBR");
  1792. else if (!cbr)
  1793. convert_x264_settings(data);
  1794. modified = true;
  1795. }
  1796. if (modified)
  1797. obs_data_save_json_safe(data, file, "tmp", "bak");
  1798. obs_data_item_release(&rc_item);
  1799. obs_data_item_release(&cbr_item);
  1800. obs_data_release(data);
  1801. }
  1802. static void upgrade_settings(void)
  1803. {
  1804. char path[512];
  1805. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1806. if (pathlen <= 0)
  1807. return;
  1808. if (!os_file_exists(path))
  1809. return;
  1810. os_dir_t *dir = os_opendir(path);
  1811. if (!dir)
  1812. return;
  1813. struct os_dirent *ent = os_readdir(dir);
  1814. while (ent) {
  1815. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1816. strcmp(ent->d_name, "..") != 0) {
  1817. strcat(path, "/");
  1818. strcat(path, ent->d_name);
  1819. strcat(path, "/basic.ini");
  1820. ConfigFile config;
  1821. int ret;
  1822. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1823. if (ret == CONFIG_SUCCESS) {
  1824. if (update_ffmpeg_output(config) ||
  1825. update_reconnect(config)) {
  1826. config_save_safe(config, "tmp",
  1827. nullptr);
  1828. }
  1829. }
  1830. if (config) {
  1831. const char *sEnc = config_get_string(
  1832. config, "AdvOut", "Encoder");
  1833. const char *rEnc = config_get_string(
  1834. config, "AdvOut", "RecEncoder");
  1835. /* replace "cbr" option with "rate_control" for
  1836. * each profile's encoder data */
  1837. path[pathlen] = 0;
  1838. strcat(path, "/");
  1839. strcat(path, ent->d_name);
  1840. strcat(path, "/recordEncoder.json");
  1841. convert_14_2_encoder_setting(rEnc, path);
  1842. path[pathlen] = 0;
  1843. strcat(path, "/");
  1844. strcat(path, ent->d_name);
  1845. strcat(path, "/streamEncoder.json");
  1846. convert_14_2_encoder_setting(sEnc, path);
  1847. }
  1848. path[pathlen] = 0;
  1849. }
  1850. ent = os_readdir(dir);
  1851. }
  1852. os_closedir(dir);
  1853. }
  1854. void ctrlc_handler(int s)
  1855. {
  1856. UNUSED_PARAMETER(s);
  1857. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1858. main->close();
  1859. }
  1860. int main(int argc, char *argv[])
  1861. {
  1862. #ifndef _WIN32
  1863. signal(SIGPIPE, SIG_IGN);
  1864. struct sigaction sig_handler;
  1865. sig_handler.sa_handler = ctrlc_handler;
  1866. sigemptyset(&sig_handler.sa_mask);
  1867. sig_handler.sa_flags = 0;
  1868. sigaction(SIGINT, &sig_handler, NULL);
  1869. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  1870. a closed pipe. */
  1871. sigset_t sigpipe_mask;
  1872. sigemptyset(&sigpipe_mask);
  1873. sigaddset(&sigpipe_mask, SIGPIPE);
  1874. sigset_t saved_mask;
  1875. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  1876. perror("pthread_sigmask");
  1877. exit(1);
  1878. }
  1879. #endif
  1880. #ifdef _WIN32
  1881. obs_init_win32_crash_handler();
  1882. SetErrorMode(SEM_FAILCRITICALERRORS);
  1883. load_debug_privilege();
  1884. base_set_crash_handler(main_crash_handler, nullptr);
  1885. #endif
  1886. base_get_log_handler(&def_log_handler, nullptr);
  1887. #if defined(USE_XDG) && defined(IS_UNIX)
  1888. move_to_xdg();
  1889. #endif
  1890. obs_set_cmdline_args(argc, argv);
  1891. for (int i = 1; i < argc; i++) {
  1892. if (arg_is(argv[i], "--portable", "-p")) {
  1893. portable_mode = true;
  1894. } else if (arg_is(argv[i], "--multi", "-m")) {
  1895. multi = true;
  1896. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1897. log_verbose = true;
  1898. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  1899. opt_always_on_top = true;
  1900. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1901. unfiltered_log = true;
  1902. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1903. opt_start_streaming = true;
  1904. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1905. opt_start_recording = true;
  1906. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1907. opt_start_replaybuffer = true;
  1908. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1909. if (++i < argc)
  1910. opt_starting_collection = argv[i];
  1911. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1912. if (++i < argc)
  1913. opt_starting_profile = argv[i];
  1914. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1915. if (++i < argc)
  1916. opt_starting_scene = argv[i];
  1917. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1918. opt_minimize_tray = true;
  1919. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1920. opt_studio_mode = true;
  1921. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  1922. opt_allow_opengl = true;
  1923. } else if (arg_is(argv[i], "--help", "-h")) {
  1924. std::cout
  1925. << "--help, -h: Get list of available commands.\n\n"
  1926. << "--startstreaming: Automatically start streaming.\n"
  1927. << "--startrecording: Automatically start recording.\n"
  1928. << "--startreplaybuffer: Start replay buffer.\n\n"
  1929. << "--collection <string>: Use specific scene collection."
  1930. << "\n"
  1931. << "--profile <string>: Use specific profile.\n"
  1932. << "--scene <string>: Start with specific scene.\n\n"
  1933. << "--studio-mode: Enable studio mode.\n"
  1934. << "--minimize-to-tray: Minimize to system tray.\n"
  1935. << "--portable, -p: Use portable mode.\n"
  1936. << "--multi, -m: Don't warn when launching multiple instances.\n\n"
  1937. << "--verbose: Make log more verbose.\n"
  1938. << "--always-on-top: Start in 'always on top' mode.\n\n"
  1939. << "--unfiltered_log: Make log unfiltered.\n\n"
  1940. << "--allow-opengl: Allow OpenGL on Windows.\n\n"
  1941. << "--version, -V: Get current version.\n";
  1942. exit(0);
  1943. } else if (arg_is(argv[i], "--version", "-V")) {
  1944. std::cout << "OBS Studio - "
  1945. << App()->GetVersionString() << "\n";
  1946. exit(0);
  1947. }
  1948. }
  1949. #if !OBS_UNIX_STRUCTURE
  1950. if (!portable_mode) {
  1951. portable_mode =
  1952. os_file_exists(BASE_PATH "/portable_mode") ||
  1953. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1954. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1955. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1956. }
  1957. #endif
  1958. upgrade_settings();
  1959. fstream logFile;
  1960. curl_global_init(CURL_GLOBAL_ALL);
  1961. int ret = run_program(logFile, argc, argv);
  1962. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1963. base_set_log_handler(nullptr, nullptr);
  1964. return ret;
  1965. }