obs-app.cpp 45 KB

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