obs-app.cpp 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943
  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. "CurrentTheme");
  607. if (!themeName) {
  608. /* Use deprecated "Theme" value if available */
  609. themeName = config_get_string(globalConfig,
  610. "General", "Theme");
  611. if (!themeName)
  612. themeName = "Default";
  613. }
  614. if (strcmp(themeName, "Default") != 0 && SetTheme(themeName))
  615. return true;
  616. return SetTheme("Default");
  617. }
  618. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  619. : QApplication(argc, argv),
  620. profilerNameStore(store)
  621. {
  622. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  623. }
  624. OBSApp::~OBSApp()
  625. {
  626. #ifdef _WIN32
  627. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  628. "DisableAudioDucking");
  629. if (disableAudioDucking)
  630. DisableAudioDucking(false);
  631. #endif
  632. #ifdef __APPLE__
  633. bool vsyncDiabled = config_get_bool(globalConfig, "Video",
  634. "DisableOSXVSync");
  635. bool resetVSync = config_get_bool(globalConfig, "Video",
  636. "ResetOSXVSyncOnExit");
  637. if (vsyncDiabled && resetVSync)
  638. EnableOSXVSync(true);
  639. #endif
  640. os_inhibit_sleep_set_active(sleepInhibitor, false);
  641. os_inhibit_sleep_destroy(sleepInhibitor);
  642. }
  643. static void move_basic_to_profiles(void)
  644. {
  645. char path[512];
  646. char new_path[512];
  647. os_glob_t *glob;
  648. /* if not first time use */
  649. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  650. return;
  651. if (!os_file_exists(path))
  652. return;
  653. /* if the profiles directory doesn't already exist */
  654. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  655. return;
  656. if (os_file_exists(new_path))
  657. return;
  658. if (os_mkdir(new_path) == MKDIR_ERROR)
  659. return;
  660. strcat(new_path, "/");
  661. strcat(new_path, Str("Untitled"));
  662. if (os_mkdir(new_path) == MKDIR_ERROR)
  663. return;
  664. strcat(path, "/*.*");
  665. if (os_glob(path, 0, &glob) != 0)
  666. return;
  667. strcpy(path, new_path);
  668. for (size_t i = 0; i < glob->gl_pathc; i++) {
  669. struct os_globent ent = glob->gl_pathv[i];
  670. char *file;
  671. if (ent.directory)
  672. continue;
  673. file = strrchr(ent.path, '/');
  674. if (!file++)
  675. continue;
  676. if (astrcmpi(file, "scenes.json") == 0)
  677. continue;
  678. strcpy(new_path, path);
  679. strcat(new_path, "/");
  680. strcat(new_path, file);
  681. os_rename(ent.path, new_path);
  682. }
  683. os_globfree(glob);
  684. }
  685. static void move_basic_to_scene_collections(void)
  686. {
  687. char path[512];
  688. char new_path[512];
  689. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  690. return;
  691. if (!os_file_exists(path))
  692. return;
  693. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  694. return;
  695. if (os_file_exists(new_path))
  696. return;
  697. if (os_mkdir(new_path) == MKDIR_ERROR)
  698. return;
  699. strcat(path, "/scenes.json");
  700. strcat(new_path, "/");
  701. strcat(new_path, Str("Untitled"));
  702. strcat(new_path, ".json");
  703. os_rename(path, new_path);
  704. }
  705. void OBSApp::AppInit()
  706. {
  707. ProfileScope("OBSApp::AppInit");
  708. if (!InitApplicationBundle())
  709. throw "Failed to initialize application bundle";
  710. if (!MakeUserDirs())
  711. throw "Failed to create required user directories";
  712. if (!InitGlobalConfig())
  713. throw "Failed to initialize global config";
  714. if (!InitLocale())
  715. throw "Failed to load locale";
  716. if (!InitTheme())
  717. throw "Failed to load theme";
  718. config_set_default_string(globalConfig, "Basic", "Profile",
  719. Str("Untitled"));
  720. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  721. Str("Untitled"));
  722. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  723. Str("Untitled"));
  724. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  725. Str("Untitled"));
  726. #ifdef _WIN32
  727. bool disableAudioDucking = config_get_bool(globalConfig, "Audio",
  728. "DisableAudioDucking");
  729. if (disableAudioDucking)
  730. DisableAudioDucking(true);
  731. #endif
  732. #ifdef __APPLE__
  733. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  734. EnableOSXVSync(false);
  735. #endif
  736. move_basic_to_profiles();
  737. move_basic_to_scene_collections();
  738. if (!MakeUserProfileDirs())
  739. throw "Failed to create profile directories";
  740. }
  741. const char *OBSApp::GetRenderModule() const
  742. {
  743. const char *renderer = config_get_string(globalConfig, "Video",
  744. "Renderer");
  745. return (astrcmpi(renderer, "Direct3D 11") == 0) ?
  746. DL_D3D11 : DL_OPENGL;
  747. }
  748. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  749. {
  750. char path[512];
  751. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  752. return false;
  753. return obs_startup(locale, path, store);
  754. }
  755. bool OBSApp::OBSInit()
  756. {
  757. ProfileScope("OBSApp::OBSInit");
  758. bool licenseAccepted = config_get_bool(globalConfig, "General",
  759. "LicenseAccepted");
  760. OBSLicenseAgreement agreement(nullptr);
  761. if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
  762. if (!licenseAccepted) {
  763. config_set_bool(globalConfig, "General",
  764. "LicenseAccepted", true);
  765. config_save(globalConfig);
  766. }
  767. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  768. return false;
  769. blog(LOG_INFO, "Portable mode: %s",
  770. portable_mode ? "true" : "false");
  771. setQuitOnLastWindowClosed(false);
  772. mainWindow = new OBSBasic();
  773. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  774. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  775. mainWindow->OBSInit();
  776. connect(this, &QGuiApplication::applicationStateChanged,
  777. [](Qt::ApplicationState state)
  778. {
  779. obs_hotkey_enable_background_press(
  780. state != Qt::ApplicationActive);
  781. });
  782. obs_hotkey_enable_background_press(
  783. applicationState() != Qt::ApplicationActive);
  784. return true;
  785. } else {
  786. return false;
  787. }
  788. }
  789. string OBSApp::GetVersionString() const
  790. {
  791. stringstream ver;
  792. #ifdef HAVE_OBSCONFIG_H
  793. ver << OBS_VERSION;
  794. #else
  795. ver << LIBOBS_API_MAJOR_VER << "." <<
  796. LIBOBS_API_MINOR_VER << "." <<
  797. LIBOBS_API_PATCH_VER;
  798. #endif
  799. ver << " (";
  800. #ifdef _WIN32
  801. if (sizeof(void*) == 8)
  802. ver << "64bit, ";
  803. ver << "windows)";
  804. #elif __APPLE__
  805. ver << "mac)";
  806. #elif __FreeBSD__
  807. ver << "freebsd)";
  808. #else /* assume linux for the time being */
  809. ver << "linux)";
  810. #endif
  811. return ver.str();
  812. }
  813. bool OBSApp::IsPortableMode()
  814. {
  815. return portable_mode;
  816. }
  817. #ifdef __APPLE__
  818. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  819. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  820. #elif _WIN32
  821. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  822. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  823. #else
  824. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  825. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  826. #endif
  827. const char *OBSApp::InputAudioSource() const
  828. {
  829. return INPUT_AUDIO_SOURCE;
  830. }
  831. const char *OBSApp::OutputAudioSource() const
  832. {
  833. return OUTPUT_AUDIO_SOURCE;
  834. }
  835. const char *OBSApp::GetLastLog() const
  836. {
  837. return lastLogFile.c_str();
  838. }
  839. const char *OBSApp::GetCurrentLog() const
  840. {
  841. return currentLogFile.c_str();
  842. }
  843. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  844. {
  845. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  846. if (cb(lookupVal, out))
  847. return true;
  848. }
  849. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  850. }
  851. QString OBSTranslator::translate(const char *context, const char *sourceText,
  852. const char *disambiguation, int n) const
  853. {
  854. const char *out = nullptr;
  855. if (!App()->TranslateString(sourceText, &out))
  856. return QString(sourceText);
  857. UNUSED_PARAMETER(context);
  858. UNUSED_PARAMETER(disambiguation);
  859. UNUSED_PARAMETER(n);
  860. return QT_UTF8(out);
  861. }
  862. static bool get_token(lexer *lex, string &str, base_token_type type)
  863. {
  864. base_token token;
  865. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  866. return false;
  867. if (token.type != type)
  868. return false;
  869. str.assign(token.text.array, token.text.len);
  870. return true;
  871. }
  872. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  873. {
  874. base_token token;
  875. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  876. return false;
  877. if (token.type != type)
  878. return false;
  879. return strref_cmp(&token.text, str) == 0;
  880. }
  881. static uint64_t convert_log_name(const char *name)
  882. {
  883. BaseLexer lex;
  884. string year, month, day, hour, minute, second;
  885. lexer_start(lex, name);
  886. if (!get_token(lex, year, BASETOKEN_DIGIT)) return 0;
  887. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  888. if (!get_token(lex, month, BASETOKEN_DIGIT)) return 0;
  889. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  890. if (!get_token(lex, day, BASETOKEN_DIGIT)) return 0;
  891. if (!get_token(lex, hour, BASETOKEN_DIGIT)) return 0;
  892. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  893. if (!get_token(lex, minute, BASETOKEN_DIGIT)) return 0;
  894. if (!expect_token(lex, "-", BASETOKEN_OTHER)) return 0;
  895. if (!get_token(lex, second, BASETOKEN_DIGIT)) return 0;
  896. stringstream timestring;
  897. timestring << year << month << day << hour << minute << second;
  898. return std::stoull(timestring.str());
  899. }
  900. static void delete_oldest_file(const char *location)
  901. {
  902. BPtr<char> logDir(GetConfigPathPtr(location));
  903. string oldestLog;
  904. uint64_t oldest_ts = (uint64_t)-1;
  905. struct os_dirent *entry;
  906. unsigned int maxLogs = (unsigned int)config_get_uint(
  907. App()->GlobalConfig(), "General", "MaxLogs");
  908. os_dir_t *dir = os_opendir(logDir);
  909. if (dir) {
  910. unsigned int count = 0;
  911. while ((entry = os_readdir(dir)) != NULL) {
  912. if (entry->directory || *entry->d_name == '.')
  913. continue;
  914. uint64_t ts = convert_log_name(entry->d_name);
  915. if (ts) {
  916. if (ts < oldest_ts) {
  917. oldestLog = entry->d_name;
  918. oldest_ts = ts;
  919. }
  920. count++;
  921. }
  922. }
  923. os_closedir(dir);
  924. if (count > maxLogs) {
  925. stringstream delPath;
  926. delPath << logDir << "/" << oldestLog;
  927. os_unlink(delPath.str().c_str());
  928. }
  929. }
  930. }
  931. static void get_last_log(void)
  932. {
  933. BPtr<char> logDir(GetConfigPathPtr("obs-studio/logs"));
  934. struct os_dirent *entry;
  935. os_dir_t *dir = os_opendir(logDir);
  936. uint64_t highest_ts = 0;
  937. if (dir) {
  938. while ((entry = os_readdir(dir)) != NULL) {
  939. if (entry->directory || *entry->d_name == '.')
  940. continue;
  941. uint64_t ts = convert_log_name(entry->d_name);
  942. if (ts > highest_ts) {
  943. lastLogFile = entry->d_name;
  944. highest_ts = ts;
  945. }
  946. }
  947. os_closedir(dir);
  948. }
  949. }
  950. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  951. {
  952. time_t now = time(0);
  953. char file[256] = {};
  954. struct tm *cur_time;
  955. cur_time = localtime(&now);
  956. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  957. cur_time->tm_year+1900,
  958. cur_time->tm_mon+1,
  959. cur_time->tm_mday,
  960. noSpace ? '_' : ' ',
  961. cur_time->tm_hour,
  962. cur_time->tm_min,
  963. cur_time->tm_sec,
  964. extension);
  965. return string(file);
  966. }
  967. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  968. const char *format)
  969. {
  970. BPtr<char> filename = os_generate_formatted_filename(extension,
  971. !noSpace, format);
  972. return string(filename);
  973. }
  974. vector<pair<string, string>> GetLocaleNames()
  975. {
  976. string path;
  977. if (!GetDataFilePath("locale.ini", path))
  978. throw "Could not find locale.ini path";
  979. ConfigFile ini;
  980. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  981. throw "Could not open locale.ini";
  982. size_t sections = config_num_sections(ini);
  983. vector<pair<string, string>> names;
  984. names.reserve(sections);
  985. for (size_t i = 0; i < sections; i++) {
  986. const char *tag = config_get_section(ini, i);
  987. const char *name = config_get_string(ini, tag, "Name");
  988. names.emplace_back(tag, name);
  989. }
  990. return names;
  991. }
  992. static void create_log_file(fstream &logFile)
  993. {
  994. stringstream dst;
  995. get_last_log();
  996. currentLogFile = GenerateTimeDateFilename("txt");
  997. dst << "obs-studio/logs/" << currentLogFile.c_str();
  998. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  999. #ifdef _WIN32
  1000. BPtr<wchar_t> wpath;
  1001. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1002. logFile.open(wpath,
  1003. ios_base::in | ios_base::out | ios_base::trunc);
  1004. #else
  1005. logFile.open(path,
  1006. ios_base::in | ios_base::out | ios_base::trunc);
  1007. #endif
  1008. if (logFile.is_open()) {
  1009. delete_oldest_file("obs-studio/logs");
  1010. base_set_log_handler(do_log, &logFile);
  1011. } else {
  1012. blog(LOG_ERROR, "Failed to open log file");
  1013. }
  1014. }
  1015. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
  1016. {
  1017. profiler_name_store_free(store);
  1018. };
  1019. using ProfilerNameStore =
  1020. std::unique_ptr<profiler_name_store_t,
  1021. decltype(ProfilerNameStoreRelease)>;
  1022. ProfilerNameStore CreateNameStore()
  1023. {
  1024. return ProfilerNameStore{profiler_name_store_create(),
  1025. ProfilerNameStoreRelease};
  1026. }
  1027. static auto SnapshotRelease = [](profiler_snapshot_t *snap)
  1028. {
  1029. profile_snapshot_free(snap);
  1030. };
  1031. using ProfilerSnapshot =
  1032. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1033. ProfilerSnapshot GetSnapshot()
  1034. {
  1035. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1036. }
  1037. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1038. {
  1039. if (currentLogFile.empty())
  1040. return;
  1041. auto pos = currentLogFile.rfind('.');
  1042. if (pos == currentLogFile.npos)
  1043. return;
  1044. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1045. ostringstream dst;
  1046. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1047. dst.write(currentLogFile.c_str(), pos);
  1048. dst.write(LITERAL_SIZE(".csv.gz"));
  1049. #undef LITERAL_SIZE
  1050. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1051. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1052. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1053. static_cast<const char*>(path));
  1054. }
  1055. static auto ProfilerFree = [](void *)
  1056. {
  1057. profiler_stop();
  1058. auto snap = GetSnapshot();
  1059. profiler_print(snap.get());
  1060. profiler_print_time_between_calls(snap.get());
  1061. SaveProfilerData(snap);
  1062. profiler_free();
  1063. };
  1064. static const char *run_program_init = "run_program_init";
  1065. static int run_program(fstream &logFile, int argc, char *argv[])
  1066. {
  1067. int ret = -1;
  1068. auto profilerNameStore = CreateNameStore();
  1069. std::unique_ptr<void, decltype(ProfilerFree)>
  1070. prof_release(static_cast<void*>(&ProfilerFree),
  1071. ProfilerFree);
  1072. profiler_start();
  1073. profile_register_root(run_program_init, 0);
  1074. ScopeProfiler prof{run_program_init};
  1075. QCoreApplication::addLibraryPath(".");
  1076. OBSApp program(argc, argv, profilerNameStore.get());
  1077. try {
  1078. program.AppInit();
  1079. OBSTranslator translator;
  1080. create_log_file(logFile);
  1081. delete_oldest_file("obs-studio/profiler_data");
  1082. program.installTranslator(&translator);
  1083. #ifdef _WIN32
  1084. /* --------------------------------------- */
  1085. /* check and warn if already running */
  1086. bool already_running = false;
  1087. RunOnceMutex rom = GetRunOnceMutex(already_running);
  1088. if (already_running) {
  1089. blog(LOG_WARNING, "\n================================");
  1090. blog(LOG_WARNING, "Warning: OBS is already running!");
  1091. blog(LOG_WARNING, "================================\n");
  1092. QMessageBox::StandardButtons buttons(
  1093. QMessageBox::Yes | QMessageBox::Cancel);
  1094. QMessageBox mb(QMessageBox::Question,
  1095. QTStr("AlreadyRunning.Title"),
  1096. QTStr("AlreadyRunning.Text"),
  1097. buttons,
  1098. nullptr);
  1099. mb.setButtonText(QMessageBox::Yes,
  1100. QTStr("AlreadyRunning.LaunchAnyway"));
  1101. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1102. mb.setDefaultButton(QMessageBox::Cancel);
  1103. QMessageBox::StandardButton button;
  1104. button = (QMessageBox::StandardButton)mb.exec();
  1105. if (button == QMessageBox::Cancel) {
  1106. blog(LOG_INFO, "User shut down the program "
  1107. "because OBS was already "
  1108. "running");
  1109. return 0;
  1110. }
  1111. blog(LOG_WARNING, "User is now running a secondary "
  1112. "instance of OBS!");
  1113. }
  1114. /* --------------------------------------- */
  1115. #endif
  1116. if (!program.OBSInit())
  1117. return 0;
  1118. prof.Stop();
  1119. return program.exec();
  1120. } catch (const char *error) {
  1121. blog(LOG_ERROR, "%s", error);
  1122. OBSErrorBox(nullptr, "%s", error);
  1123. }
  1124. return ret;
  1125. }
  1126. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1127. #ifdef _WIN32
  1128. #define CRASH_MESSAGE \
  1129. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1130. "to the clipboard? (Crash logs will still be saved to the " \
  1131. "%appdata%\\obs-studio\\crashes directory)"
  1132. static void main_crash_handler(const char *format, va_list args, void *param)
  1133. {
  1134. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1135. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1136. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1137. delete_oldest_file("obs-studio/crashes");
  1138. string name = "obs-studio/crashes/Crash ";
  1139. name += GenerateTimeDateFilename("txt");
  1140. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1141. fstream file;
  1142. #ifdef _WIN32
  1143. BPtr<wchar_t> wpath;
  1144. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1145. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1146. ios_base::binary);
  1147. #else
  1148. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1149. ios_base::binary);
  1150. #endif
  1151. file << text;
  1152. file.close();
  1153. int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
  1154. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1155. if (ret == IDYES) {
  1156. size_t len = strlen(text);
  1157. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1158. memcpy(GlobalLock(mem), text, len);
  1159. GlobalUnlock(mem);
  1160. OpenClipboard(0);
  1161. EmptyClipboard();
  1162. SetClipboardData(CF_TEXT, mem);
  1163. CloseClipboard();
  1164. }
  1165. exit(-1);
  1166. UNUSED_PARAMETER(param);
  1167. }
  1168. static void load_debug_privilege(void)
  1169. {
  1170. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1171. TOKEN_PRIVILEGES tp;
  1172. HANDLE token;
  1173. LUID val;
  1174. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1175. return;
  1176. }
  1177. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1178. tp.PrivilegeCount = 1;
  1179. tp.Privileges[0].Luid = val;
  1180. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1181. AdjustTokenPrivileges(token, false, &tp,
  1182. sizeof(tp), NULL, NULL);
  1183. }
  1184. CloseHandle(token);
  1185. }
  1186. #endif
  1187. #ifdef __APPLE__
  1188. #define BASE_PATH ".."
  1189. #else
  1190. #define BASE_PATH "../.."
  1191. #endif
  1192. #define CONFIG_PATH BASE_PATH "/config"
  1193. #ifndef OBS_UNIX_STRUCTURE
  1194. #define OBS_UNIX_STRUCTURE 0
  1195. #endif
  1196. int GetConfigPath(char *path, size_t size, const char *name)
  1197. {
  1198. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1199. if (name && *name) {
  1200. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1201. } else {
  1202. return snprintf(path, size, CONFIG_PATH);
  1203. }
  1204. } else {
  1205. return os_get_config_path(path, size, name);
  1206. }
  1207. }
  1208. char *GetConfigPathPtr(const char *name)
  1209. {
  1210. if (!OBS_UNIX_STRUCTURE && portable_mode) {
  1211. char path[512];
  1212. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1213. return bstrdup(path);
  1214. } else {
  1215. return NULL;
  1216. }
  1217. } else {
  1218. return os_get_config_path_ptr(name);
  1219. }
  1220. }
  1221. int GetProgramDataPath(char *path, size_t size, const char *name)
  1222. {
  1223. return os_get_program_data_path(path, size, name);
  1224. }
  1225. char *GetProgramDataPathPtr(const char *name)
  1226. {
  1227. return os_get_program_data_path_ptr(name);
  1228. }
  1229. bool GetFileSafeName(const char *name, std::string &file)
  1230. {
  1231. size_t base_len = strlen(name);
  1232. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1233. std::wstring wfile;
  1234. if (!len)
  1235. return false;
  1236. wfile.resize(len);
  1237. os_utf8_to_wcs(name, base_len, &wfile[0], len);
  1238. for (size_t i = wfile.size(); i > 0; i--) {
  1239. size_t im1 = i - 1;
  1240. if (iswspace(wfile[im1])) {
  1241. wfile[im1] = '_';
  1242. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1243. wfile.erase(im1, 1);
  1244. }
  1245. }
  1246. if (wfile.size() == 0)
  1247. wfile = L"characters_only";
  1248. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1249. if (!len)
  1250. return false;
  1251. file.resize(len);
  1252. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
  1253. return true;
  1254. }
  1255. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1256. {
  1257. size_t len = path.size();
  1258. if (extension) {
  1259. path += ".";
  1260. path += extension;
  1261. }
  1262. if (!os_file_exists(path.c_str()))
  1263. return true;
  1264. int index = 1;
  1265. do {
  1266. path.resize(len);
  1267. path += std::to_string(++index);
  1268. if (extension) {
  1269. path += ".";
  1270. path += extension;
  1271. }
  1272. } while (os_file_exists(path.c_str()));
  1273. return true;
  1274. }
  1275. bool WindowPositionValid(QRect rect)
  1276. {
  1277. for (QScreen* screen: QGuiApplication::screens()) {
  1278. if (screen->availableGeometry().intersects(rect))
  1279. return true;
  1280. }
  1281. return false;
  1282. }
  1283. static inline bool arg_is(const char *arg,
  1284. const char *long_form, const char *short_form)
  1285. {
  1286. return (long_form && strcmp(arg, long_form) == 0) ||
  1287. (short_form && strcmp(arg, short_form) == 0);
  1288. }
  1289. #if !defined(_WIN32) && !defined(__APPLE__)
  1290. #define IS_UNIX 1
  1291. #endif
  1292. /* if using XDG and was previously using an older build of OBS, move config
  1293. * files to XDG directory */
  1294. #if defined(USE_XDG) && defined(IS_UNIX)
  1295. static void move_to_xdg(void)
  1296. {
  1297. char old_path[512];
  1298. char new_path[512];
  1299. char *home = getenv("HOME");
  1300. if (!home)
  1301. return;
  1302. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  1303. return;
  1304. /* make base xdg path if it doesn't already exist */
  1305. if (GetConfigPath(new_path, 512, "") <= 0)
  1306. return;
  1307. if (os_mkdirs(new_path) == MKDIR_ERROR)
  1308. return;
  1309. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  1310. return;
  1311. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  1312. rename(old_path, new_path);
  1313. }
  1314. }
  1315. #endif
  1316. static bool update_ffmpeg_output(ConfigFile &config)
  1317. {
  1318. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  1319. return false;
  1320. const char *url = config_get_string(config, "AdvOut", "FFURL");
  1321. if (!url)
  1322. return false;
  1323. bool isActualURL = strstr(url, "://") != nullptr;
  1324. if (isActualURL)
  1325. return false;
  1326. string urlStr = url;
  1327. string extension;
  1328. for (size_t i = urlStr.length(); i > 0; i--) {
  1329. size_t idx = i - 1;
  1330. if (urlStr[idx] == '.') {
  1331. extension = &urlStr[i];
  1332. }
  1333. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  1334. urlStr[idx] = 0;
  1335. break;
  1336. }
  1337. }
  1338. if (urlStr.empty() || extension.empty())
  1339. return false;
  1340. config_remove_value(config, "AdvOut", "FFURL");
  1341. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  1342. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  1343. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  1344. return true;
  1345. }
  1346. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  1347. {
  1348. bool changed = false;
  1349. if (config_has_user_value(config, sec, "Reconnect")) {
  1350. bool reconnect = config_get_bool(config, sec, "Reconnect");
  1351. config_set_bool(config, "Output", "Reconnect", reconnect);
  1352. changed = true;
  1353. }
  1354. if (config_has_user_value(config, sec, "RetryDelay")) {
  1355. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  1356. config_set_uint(config, "Output", "RetryDelay", delay);
  1357. changed = true;
  1358. }
  1359. if (config_has_user_value(config, sec, "MaxRetries")) {
  1360. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  1361. config_set_uint(config, "Output", "MaxRetries", retries);
  1362. changed = true;
  1363. }
  1364. return changed;
  1365. }
  1366. static bool update_reconnect(ConfigFile &config)
  1367. {
  1368. if (!config_has_user_value(config, "Output", "Mode"))
  1369. return false;
  1370. const char *mode = config_get_string(config, "Output", "Mode");
  1371. if (!mode)
  1372. return false;
  1373. const char *section = (strcmp(mode, "Advanced") == 0) ?
  1374. "AdvOut" : "SimpleOutput";
  1375. if (move_reconnect_settings(config, section)) {
  1376. config_remove_value(config, "SimpleOutput", "Reconnect");
  1377. config_remove_value(config, "SimpleOutput", "RetryDelay");
  1378. config_remove_value(config, "SimpleOutput", "MaxRetries");
  1379. config_remove_value(config, "AdvOut", "Reconnect");
  1380. config_remove_value(config, "AdvOut", "RetryDelay");
  1381. config_remove_value(config, "AdvOut", "MaxRetries");
  1382. return true;
  1383. }
  1384. return false;
  1385. }
  1386. static void convert_x264_settings(obs_data_t *data)
  1387. {
  1388. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  1389. if (use_bufsize) {
  1390. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  1391. if (buffer_size == 0)
  1392. obs_data_set_string(data, "rate_control", "CRF");
  1393. }
  1394. }
  1395. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  1396. {
  1397. obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
  1398. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  1399. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  1400. bool modified = false;
  1401. bool cbr = true;
  1402. if (cbr_item) {
  1403. cbr = obs_data_item_get_bool(cbr_item);
  1404. obs_data_item_unset_user_value(cbr_item);
  1405. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  1406. modified = true;
  1407. }
  1408. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  1409. if (!cbr_item)
  1410. obs_data_set_string(data, "rate_control", "CBR");
  1411. else if (!cbr)
  1412. convert_x264_settings(data);
  1413. modified = true;
  1414. }
  1415. if (modified)
  1416. obs_data_save_json_safe(data, file, "tmp", "bak");
  1417. obs_data_item_release(&rc_item);
  1418. obs_data_item_release(&cbr_item);
  1419. obs_data_release(data);
  1420. }
  1421. static void upgrade_settings(void)
  1422. {
  1423. char path[512];
  1424. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  1425. if (pathlen <= 0)
  1426. return;
  1427. if (!os_file_exists(path))
  1428. return;
  1429. os_dir_t *dir = os_opendir(path);
  1430. if (!dir)
  1431. return;
  1432. struct os_dirent *ent = os_readdir(dir);
  1433. while (ent) {
  1434. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  1435. strcmp(ent->d_name, "..") != 0) {
  1436. strcat(path, "/");
  1437. strcat(path, ent->d_name);
  1438. strcat(path, "/basic.ini");
  1439. ConfigFile config;
  1440. int ret;
  1441. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  1442. if (ret == CONFIG_SUCCESS) {
  1443. if (update_ffmpeg_output(config) ||
  1444. update_reconnect(config)) {
  1445. config_save_safe(config, "tmp",
  1446. nullptr);
  1447. }
  1448. }
  1449. if (config) {
  1450. const char *sEnc = config_get_string(config,
  1451. "AdvOut", "Encoder");
  1452. const char *rEnc = config_get_string(config,
  1453. "AdvOut", "RecEncoder");
  1454. /* replace "cbr" option with "rate_control" for
  1455. * each profile's encoder data */
  1456. path[pathlen] = 0;
  1457. strcat(path, "/");
  1458. strcat(path, ent->d_name);
  1459. strcat(path, "/recordEncoder.json");
  1460. convert_14_2_encoder_setting(rEnc, path);
  1461. path[pathlen] = 0;
  1462. strcat(path, "/");
  1463. strcat(path, ent->d_name);
  1464. strcat(path, "/streamEncoder.json");
  1465. convert_14_2_encoder_setting(sEnc, path);
  1466. }
  1467. path[pathlen] = 0;
  1468. }
  1469. ent = os_readdir(dir);
  1470. }
  1471. os_closedir(dir);
  1472. }
  1473. int main(int argc, char *argv[])
  1474. {
  1475. #ifndef _WIN32
  1476. signal(SIGPIPE, SIG_IGN);
  1477. #endif
  1478. #ifdef _WIN32
  1479. SetErrorMode(SEM_FAILCRITICALERRORS);
  1480. load_debug_privilege();
  1481. base_set_crash_handler(main_crash_handler, nullptr);
  1482. #endif
  1483. base_get_log_handler(&def_log_handler, nullptr);
  1484. #if defined(USE_XDG) && defined(IS_UNIX)
  1485. move_to_xdg();
  1486. #endif
  1487. for (int i = 1; i < argc; i++) {
  1488. if (arg_is(argv[i], "--portable", "-p")) {
  1489. portable_mode = true;
  1490. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  1491. log_verbose = true;
  1492. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  1493. opt_always_on_top = true;
  1494. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  1495. unfiltered_log = true;
  1496. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  1497. opt_start_streaming = true;
  1498. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  1499. opt_start_recording = true;
  1500. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  1501. opt_start_replaybuffer = true;
  1502. } else if (arg_is(argv[i], "--collection", nullptr)) {
  1503. if (++i < argc) opt_starting_collection = argv[i];
  1504. } else if (arg_is(argv[i], "--profile", nullptr)) {
  1505. if (++i < argc) opt_starting_profile = argv[i];
  1506. } else if (arg_is(argv[i], "--scene", nullptr)) {
  1507. if (++i < argc) opt_starting_scene = argv[i];
  1508. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  1509. opt_minimize_tray = true;
  1510. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  1511. opt_studio_mode = true;
  1512. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  1513. opt_allow_opengl = true;
  1514. } else if (arg_is(argv[i], "--help", "-h")) {
  1515. std::cout <<
  1516. "--help, -h: Get list of available commands.\n\n" <<
  1517. "--startstreaming: Automatically start streaming.\n" <<
  1518. "--startrecording: Automatically start recording.\n" <<
  1519. "--startreplaybuffer: Start replay buffer.\n\n" <<
  1520. "--collection <string>: Use specific scene collection."
  1521. << "\n" <<
  1522. "--profile <string>: Use specific profile.\n" <<
  1523. "--scene <string>: Start with specific scene.\n\n" <<
  1524. "--studio-mode: Enable studio mode.\n" <<
  1525. "--minimize-to-tray: Minimize to system tray.\n" <<
  1526. "--portable, -p: Use portable mode.\n\n" <<
  1527. "--verbose: Make log more verbose.\n" <<
  1528. "--always-on-top: Start in 'always on top' mode.\n\n" <<
  1529. "--unfiltered_log: Make log unfiltered.\n\n" <<
  1530. "--allow-opengl: Allow OpenGL on Windows.\n\n" <<
  1531. "--version, -V: Get current version.\n";
  1532. exit(0);
  1533. } else if (arg_is(argv[i], "--version", "-V")) {
  1534. std::cout << "OBS Studio - " <<
  1535. App()->GetVersionString() << "\n";
  1536. exit(0);
  1537. }
  1538. }
  1539. #if !OBS_UNIX_STRUCTURE
  1540. if (!portable_mode) {
  1541. portable_mode =
  1542. os_file_exists(BASE_PATH "/portable_mode") ||
  1543. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  1544. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  1545. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  1546. }
  1547. #endif
  1548. upgrade_settings();
  1549. fstream logFile;
  1550. curl_global_init(CURL_GLOBAL_ALL);
  1551. int ret = run_program(logFile, argc, argv);
  1552. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  1553. base_set_log_handler(nullptr, nullptr);
  1554. return ret;
  1555. }