obs-app.cpp 59 KB

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