obs-app.cpp 56 KB

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