obs-app.cpp 60 KB

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