obs-app.cpp 45 KB

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