obs-app.cpp 60 KB

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