obs-app.cpp 47 KB

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