obs-app.cpp 56 KB

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