obs-app.cpp 46 KB

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