obs-app.cpp 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891
  1. /******************************************************************************
  2. Copyright (C) 2023 by Lain 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 <filesystem>
  23. #include <util/bmem.h>
  24. #include <util/dstr.hpp>
  25. #include <util/platform.h>
  26. #include <util/profiler.hpp>
  27. #include <util/cf-parser.h>
  28. #include <obs-config.h>
  29. #include <obs.hpp>
  30. #include <qt-wrappers.hpp>
  31. #include <slider-ignorewheel.hpp>
  32. #include <QDir>
  33. #include <QFile>
  34. #include <QGuiApplication>
  35. #include <QScreen>
  36. #include <QProcess>
  37. #include <QAccessible>
  38. #include "obs-app.hpp"
  39. #include "obs-proxy-style.hpp"
  40. #include "log-viewer.hpp"
  41. #include "volume-control.hpp"
  42. #include "window-basic-main.hpp"
  43. #ifdef __APPLE__
  44. #include "window-permissions.hpp"
  45. #endif
  46. #include "window-basic-settings.hpp"
  47. #include "platform.hpp"
  48. #include <fstream>
  49. #include <curl/curl.h>
  50. #ifdef _WIN32
  51. #include <windows.h>
  52. #include <filesystem>
  53. #include <util/windows/win-version.h>
  54. #else
  55. #include <signal.h>
  56. #include <pthread.h>
  57. #include <sys/types.h>
  58. #include <sys/socket.h>
  59. #include <unistd.h>
  60. #endif
  61. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  62. #include "update/models/branches.hpp"
  63. #endif
  64. #if !defined(_WIN32) && !defined(__APPLE__)
  65. #include <obs-nix-platform.h>
  66. #include <qpa/qplatformnativeinterface.h>
  67. #endif
  68. #include <iostream>
  69. #include "ui-config.h"
  70. using namespace std;
  71. static log_handler_t def_log_handler;
  72. static string currentLogFile;
  73. static string lastLogFile;
  74. static string lastCrashLogFile;
  75. bool portable_mode = false;
  76. bool steam = false;
  77. bool safe_mode = false;
  78. bool disable_3p_plugins = false;
  79. bool unclean_shutdown = false;
  80. bool disable_shutdown_check = false;
  81. static bool multi = false;
  82. static bool log_verbose = false;
  83. static bool unfiltered_log = false;
  84. bool opt_start_streaming = false;
  85. bool opt_start_recording = false;
  86. bool opt_studio_mode = false;
  87. bool opt_start_replaybuffer = false;
  88. bool opt_start_virtualcam = false;
  89. bool opt_minimize_tray = false;
  90. bool opt_allow_opengl = false;
  91. bool opt_always_on_top = false;
  92. bool opt_disable_updater = false;
  93. bool opt_disable_missing_files_check = false;
  94. string opt_starting_collection;
  95. string opt_starting_profile;
  96. string opt_starting_scene;
  97. bool restart = false;
  98. bool restart_safe = false;
  99. QStringList arguments;
  100. QPointer<OBSLogViewer> obsLogViewer;
  101. #ifndef _WIN32
  102. int OBSApp::sigintFd[2];
  103. #endif
  104. // GPU hint exports for AMD/NVIDIA laptops
  105. #ifdef _MSC_VER
  106. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  107. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  108. #endif
  109. QObject *CreateShortcutFilter()
  110. {
  111. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  112. auto mouse_event = [](QMouseEvent &event) {
  113. if (!App()->HotkeysEnabledInFocus() &&
  114. event.button() != Qt::LeftButton)
  115. return true;
  116. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  117. bool pressed = event.type() == QEvent::MouseButtonPress;
  118. switch (event.button()) {
  119. case Qt::NoButton:
  120. case Qt::LeftButton:
  121. case Qt::RightButton:
  122. case Qt::AllButtons:
  123. case Qt::MouseButtonMask:
  124. return false;
  125. case Qt::MiddleButton:
  126. hotkey.key = OBS_KEY_MOUSE3;
  127. break;
  128. #define MAP_BUTTON(i, j) \
  129. case Qt::ExtraButton##i: \
  130. hotkey.key = OBS_KEY_MOUSE##j; \
  131. break;
  132. MAP_BUTTON(1, 4);
  133. MAP_BUTTON(2, 5);
  134. MAP_BUTTON(3, 6);
  135. MAP_BUTTON(4, 7);
  136. MAP_BUTTON(5, 8);
  137. MAP_BUTTON(6, 9);
  138. MAP_BUTTON(7, 10);
  139. MAP_BUTTON(8, 11);
  140. MAP_BUTTON(9, 12);
  141. MAP_BUTTON(10, 13);
  142. MAP_BUTTON(11, 14);
  143. MAP_BUTTON(12, 15);
  144. MAP_BUTTON(13, 16);
  145. MAP_BUTTON(14, 17);
  146. MAP_BUTTON(15, 18);
  147. MAP_BUTTON(16, 19);
  148. MAP_BUTTON(17, 20);
  149. MAP_BUTTON(18, 21);
  150. MAP_BUTTON(19, 22);
  151. MAP_BUTTON(20, 23);
  152. MAP_BUTTON(21, 24);
  153. MAP_BUTTON(22, 25);
  154. MAP_BUTTON(23, 26);
  155. MAP_BUTTON(24, 27);
  156. #undef MAP_BUTTON
  157. }
  158. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  159. event.modifiers());
  160. obs_hotkey_inject_event(hotkey, pressed);
  161. return true;
  162. };
  163. auto key_event = [&](QKeyEvent *event) {
  164. int key = event->key();
  165. bool enabledInFocus = App()->HotkeysEnabledInFocus();
  166. if (key != Qt::Key_Enter && key != Qt::Key_Escape &&
  167. key != Qt::Key_Return && !enabledInFocus)
  168. return true;
  169. QDialog *dialog = qobject_cast<QDialog *>(obj);
  170. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  171. bool pressed = event->type() == QEvent::KeyPress;
  172. switch (key) {
  173. case Qt::Key_Shift:
  174. case Qt::Key_Control:
  175. case Qt::Key_Alt:
  176. case Qt::Key_Meta:
  177. break;
  178. #ifdef __APPLE__
  179. case Qt::Key_CapsLock:
  180. // kVK_CapsLock == 57
  181. hotkey.key = obs_key_from_virtual_key(57);
  182. pressed = true;
  183. break;
  184. #endif
  185. case Qt::Key_Enter:
  186. case Qt::Key_Escape:
  187. case Qt::Key_Return:
  188. if (dialog && pressed)
  189. return false;
  190. if (!enabledInFocus)
  191. return true;
  192. /* Falls through. */
  193. default:
  194. hotkey.key = obs_key_from_virtual_key(
  195. event->nativeVirtualKey());
  196. }
  197. if (event->isAutoRepeat())
  198. return true;
  199. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  200. event->modifiers());
  201. obs_hotkey_inject_event(hotkey, pressed);
  202. return true;
  203. };
  204. switch (event->type()) {
  205. case QEvent::MouseButtonPress:
  206. case QEvent::MouseButtonRelease:
  207. return mouse_event(*static_cast<QMouseEvent *>(event));
  208. /*case QEvent::MouseButtonDblClick:
  209. case QEvent::Wheel:*/
  210. case QEvent::KeyPress:
  211. case QEvent::KeyRelease:
  212. return key_event(static_cast<QKeyEvent *>(event));
  213. default:
  214. return false;
  215. }
  216. });
  217. }
  218. string CurrentTimeString()
  219. {
  220. using namespace std::chrono;
  221. struct tm tstruct;
  222. char buf[80];
  223. auto tp = system_clock::now();
  224. auto now = system_clock::to_time_t(tp);
  225. tstruct = *localtime(&now);
  226. size_t written = strftime(buf, sizeof(buf), "%T", &tstruct);
  227. if (ratio_less<system_clock::period, seconds::period>::value &&
  228. written && (sizeof(buf) - written) > 5) {
  229. auto tp_secs = time_point_cast<seconds>(tp);
  230. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  231. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  232. static_cast<unsigned>(millis));
  233. }
  234. return buf;
  235. }
  236. string CurrentDateTimeString()
  237. {
  238. time_t now = time(0);
  239. struct tm tstruct;
  240. char buf[80];
  241. tstruct = *localtime(&now);
  242. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  243. return buf;
  244. }
  245. static void LogString(fstream &logFile, const char *timeString, char *str,
  246. int log_level)
  247. {
  248. static mutex logfile_mutex;
  249. string msg;
  250. msg += timeString;
  251. msg += str;
  252. logfile_mutex.lock();
  253. logFile << msg << endl;
  254. logfile_mutex.unlock();
  255. if (!!obsLogViewer)
  256. QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine",
  257. Qt::QueuedConnection,
  258. Q_ARG(int, log_level),
  259. Q_ARG(QString, QString(msg.c_str())));
  260. }
  261. static inline void LogStringChunk(fstream &logFile, char *str, int log_level)
  262. {
  263. char *nextLine = str;
  264. string timeString = CurrentTimeString();
  265. timeString += ": ";
  266. while (*nextLine) {
  267. char *nextLine = strchr(str, '\n');
  268. if (!nextLine)
  269. break;
  270. if (nextLine != str && nextLine[-1] == '\r') {
  271. nextLine[-1] = 0;
  272. } else {
  273. nextLine[0] = 0;
  274. }
  275. LogString(logFile, timeString.c_str(), str, log_level);
  276. nextLine++;
  277. str = nextLine;
  278. }
  279. LogString(logFile, timeString.c_str(), str, log_level);
  280. }
  281. #define MAX_REPEATED_LINES 30
  282. #define MAX_CHAR_VARIATION (255 * 3)
  283. static inline int sum_chars(const char *str)
  284. {
  285. int val = 0;
  286. for (; *str != 0; str++)
  287. val += *str;
  288. return val;
  289. }
  290. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  291. const char *output_str)
  292. {
  293. static mutex log_mutex;
  294. static const char *last_msg_ptr = nullptr;
  295. static int last_char_sum = 0;
  296. static int rep_count = 0;
  297. int new_sum = sum_chars(output_str);
  298. lock_guard<mutex> guard(log_mutex);
  299. if (unfiltered_log) {
  300. return false;
  301. }
  302. if (last_msg_ptr == msg) {
  303. int diff = std::abs(new_sum - last_char_sum);
  304. if (diff < MAX_CHAR_VARIATION) {
  305. return (rep_count++ >= MAX_REPEATED_LINES);
  306. }
  307. }
  308. if (rep_count > MAX_REPEATED_LINES) {
  309. logFile << CurrentTimeString()
  310. << ": Last log entry repeated for "
  311. << to_string(rep_count - MAX_REPEATED_LINES)
  312. << " more lines" << endl;
  313. }
  314. last_msg_ptr = msg;
  315. last_char_sum = new_sum;
  316. rep_count = 0;
  317. return false;
  318. }
  319. static void do_log(int log_level, const char *msg, va_list args, void *param)
  320. {
  321. fstream &logFile = *static_cast<fstream *>(param);
  322. char str[8192];
  323. #ifndef _WIN32
  324. va_list args2;
  325. va_copy(args2, args);
  326. #endif
  327. vsnprintf(str, sizeof(str), msg, args);
  328. #ifdef _WIN32
  329. if (IsDebuggerPresent()) {
  330. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  331. if (wNum > 1) {
  332. static wstring wide_buf;
  333. static mutex wide_mutex;
  334. lock_guard<mutex> lock(wide_mutex);
  335. wide_buf.reserve(wNum + 1);
  336. wide_buf.resize(wNum - 1);
  337. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  338. wNum);
  339. wide_buf.push_back('\n');
  340. OutputDebugStringW(wide_buf.c_str());
  341. }
  342. }
  343. #endif
  344. #if !defined(_WIN32) && defined(_DEBUG)
  345. def_log_handler(log_level, msg, args2, nullptr);
  346. #endif
  347. if (log_level <= LOG_INFO || log_verbose) {
  348. #if !defined(_WIN32) && !defined(_DEBUG)
  349. def_log_handler(log_level, msg, args2, nullptr);
  350. #endif
  351. if (!too_many_repeated_entries(logFile, msg, str))
  352. LogStringChunk(logFile, str, log_level);
  353. }
  354. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  355. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  356. __debugbreak();
  357. #endif
  358. #ifndef _WIN32
  359. va_end(args2);
  360. #endif
  361. }
  362. #define DEFAULT_LANG "en-US"
  363. bool OBSApp::InitGlobalConfigDefaults()
  364. {
  365. config_set_default_uint(appConfig, "General", "MaxLogs", 10);
  366. config_set_default_int(appConfig, "General", "InfoIncrement", -1);
  367. config_set_default_string(appConfig, "General", "ProcessPriority",
  368. "Normal");
  369. config_set_default_bool(appConfig, "General", "EnableAutoUpdates",
  370. true);
  371. #if _WIN32
  372. config_set_default_string(appConfig, "Video", "Renderer",
  373. "Direct3D 11");
  374. #else
  375. config_set_default_string(appConfig, "Video", "Renderer", "OpenGL");
  376. #endif
  377. #ifdef _WIN32
  378. config_set_default_bool(appConfig, "Audio", "DisableAudioDucking",
  379. true);
  380. config_set_default_bool(appConfig, "General", "BrowserHWAccel", true);
  381. #endif
  382. #ifdef __APPLE__
  383. config_set_default_bool(appConfig, "General", "BrowserHWAccel", true);
  384. config_set_default_bool(appConfig, "Video", "DisableOSXVSync", true);
  385. config_set_default_bool(appConfig, "Video", "ResetOSXVSyncOnExit",
  386. true);
  387. #endif
  388. return true;
  389. }
  390. bool OBSApp::InitGlobalLocationDefaults()
  391. {
  392. char path[512];
  393. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  394. if (len <= 0) {
  395. OBSErrorBox(NULL, "Unable to get global configuration path.");
  396. return false;
  397. }
  398. config_set_default_string(appConfig, "Locations", "Configuration",
  399. path);
  400. config_set_default_string(appConfig, "Locations", "SceneCollections",
  401. path);
  402. config_set_default_string(appConfig, "Locations", "Profiles", path);
  403. return true;
  404. }
  405. void OBSApp::InitUserConfigDefaults()
  406. {
  407. config_set_default_bool(userConfig, "General", "ConfirmOnExit", true);
  408. config_set_default_string(userConfig, "General", "HotkeyFocusType",
  409. "NeverDisableHotkeys");
  410. config_set_default_bool(userConfig, "BasicWindow", "PreviewEnabled",
  411. true);
  412. config_set_default_bool(userConfig, "BasicWindow", "PreviewProgramMode",
  413. false);
  414. config_set_default_bool(userConfig, "BasicWindow",
  415. "SceneDuplicationMode", true);
  416. config_set_default_bool(userConfig, "BasicWindow", "SwapScenesMode",
  417. true);
  418. config_set_default_bool(userConfig, "BasicWindow", "SnappingEnabled",
  419. true);
  420. config_set_default_bool(userConfig, "BasicWindow", "ScreenSnapping",
  421. true);
  422. config_set_default_bool(userConfig, "BasicWindow", "SourceSnapping",
  423. true);
  424. config_set_default_bool(userConfig, "BasicWindow", "CenterSnapping",
  425. false);
  426. config_set_default_double(userConfig, "BasicWindow", "SnapDistance",
  427. 10.0);
  428. config_set_default_bool(userConfig, "BasicWindow",
  429. "SpacingHelpersEnabled", true);
  430. config_set_default_bool(userConfig, "BasicWindow",
  431. "RecordWhenStreaming", false);
  432. config_set_default_bool(userConfig, "BasicWindow",
  433. "KeepRecordingWhenStreamStops", false);
  434. config_set_default_bool(userConfig, "BasicWindow", "SysTrayEnabled",
  435. true);
  436. config_set_default_bool(userConfig, "BasicWindow", "SysTrayWhenStarted",
  437. false);
  438. config_set_default_bool(userConfig, "BasicWindow", "SaveProjectors",
  439. false);
  440. config_set_default_bool(userConfig, "BasicWindow", "ShowTransitions",
  441. true);
  442. config_set_default_bool(userConfig, "BasicWindow",
  443. "ShowListboxToolbars", true);
  444. config_set_default_bool(userConfig, "BasicWindow", "ShowStatusBar",
  445. true);
  446. config_set_default_bool(userConfig, "BasicWindow", "ShowSourceIcons",
  447. true);
  448. config_set_default_bool(userConfig, "BasicWindow",
  449. "ShowContextToolbars", true);
  450. config_set_default_bool(userConfig, "BasicWindow", "StudioModeLabels",
  451. true);
  452. config_set_default_bool(userConfig, "BasicWindow", "VerticalVolControl",
  453. false);
  454. config_set_default_bool(userConfig, "BasicWindow",
  455. "MultiviewMouseSwitch", true);
  456. config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawNames",
  457. true);
  458. config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawAreas",
  459. true);
  460. config_set_default_bool(userConfig, "BasicWindow",
  461. "MediaControlsCountdownTimer", true);
  462. }
  463. static bool do_mkdir(const char *path)
  464. {
  465. if (os_mkdirs(path) == MKDIR_ERROR) {
  466. OBSErrorBox(NULL, "Failed to create directory %s", path);
  467. return false;
  468. }
  469. return true;
  470. }
  471. static bool MakeUserDirs()
  472. {
  473. char path[512];
  474. if (GetAppConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  475. return false;
  476. if (!do_mkdir(path))
  477. return false;
  478. if (GetAppConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  479. return false;
  480. if (!do_mkdir(path))
  481. return false;
  482. if (GetAppConfigPath(path, sizeof(path), "obs-studio/profiler_data") <=
  483. 0)
  484. return false;
  485. if (!do_mkdir(path))
  486. return false;
  487. #ifdef _WIN32
  488. if (GetAppConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  489. return false;
  490. if (!do_mkdir(path))
  491. return false;
  492. #endif
  493. #ifdef WHATSNEW_ENABLED
  494. if (GetAppConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  495. return false;
  496. if (!do_mkdir(path))
  497. return false;
  498. #endif
  499. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <=
  500. 0)
  501. return false;
  502. if (!do_mkdir(path))
  503. return false;
  504. return true;
  505. }
  506. constexpr std::string_view OBSProfileSubDirectory = "obs-studio/basic/profiles";
  507. constexpr std::string_view OBSScenesSubDirectory = "obs-studio/basic/scenes";
  508. static bool MakeUserProfileDirs()
  509. {
  510. const std::filesystem::path userProfilePath =
  511. App()->userProfilesLocation /
  512. std::filesystem::u8path(OBSProfileSubDirectory);
  513. const std::filesystem::path userScenesPath =
  514. App()->userScenesLocation /
  515. std::filesystem::u8path(OBSScenesSubDirectory);
  516. if (!std::filesystem::exists(userProfilePath)) {
  517. try {
  518. std::filesystem::create_directories(userProfilePath);
  519. } catch (const std::filesystem::filesystem_error &error) {
  520. blog(LOG_ERROR,
  521. "Failed to create user profile directory '%s'\n%s",
  522. userProfilePath.u8string().c_str(), error.what());
  523. return false;
  524. }
  525. }
  526. if (!std::filesystem::exists(userScenesPath)) {
  527. try {
  528. std::filesystem::create_directories(userScenesPath);
  529. } catch (const std::filesystem::filesystem_error &error) {
  530. blog(LOG_ERROR,
  531. "Failed to create user scene collection directory '%s'\n%s",
  532. userScenesPath.u8string().c_str(), error.what());
  533. return false;
  534. }
  535. }
  536. return true;
  537. }
  538. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  539. {
  540. if (!layout)
  541. return false;
  542. if (astrcmpi(layout, "horizontaltop") == 0) {
  543. config_set_int(
  544. userConfig, "BasicWindow", "MultiviewLayout",
  545. static_cast<int>(
  546. MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  547. return true;
  548. }
  549. if (astrcmpi(layout, "horizontalbottom") == 0) {
  550. config_set_int(
  551. userConfig, "BasicWindow", "MultiviewLayout",
  552. static_cast<int>(
  553. MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  554. return true;
  555. }
  556. if (astrcmpi(layout, "verticalleft") == 0) {
  557. config_set_int(
  558. userConfig, "BasicWindow", "MultiviewLayout",
  559. static_cast<int>(
  560. MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  561. return true;
  562. }
  563. if (astrcmpi(layout, "verticalright") == 0) {
  564. config_set_int(
  565. userConfig, "BasicWindow", "MultiviewLayout",
  566. static_cast<int>(
  567. MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  568. return true;
  569. }
  570. return false;
  571. }
  572. bool OBSApp::InitGlobalConfig()
  573. {
  574. char path[512];
  575. int len = GetAppConfigPath(path, sizeof(path), "obs-studio/global.ini");
  576. if (len <= 0) {
  577. return false;
  578. }
  579. int errorcode = appConfig.Open(path, CONFIG_OPEN_ALWAYS);
  580. if (errorcode != CONFIG_SUCCESS) {
  581. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  582. return false;
  583. }
  584. uint32_t lastVersion =
  585. config_get_int(appConfig, "General", "LastVersion");
  586. if (lastVersion < MAKE_SEMANTIC_VERSION(31, 0, 0)) {
  587. bool migratedUserSettings =
  588. config_get_bool(appConfig, "General", "Pre31Migrated");
  589. if (!migratedUserSettings) {
  590. bool migrated = MigrateGlobalSettings();
  591. config_set_bool(appConfig, "General", "Pre31Migrated",
  592. migrated);
  593. config_save_safe(appConfig, "tmp", nullptr);
  594. }
  595. }
  596. InitGlobalConfigDefaults();
  597. InitGlobalLocationDefaults();
  598. if (IsPortableMode()) {
  599. userConfigLocation = std::filesystem::u8path(
  600. config_get_default_string(appConfig, "Locations",
  601. "Configuration"));
  602. userScenesLocation = std::filesystem::u8path(
  603. config_get_default_string(appConfig, "Locations",
  604. "SceneCollections"));
  605. userProfilesLocation = std::filesystem::u8path(
  606. config_get_default_string(appConfig, "Locations",
  607. "Profiles"));
  608. } else {
  609. userConfigLocation = std::filesystem::u8path(config_get_string(
  610. appConfig, "Locations", "Configuration"));
  611. userScenesLocation = std::filesystem::u8path(config_get_string(
  612. appConfig, "Locations", "SceneCollections"));
  613. userProfilesLocation = std::filesystem::u8path(
  614. config_get_string(appConfig, "Locations", "Profiles"));
  615. }
  616. bool userConfigResult = InitUserConfig(userConfigLocation, lastVersion);
  617. return userConfigResult;
  618. }
  619. bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation,
  620. uint32_t lastVersion)
  621. {
  622. bool hasChanges = false;
  623. const std::string userConfigFile =
  624. userConfigLocation.u8string() + "/obs-studio/user.ini";
  625. int errorCode =
  626. userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS);
  627. if (errorCode != CONFIG_SUCCESS) {
  628. OBSErrorBox(nullptr, "Failed to open user.ini: %d", errorCode);
  629. return false;
  630. }
  631. hasChanges = MigrateLegacySettings(lastVersion);
  632. if (!opt_starting_collection.empty()) {
  633. const OBSBasic *basic =
  634. reinterpret_cast<OBSBasic *>(GetMainWindow());
  635. const std::optional<OBSSceneCollection> foundCollection =
  636. basic->GetSceneCollectionByName(
  637. opt_starting_collection);
  638. if (foundCollection) {
  639. config_set_string(userConfig, "Basic",
  640. "SceneCollection",
  641. foundCollection.value().name.c_str());
  642. config_set_string(
  643. userConfig, "Basic", "SceneCollectionFile",
  644. foundCollection.value().fileName.c_str());
  645. hasChanges = true;
  646. }
  647. }
  648. if (!opt_starting_profile.empty()) {
  649. const OBSBasic *basic =
  650. reinterpret_cast<OBSBasic *>(GetMainWindow());
  651. const std::optional<OBSProfile> foundProfile =
  652. basic->GetProfileByName(opt_starting_profile);
  653. if (foundProfile) {
  654. config_set_string(userConfig, "Basic", "Profile",
  655. foundProfile.value().name.c_str());
  656. config_set_string(
  657. userConfig, "Basic", "ProfileDir",
  658. foundProfile.value().directoryName.c_str());
  659. hasChanges = true;
  660. }
  661. }
  662. if (hasChanges) {
  663. config_save_safe(userConfig, "tmp", nullptr);
  664. }
  665. InitUserConfigDefaults();
  666. return true;
  667. }
  668. bool OBSApp::MigrateLegacySettings(const uint32_t lastVersion)
  669. {
  670. bool hasChanges = false;
  671. const uint32_t v19 = MAKE_SEMANTIC_VERSION(19, 0, 0);
  672. const uint32_t v21 = MAKE_SEMANTIC_VERSION(21, 0, 0);
  673. const uint32_t v23 = MAKE_SEMANTIC_VERSION(23, 0, 0);
  674. const uint32_t v24 = MAKE_SEMANTIC_VERSION(24, 0, 0);
  675. const uint32_t v24_1 = MAKE_SEMANTIC_VERSION(24, 1, 0);
  676. const map<uint32_t, string> defaultsMap{{{v19, "Pre19Defaults"},
  677. {v21, "Pre21Defaults"},
  678. {v23, "Pre23Defaults"},
  679. {v24_1, "Pre24.1Defaults"}}};
  680. for (auto &[version, configKey] : defaultsMap) {
  681. if (!config_has_user_value(userConfig, "General",
  682. configKey.c_str())) {
  683. bool useOldDefaults = lastVersion &&
  684. lastVersion < version;
  685. config_set_bool(userConfig, "General",
  686. configKey.c_str(), useOldDefaults);
  687. hasChanges = true;
  688. }
  689. }
  690. if (config_has_user_value(userConfig, "BasicWindow",
  691. "MultiviewLayout")) {
  692. const char *layout = config_get_string(
  693. userConfig, "BasicWindow", "MultiviewLayout");
  694. bool layoutUpdated = UpdatePre22MultiviewLayout(layout);
  695. hasChanges = hasChanges | layoutUpdated;
  696. }
  697. if (lastVersion && lastVersion < v24) {
  698. bool disableHotkeysInFocus = config_get_bool(
  699. userConfig, "General", "DisableHotkeysInFocus");
  700. if (disableHotkeysInFocus) {
  701. config_set_string(userConfig, "General",
  702. "HotkeyFocusType",
  703. "DisableHotkeysInFocus");
  704. }
  705. hasChanges = true;
  706. }
  707. return hasChanges;
  708. }
  709. static constexpr string_view OBSGlobalIniPath = "/obs-studio/global.ini";
  710. static constexpr string_view OBSUserIniPath = "/obs-studio/user.ini";
  711. bool OBSApp::MigrateGlobalSettings()
  712. {
  713. char path[512];
  714. int len = GetAppConfigPath(path, sizeof(path), nullptr);
  715. if (len <= 0) {
  716. OBSErrorBox(nullptr,
  717. "Unable to get global configuration path.");
  718. return false;
  719. }
  720. std::string legacyConfigFileString;
  721. legacyConfigFileString.reserve(strlen(path) + OBSGlobalIniPath.size());
  722. legacyConfigFileString.append(path).append(OBSGlobalIniPath);
  723. const std::filesystem::path legacyGlobalConfigFile =
  724. std::filesystem::u8path(legacyConfigFileString);
  725. std::string configFileString;
  726. configFileString.reserve(strlen(path) + OBSUserIniPath.size());
  727. configFileString.append(path).append(OBSUserIniPath);
  728. const std::filesystem::path userConfigFile =
  729. std::filesystem::u8path(configFileString);
  730. if (std::filesystem::exists(userConfigFile)) {
  731. OBSErrorBox(
  732. nullptr,
  733. "Unable to migrate global configuration - user configuration file already exists.");
  734. return false;
  735. }
  736. std::filesystem::copy(legacyGlobalConfigFile, userConfigFile);
  737. return true;
  738. }
  739. bool OBSApp::InitLocale()
  740. {
  741. ProfileScope("OBSApp::InitLocale");
  742. const char *lang = config_get_string(userConfig, "General", "Language");
  743. bool userLocale =
  744. config_has_user_value(userConfig, "General", "Language");
  745. if (!userLocale || !lang || lang[0] == '\0')
  746. lang = DEFAULT_LANG;
  747. locale = lang;
  748. // set basic default application locale
  749. if (!locale.empty())
  750. QLocale::setDefault(QLocale(
  751. QString::fromStdString(locale).replace('-', '_')));
  752. string englishPath;
  753. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  754. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  755. return false;
  756. }
  757. textLookup = text_lookup_create(englishPath.c_str());
  758. if (!textLookup) {
  759. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  760. englishPath.c_str());
  761. return false;
  762. }
  763. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  764. if (userLocale && defaultLang)
  765. return true;
  766. if (!userLocale && defaultLang) {
  767. for (auto &locale_ : GetPreferredLocales()) {
  768. if (locale_ == lang)
  769. return true;
  770. stringstream file;
  771. file << "locale/" << locale_ << ".ini";
  772. string path;
  773. if (!GetDataFilePath(file.str().c_str(), path))
  774. continue;
  775. if (!text_lookup_add(textLookup, path.c_str()))
  776. continue;
  777. blog(LOG_INFO, "Using preferred locale '%s'",
  778. locale_.c_str());
  779. locale = locale_;
  780. // set application default locale to the new choosen one
  781. if (!locale.empty())
  782. QLocale::setDefault(QLocale(
  783. QString::fromStdString(locale).replace(
  784. '-', '_')));
  785. return true;
  786. }
  787. return true;
  788. }
  789. stringstream file;
  790. file << "locale/" << lang << ".ini";
  791. string path;
  792. if (GetDataFilePath(file.str().c_str(), path)) {
  793. if (!text_lookup_add(textLookup, path.c_str()))
  794. blog(LOG_ERROR, "Failed to add locale file '%s'",
  795. path.c_str());
  796. } else {
  797. blog(LOG_ERROR, "Could not find locale file '%s'",
  798. file.str().c_str());
  799. }
  800. return true;
  801. }
  802. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  803. void ParseBranchesJson(const std::string &jsonString, vector<UpdateBranch> &out,
  804. std::string &error)
  805. {
  806. JsonBranches branches;
  807. try {
  808. nlohmann::json json = nlohmann::json::parse(jsonString);
  809. branches = json.get<JsonBranches>();
  810. } catch (nlohmann::json::exception &e) {
  811. error = e.what();
  812. return;
  813. }
  814. for (const JsonBranch &json_branch : branches) {
  815. #ifdef _WIN32
  816. if (!json_branch.windows)
  817. continue;
  818. #elif defined(__APPLE__)
  819. if (!json_branch.macos)
  820. continue;
  821. #endif
  822. UpdateBranch branch = {
  823. QString::fromStdString(json_branch.name),
  824. QString::fromStdString(json_branch.display_name),
  825. QString::fromStdString(json_branch.description),
  826. json_branch.enabled,
  827. json_branch.visible,
  828. };
  829. out.push_back(branch);
  830. }
  831. }
  832. bool LoadBranchesFile(vector<UpdateBranch> &out)
  833. {
  834. string error;
  835. string branchesText;
  836. BPtr<char> branchesFilePath =
  837. GetAppConfigPathPtr("obs-studio/updates/branches.json");
  838. QFile branchesFile(branchesFilePath.Get());
  839. if (!branchesFile.open(QIODevice::ReadOnly)) {
  840. error = "Opening file failed.";
  841. goto fail;
  842. }
  843. branchesText = branchesFile.readAll();
  844. if (branchesText.empty()) {
  845. error = "File empty.";
  846. goto fail;
  847. }
  848. ParseBranchesJson(branchesText, out, error);
  849. if (error.empty())
  850. return !out.empty();
  851. fail:
  852. blog(LOG_WARNING, "Loading branches from file failed: %s",
  853. error.c_str());
  854. return false;
  855. }
  856. #endif
  857. void OBSApp::SetBranchData(const string &data)
  858. {
  859. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  860. string error;
  861. vector<UpdateBranch> result;
  862. ParseBranchesJson(data, result, error);
  863. if (!error.empty()) {
  864. blog(LOG_WARNING, "Reading branches JSON response failed: %s",
  865. error.c_str());
  866. return;
  867. }
  868. if (!result.empty())
  869. updateBranches = result;
  870. branches_loaded = true;
  871. #else
  872. UNUSED_PARAMETER(data);
  873. #endif
  874. }
  875. std::vector<UpdateBranch> OBSApp::GetBranches()
  876. {
  877. vector<UpdateBranch> out;
  878. /* Always ensure the default branch exists */
  879. out.push_back(UpdateBranch{"stable", "", "", true, true});
  880. #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER)
  881. if (!branches_loaded) {
  882. vector<UpdateBranch> result;
  883. if (LoadBranchesFile(result))
  884. updateBranches = result;
  885. branches_loaded = true;
  886. }
  887. #endif
  888. /* Copy additional branches to result (if any) */
  889. if (!updateBranches.empty())
  890. out.insert(out.end(), updateBranches.begin(),
  891. updateBranches.end());
  892. return out;
  893. }
  894. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  895. : QApplication(argc, argv),
  896. profilerNameStore(store)
  897. {
  898. /* fix float handling */
  899. #if defined(Q_OS_UNIX)
  900. if (!setlocale(LC_NUMERIC, "C"))
  901. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  902. #endif
  903. #ifndef _WIN32
  904. /* Handle SIGINT properly */
  905. socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd);
  906. snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this);
  907. connect(snInt, &QSocketNotifier::activated, this,
  908. &OBSApp::ProcessSigInt);
  909. #else
  910. connect(qApp, &QGuiApplication::commitDataRequest, this,
  911. &OBSApp::commitData);
  912. #endif
  913. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  914. #ifndef __APPLE__
  915. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  916. #endif
  917. setDesktopFileName("com.obsproject.Studio");
  918. }
  919. OBSApp::~OBSApp()
  920. {
  921. #ifdef _WIN32
  922. bool disableAudioDucking =
  923. config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  924. if (disableAudioDucking)
  925. DisableAudioDucking(false);
  926. #else
  927. delete snInt;
  928. close(sigintFd[0]);
  929. close(sigintFd[1]);
  930. #endif
  931. #ifdef __APPLE__
  932. bool vsyncDisabled =
  933. config_get_bool(appConfig, "Video", "DisableOSXVSync");
  934. bool resetVSync =
  935. config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit");
  936. if (vsyncDisabled && resetVSync)
  937. EnableOSXVSync(true);
  938. #endif
  939. os_inhibit_sleep_set_active(sleepInhibitor, false);
  940. os_inhibit_sleep_destroy(sleepInhibitor);
  941. if (libobs_initialized)
  942. obs_shutdown();
  943. }
  944. static void move_basic_to_profiles(void)
  945. {
  946. char path[512];
  947. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  948. return;
  949. }
  950. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  951. if (!std::filesystem::exists(basicPath)) {
  952. return;
  953. }
  954. const std::filesystem::path profilesPath =
  955. App()->userProfilesLocation /
  956. std::filesystem::u8path("obs-studio/basic/profiles");
  957. if (std::filesystem::exists(profilesPath)) {
  958. return;
  959. }
  960. try {
  961. std::filesystem::create_directories(profilesPath);
  962. } catch (const std::filesystem::filesystem_error &error) {
  963. blog(LOG_ERROR,
  964. "Failed to create profiles directory for migration from basic profile\n%s",
  965. error.what());
  966. return;
  967. }
  968. const std::filesystem::path newProfilePath =
  969. profilesPath / std::filesystem::u8path(Str("Untitled"));
  970. for (auto &entry : std::filesystem::directory_iterator(basicPath)) {
  971. if (entry.is_directory()) {
  972. continue;
  973. }
  974. if (entry.path().filename().u8string() == "scenes.json") {
  975. continue;
  976. }
  977. if (!std::filesystem::exists(newProfilePath)) {
  978. try {
  979. std::filesystem::create_directory(
  980. newProfilePath);
  981. } catch (
  982. const std::filesystem::filesystem_error &error) {
  983. blog(LOG_ERROR,
  984. "Failed to create profile directory for 'Untitled'\n%s",
  985. error.what());
  986. return;
  987. }
  988. }
  989. const filesystem::path destinationFile =
  990. newProfilePath / entry.path().filename();
  991. const auto copyOptions =
  992. std::filesystem::copy_options::overwrite_existing;
  993. try {
  994. std::filesystem::copy(entry.path(), destinationFile,
  995. copyOptions);
  996. } catch (const std::filesystem::filesystem_error &error) {
  997. blog(LOG_ERROR,
  998. "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s",
  999. entry.path().filename().u8string().c_str(),
  1000. error.what());
  1001. return;
  1002. }
  1003. }
  1004. }
  1005. static void move_basic_to_scene_collections(void)
  1006. {
  1007. char path[512];
  1008. if (GetAppConfigPath(path, 512, "obs-studio/basic") <= 0) {
  1009. return;
  1010. }
  1011. const std::filesystem::path basicPath = std::filesystem::u8path(path);
  1012. if (!std::filesystem::exists(basicPath)) {
  1013. return;
  1014. }
  1015. const std::filesystem::path sceneCollectionPath =
  1016. App()->userScenesLocation /
  1017. std::filesystem::u8path("obs-studio/basic/scenes");
  1018. if (std::filesystem::exists(sceneCollectionPath)) {
  1019. return;
  1020. }
  1021. try {
  1022. std::filesystem::create_directories(sceneCollectionPath);
  1023. } catch (const std::filesystem::filesystem_error &error) {
  1024. blog(LOG_ERROR,
  1025. "Failed to create scene collection directory for migration from basic scene collection\n%s",
  1026. error.what());
  1027. return;
  1028. }
  1029. const std::filesystem::path sourceFile =
  1030. basicPath / std::filesystem::u8path("scenes.json");
  1031. const std::filesystem::path destinationFile =
  1032. (sceneCollectionPath / std::filesystem::u8path(Str("Untitled")))
  1033. .replace_extension(".json");
  1034. try {
  1035. std::filesystem::rename(sourceFile, destinationFile);
  1036. } catch (const std::filesystem::filesystem_error &error) {
  1037. blog(LOG_ERROR,
  1038. "Failed to rename basic scene collection file:\n%s",
  1039. error.what());
  1040. return;
  1041. }
  1042. }
  1043. void OBSApp::AppInit()
  1044. {
  1045. ProfileScope("OBSApp::AppInit");
  1046. if (!MakeUserDirs())
  1047. throw "Failed to create required user directories";
  1048. if (!InitGlobalConfig())
  1049. throw "Failed to initialize global config";
  1050. if (!InitLocale())
  1051. throw "Failed to load locale";
  1052. if (!InitTheme())
  1053. throw "Failed to load theme";
  1054. config_set_default_string(userConfig, "Basic", "Profile",
  1055. Str("Untitled"));
  1056. config_set_default_string(userConfig, "Basic", "ProfileDir",
  1057. Str("Untitled"));
  1058. config_set_default_string(userConfig, "Basic", "SceneCollection",
  1059. Str("Untitled"));
  1060. config_set_default_string(userConfig, "Basic", "SceneCollectionFile",
  1061. Str("Untitled"));
  1062. config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile",
  1063. true);
  1064. if (!config_has_user_value(userConfig, "Basic", "Profile")) {
  1065. config_set_string(userConfig, "Basic", "Profile",
  1066. Str("Untitled"));
  1067. config_set_string(userConfig, "Basic", "ProfileDir",
  1068. Str("Untitled"));
  1069. }
  1070. if (!config_has_user_value(userConfig, "Basic", "SceneCollection")) {
  1071. config_set_string(userConfig, "Basic", "SceneCollection",
  1072. Str("Untitled"));
  1073. config_set_string(userConfig, "Basic", "SceneCollectionFile",
  1074. Str("Untitled"));
  1075. }
  1076. #ifdef _WIN32
  1077. bool disableAudioDucking =
  1078. config_get_bool(appConfig, "Audio", "DisableAudioDucking");
  1079. if (disableAudioDucking)
  1080. DisableAudioDucking(true);
  1081. #endif
  1082. #ifdef __APPLE__
  1083. if (config_get_bool(appConfig, "Video", "DisableOSXVSync"))
  1084. EnableOSXVSync(false);
  1085. #endif
  1086. UpdateHotkeyFocusSetting(false);
  1087. move_basic_to_profiles();
  1088. move_basic_to_scene_collections();
  1089. if (!MakeUserProfileDirs())
  1090. throw "Failed to create profile directories";
  1091. }
  1092. const char *OBSApp::GetRenderModule() const
  1093. {
  1094. const char *renderer =
  1095. config_get_string(appConfig, "Video", "Renderer");
  1096. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1097. }
  1098. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1099. {
  1100. char path[512];
  1101. if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <=
  1102. 0)
  1103. return false;
  1104. return obs_startup(locale, path, store);
  1105. }
  1106. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1107. {
  1108. obs_hotkey_enable_background_press(
  1109. (inFocus && enableHotkeysInFocus) ||
  1110. (!inFocus && enableHotkeysOutOfFocus));
  1111. }
  1112. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1113. {
  1114. enableHotkeysInFocus = true;
  1115. enableHotkeysOutOfFocus = true;
  1116. const char *hotkeyFocusType =
  1117. config_get_string(userConfig, "General", "HotkeyFocusType");
  1118. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1119. enableHotkeysInFocus = false;
  1120. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1121. enableHotkeysOutOfFocus = false;
  1122. }
  1123. if (resetState)
  1124. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1125. }
  1126. void OBSApp::DisableHotkeys()
  1127. {
  1128. enableHotkeysInFocus = false;
  1129. enableHotkeysOutOfFocus = false;
  1130. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1131. }
  1132. Q_DECLARE_METATYPE(VoidFunc)
  1133. void OBSApp::Exec(VoidFunc func)
  1134. {
  1135. func();
  1136. }
  1137. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  1138. {
  1139. auto doTask = [=]() {
  1140. /* to get clang-format to behave */
  1141. task(param);
  1142. };
  1143. QMetaObject::invokeMethod(App(), "Exec",
  1144. wait ? WaitConnection() : Qt::AutoConnection,
  1145. Q_ARG(VoidFunc, doTask));
  1146. }
  1147. bool OBSApp::OBSInit()
  1148. {
  1149. ProfileScope("OBSApp::OBSInit");
  1150. qRegisterMetaType<VoidFunc>("VoidFunc");
  1151. #if !defined(_WIN32) && !defined(__APPLE__)
  1152. if (QApplication::platformName() == "xcb") {
  1153. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  1154. blog(LOG_INFO, "Using EGL/X11");
  1155. }
  1156. #ifdef ENABLE_WAYLAND
  1157. if (QApplication::platformName().contains("wayland")) {
  1158. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  1159. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1160. blog(LOG_INFO, "Platform: Wayland");
  1161. }
  1162. #endif
  1163. QPlatformNativeInterface *native =
  1164. QGuiApplication::platformNativeInterface();
  1165. obs_set_nix_platform_display(
  1166. native->nativeResourceForIntegration("display"));
  1167. #endif
  1168. #ifdef __APPLE__
  1169. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1170. #endif
  1171. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1172. return false;
  1173. libobs_initialized = true;
  1174. obs_set_ui_task_handler(ui_task_handler);
  1175. #if defined(_WIN32) || defined(__APPLE__)
  1176. bool browserHWAccel =
  1177. config_get_bool(userConfig, "General", "BrowserHWAccel");
  1178. OBSDataAutoRelease settings = obs_data_create();
  1179. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1180. obs_apply_private_data(settings);
  1181. blog(LOG_INFO, "Current Date/Time: %s",
  1182. CurrentDateTimeString().c_str());
  1183. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1184. browserHWAccel ? "true" : "false");
  1185. #endif
  1186. #ifdef _WIN32
  1187. bool hideFromCapture = config_get_bool(userConfig, "BasicWindow",
  1188. "HideOBSWindowsFromCapture");
  1189. blog(LOG_INFO, "Hide OBS windows from screen capture: %s",
  1190. hideFromCapture ? "true" : "false");
  1191. #endif
  1192. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(),
  1193. QT_VERSION_STR);
  1194. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1195. if (safe_mode) {
  1196. blog(LOG_WARNING, "Safe Mode enabled.");
  1197. } else if (disable_3p_plugins) {
  1198. blog(LOG_WARNING, "Third-party plugins disabled.");
  1199. }
  1200. setQuitOnLastWindowClosed(false);
  1201. mainWindow = new OBSBasic();
  1202. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1203. connect(mainWindow, &OBSBasic::destroyed, this, &OBSApp::quit);
  1204. mainWindow->OBSInit();
  1205. connect(this, &QGuiApplication::applicationStateChanged,
  1206. [this](Qt::ApplicationState state) {
  1207. ResetHotkeyState(state == Qt::ApplicationActive);
  1208. });
  1209. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1210. return true;
  1211. }
  1212. string OBSApp::GetVersionString(bool platform) const
  1213. {
  1214. stringstream ver;
  1215. #ifdef HAVE_OBSCONFIG_H
  1216. ver << obs_get_version_string();
  1217. #else
  1218. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1219. << LIBOBS_API_PATCH_VER;
  1220. #endif
  1221. if (platform) {
  1222. ver << " (";
  1223. #ifdef _WIN32
  1224. if (sizeof(void *) == 8)
  1225. ver << "64-bit, ";
  1226. else
  1227. ver << "32-bit, ";
  1228. ver << "windows)";
  1229. #elif __APPLE__
  1230. ver << "mac)";
  1231. #elif __OpenBSD__
  1232. ver << "openbsd)";
  1233. #elif __FreeBSD__
  1234. ver << "freebsd)";
  1235. #else /* assume linux for the time being */
  1236. ver << "linux)";
  1237. #endif
  1238. }
  1239. return ver.str();
  1240. }
  1241. bool OBSApp::IsPortableMode()
  1242. {
  1243. return portable_mode;
  1244. }
  1245. bool OBSApp::IsUpdaterDisabled()
  1246. {
  1247. return opt_disable_updater;
  1248. }
  1249. bool OBSApp::IsMissingFilesCheckDisabled()
  1250. {
  1251. return opt_disable_missing_files_check;
  1252. }
  1253. #ifdef __APPLE__
  1254. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1255. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1256. #elif _WIN32
  1257. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1258. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1259. #else
  1260. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1261. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1262. #endif
  1263. const char *OBSApp::InputAudioSource() const
  1264. {
  1265. return INPUT_AUDIO_SOURCE;
  1266. }
  1267. const char *OBSApp::OutputAudioSource() const
  1268. {
  1269. return OUTPUT_AUDIO_SOURCE;
  1270. }
  1271. const char *OBSApp::GetLastLog() const
  1272. {
  1273. return lastLogFile.c_str();
  1274. }
  1275. const char *OBSApp::GetCurrentLog() const
  1276. {
  1277. return currentLogFile.c_str();
  1278. }
  1279. const char *OBSApp::GetLastCrashLog() const
  1280. {
  1281. return lastCrashLogFile.c_str();
  1282. }
  1283. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1284. {
  1285. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1286. if (cb(lookupVal, out))
  1287. return true;
  1288. }
  1289. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1290. }
  1291. // Global handler to receive all QEvent::Show events so we can apply
  1292. // display affinity on any newly created windows and dialogs without
  1293. // caring where they are coming from (e.g. plugins).
  1294. bool OBSApp::notify(QObject *receiver, QEvent *e)
  1295. {
  1296. QWidget *w;
  1297. QWindow *window;
  1298. int windowType;
  1299. if (!receiver->isWidgetType())
  1300. goto skip;
  1301. if (e->type() != QEvent::Show)
  1302. goto skip;
  1303. w = qobject_cast<QWidget *>(receiver);
  1304. if (!w->isWindow())
  1305. goto skip;
  1306. window = w->windowHandle();
  1307. if (!window)
  1308. goto skip;
  1309. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  1310. if (windowType == Qt::WindowType::Dialog ||
  1311. windowType == Qt::WindowType::Window ||
  1312. windowType == Qt::WindowType::Tool) {
  1313. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1314. if (main)
  1315. main->SetDisplayAffinity(window);
  1316. }
  1317. skip:
  1318. return QApplication::notify(receiver, e);
  1319. }
  1320. QString OBSTranslator::translate(const char *, const char *sourceText,
  1321. const char *, int) const
  1322. {
  1323. const char *out = nullptr;
  1324. QString str(sourceText);
  1325. str.replace(" ", "");
  1326. if (!App()->TranslateString(QT_TO_UTF8(str), &out))
  1327. return QString(sourceText);
  1328. return QT_UTF8(out);
  1329. }
  1330. static bool get_token(lexer *lex, string &str, base_token_type type)
  1331. {
  1332. base_token token;
  1333. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1334. return false;
  1335. if (token.type != type)
  1336. return false;
  1337. str.assign(token.text.array, token.text.len);
  1338. return true;
  1339. }
  1340. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1341. {
  1342. base_token token;
  1343. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1344. return false;
  1345. if (token.type != type)
  1346. return false;
  1347. return strref_cmp(&token.text, str) == 0;
  1348. }
  1349. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1350. {
  1351. BaseLexer lex;
  1352. string year, month, day, hour, minute, second;
  1353. lexer_start(lex, name);
  1354. if (has_prefix) {
  1355. string temp;
  1356. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1357. return 0;
  1358. }
  1359. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1360. return 0;
  1361. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1362. return 0;
  1363. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1364. return 0;
  1365. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1366. return 0;
  1367. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1368. return 0;
  1369. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1370. return 0;
  1371. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1372. return 0;
  1373. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1374. return 0;
  1375. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1376. return 0;
  1377. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1378. return 0;
  1379. stringstream timestring;
  1380. timestring << year << month << day << hour << minute << second;
  1381. return std::stoull(timestring.str());
  1382. }
  1383. static void delete_oldest_file(bool has_prefix, const char *location)
  1384. {
  1385. BPtr<char> logDir(GetAppConfigPathPtr(location));
  1386. string oldestLog;
  1387. uint64_t oldest_ts = (uint64_t)-1;
  1388. struct os_dirent *entry;
  1389. unsigned int maxLogs = (unsigned int)config_get_uint(
  1390. App()->GetUserConfig(), "General", "MaxLogs");
  1391. os_dir_t *dir = os_opendir(logDir);
  1392. if (dir) {
  1393. unsigned int count = 0;
  1394. while ((entry = os_readdir(dir)) != NULL) {
  1395. if (entry->directory || *entry->d_name == '.')
  1396. continue;
  1397. uint64_t ts =
  1398. convert_log_name(has_prefix, entry->d_name);
  1399. if (ts) {
  1400. if (ts < oldest_ts) {
  1401. oldestLog = entry->d_name;
  1402. oldest_ts = ts;
  1403. }
  1404. count++;
  1405. }
  1406. }
  1407. os_closedir(dir);
  1408. if (count > maxLogs) {
  1409. stringstream delPath;
  1410. delPath << logDir << "/" << oldestLog;
  1411. os_unlink(delPath.str().c_str());
  1412. }
  1413. }
  1414. }
  1415. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1416. std::string &last)
  1417. {
  1418. BPtr<char> logDir(GetAppConfigPathPtr(subdir_to_use));
  1419. struct os_dirent *entry;
  1420. os_dir_t *dir = os_opendir(logDir);
  1421. uint64_t highest_ts = 0;
  1422. if (dir) {
  1423. while ((entry = os_readdir(dir)) != NULL) {
  1424. if (entry->directory || *entry->d_name == '.')
  1425. continue;
  1426. uint64_t ts =
  1427. convert_log_name(has_prefix, entry->d_name);
  1428. if (ts > highest_ts) {
  1429. last = entry->d_name;
  1430. highest_ts = ts;
  1431. }
  1432. }
  1433. os_closedir(dir);
  1434. }
  1435. }
  1436. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1437. {
  1438. time_t now = time(0);
  1439. char file[256] = {};
  1440. struct tm *cur_time;
  1441. cur_time = localtime(&now);
  1442. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1443. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1444. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1445. cur_time->tm_min, cur_time->tm_sec, extension);
  1446. return string(file);
  1447. }
  1448. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1449. const char *format)
  1450. {
  1451. BPtr<char> filename =
  1452. os_generate_formatted_filename(extension, !noSpace, format);
  1453. return string(filename);
  1454. }
  1455. static void FindBestFilename(string &strPath, bool noSpace)
  1456. {
  1457. int num = 2;
  1458. if (!os_file_exists(strPath.c_str()))
  1459. return;
  1460. const char *ext = strrchr(strPath.c_str(), '.');
  1461. if (!ext)
  1462. return;
  1463. int extStart = int(ext - strPath.c_str());
  1464. for (;;) {
  1465. string testPath = strPath;
  1466. string numStr;
  1467. numStr = noSpace ? "_" : " (";
  1468. numStr += to_string(num++);
  1469. if (!noSpace)
  1470. numStr += ")";
  1471. testPath.insert(extStart, numStr);
  1472. if (!os_file_exists(testPath.c_str())) {
  1473. strPath = testPath;
  1474. break;
  1475. }
  1476. }
  1477. }
  1478. static void ensure_directory_exists(string &path)
  1479. {
  1480. replace(path.begin(), path.end(), '\\', '/');
  1481. size_t last = path.rfind('/');
  1482. if (last == string::npos)
  1483. return;
  1484. string directory = path.substr(0, last);
  1485. os_mkdirs(directory.c_str());
  1486. }
  1487. static void remove_reserved_file_characters(string &s)
  1488. {
  1489. replace(s.begin(), s.end(), '\\', '/');
  1490. replace(s.begin(), s.end(), '*', '_');
  1491. replace(s.begin(), s.end(), '?', '_');
  1492. replace(s.begin(), s.end(), '"', '_');
  1493. replace(s.begin(), s.end(), '|', '_');
  1494. replace(s.begin(), s.end(), ':', '_');
  1495. replace(s.begin(), s.end(), '>', '_');
  1496. replace(s.begin(), s.end(), '<', '_');
  1497. }
  1498. string GetFormatString(const char *format, const char *prefix,
  1499. const char *suffix)
  1500. {
  1501. string f;
  1502. f = format;
  1503. if (prefix && *prefix) {
  1504. string str_prefix = prefix;
  1505. if (str_prefix.back() != ' ')
  1506. str_prefix += " ";
  1507. size_t insert_pos = 0;
  1508. size_t tmp;
  1509. tmp = f.find_last_of('/');
  1510. if (tmp != string::npos && tmp > insert_pos)
  1511. insert_pos = tmp + 1;
  1512. tmp = f.find_last_of('\\');
  1513. if (tmp != string::npos && tmp > insert_pos)
  1514. insert_pos = tmp + 1;
  1515. f.insert(insert_pos, str_prefix);
  1516. }
  1517. if (suffix && *suffix) {
  1518. if (*suffix != ' ')
  1519. f += " ";
  1520. f += suffix;
  1521. }
  1522. remove_reserved_file_characters(f);
  1523. return f;
  1524. }
  1525. string GetFormatExt(const char *container)
  1526. {
  1527. string ext = container;
  1528. if (ext == "fragmented_mp4")
  1529. ext = "mp4";
  1530. if (ext == "hybrid_mp4")
  1531. ext = "mp4";
  1532. else if (ext == "fragmented_mov")
  1533. ext = "mov";
  1534. else if (ext == "hls")
  1535. ext = "m3u8";
  1536. else if (ext == "mpegts")
  1537. ext = "ts";
  1538. return ext;
  1539. }
  1540. string GetOutputFilename(const char *path, const char *container, bool noSpace,
  1541. bool overwrite, const char *format)
  1542. {
  1543. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1544. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1545. if (!dir) {
  1546. if (main->isVisible())
  1547. OBSMessageBox::warning(main,
  1548. QTStr("Output.BadPath.Title"),
  1549. QTStr("Output.BadPath.Text"));
  1550. else
  1551. main->SysTrayNotify(QTStr("Output.BadPath.Text"),
  1552. QSystemTrayIcon::Warning);
  1553. return "";
  1554. }
  1555. os_closedir(dir);
  1556. string strPath;
  1557. strPath += path;
  1558. char lastChar = strPath.back();
  1559. if (lastChar != '/' && lastChar != '\\')
  1560. strPath += "/";
  1561. string ext = GetFormatExt(container);
  1562. strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format);
  1563. ensure_directory_exists(strPath);
  1564. if (!overwrite)
  1565. FindBestFilename(strPath, noSpace);
  1566. return strPath;
  1567. }
  1568. vector<pair<string, string>> GetLocaleNames()
  1569. {
  1570. string path;
  1571. if (!GetDataFilePath("locale.ini", path))
  1572. throw "Could not find locale.ini path";
  1573. ConfigFile ini;
  1574. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1575. throw "Could not open locale.ini";
  1576. size_t sections = config_num_sections(ini);
  1577. vector<pair<string, string>> names;
  1578. names.reserve(sections);
  1579. for (size_t i = 0; i < sections; i++) {
  1580. const char *tag = config_get_section(ini, i);
  1581. const char *name = config_get_string(ini, tag, "Name");
  1582. names.emplace_back(tag, name);
  1583. }
  1584. return names;
  1585. }
  1586. static void create_log_file(fstream &logFile)
  1587. {
  1588. stringstream dst;
  1589. get_last_log(false, "obs-studio/logs", lastLogFile);
  1590. #ifdef _WIN32
  1591. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1592. #endif
  1593. currentLogFile = GenerateTimeDateFilename("txt");
  1594. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1595. BPtr<char> path(GetAppConfigPathPtr(dst.str().c_str()));
  1596. #ifdef _WIN32
  1597. BPtr<wchar_t> wpath;
  1598. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1599. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1600. #else
  1601. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1602. #endif
  1603. if (logFile.is_open()) {
  1604. delete_oldest_file(false, "obs-studio/logs");
  1605. base_set_log_handler(do_log, &logFile);
  1606. } else {
  1607. blog(LOG_ERROR, "Failed to open log file");
  1608. }
  1609. }
  1610. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1611. profiler_name_store_free(store);
  1612. };
  1613. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1614. decltype(ProfilerNameStoreRelease)>;
  1615. ProfilerNameStore CreateNameStore()
  1616. {
  1617. return ProfilerNameStore{profiler_name_store_create(),
  1618. ProfilerNameStoreRelease};
  1619. }
  1620. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1621. profile_snapshot_free(snap);
  1622. };
  1623. using ProfilerSnapshot =
  1624. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1625. ProfilerSnapshot GetSnapshot()
  1626. {
  1627. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1628. }
  1629. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1630. {
  1631. if (currentLogFile.empty())
  1632. return;
  1633. auto pos = currentLogFile.rfind('.');
  1634. if (pos == currentLogFile.npos)
  1635. return;
  1636. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1637. ostringstream dst;
  1638. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1639. dst.write(currentLogFile.c_str(), pos);
  1640. dst.write(LITERAL_SIZE(".csv.gz"));
  1641. #undef LITERAL_SIZE
  1642. BPtr<char> path = GetAppConfigPathPtr(dst.str().c_str());
  1643. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1644. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1645. static_cast<const char *>(path));
  1646. }
  1647. static auto ProfilerFree = [](void *) {
  1648. profiler_stop();
  1649. auto snap = GetSnapshot();
  1650. profiler_print(snap.get());
  1651. profiler_print_time_between_calls(snap.get());
  1652. SaveProfilerData(snap);
  1653. profiler_free();
  1654. };
  1655. QAccessibleInterface *accessibleFactory(const QString &classname,
  1656. QObject *object)
  1657. {
  1658. if (classname == QLatin1String("VolumeSlider") && object &&
  1659. object->isWidgetType())
  1660. return new VolumeAccessibleInterface(
  1661. static_cast<QWidget *>(object));
  1662. return nullptr;
  1663. }
  1664. static const char *run_program_init = "run_program_init";
  1665. static int run_program(fstream &logFile, int argc, char *argv[])
  1666. {
  1667. int ret = -1;
  1668. auto profilerNameStore = CreateNameStore();
  1669. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1670. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1671. profiler_start();
  1672. profile_register_root(run_program_init, 0);
  1673. ScopeProfiler prof{run_program_init};
  1674. #ifdef _WIN32
  1675. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
  1676. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1677. #endif
  1678. QCoreApplication::addLibraryPath(".");
  1679. #if __APPLE__
  1680. InstallNSApplicationSubclass();
  1681. InstallNSThreadLocks();
  1682. if (!isInBundle()) {
  1683. blog(LOG_ERROR,
  1684. "OBS cannot be run as a standalone binary on macOS. Run the Application bundle instead.");
  1685. return ret;
  1686. }
  1687. #endif
  1688. #if !defined(_WIN32) && !defined(__APPLE__)
  1689. /* NOTE: Users blindly set this, but this theme is incompatble with Qt6 and
  1690. * crashes loading saved geometry. Just turn off this theme and let users complain OBS
  1691. * looks ugly instead of crashing. */
  1692. const char *platform_theme = getenv("QT_QPA_PLATFORMTHEME");
  1693. if (platform_theme && strcmp(platform_theme, "qt5ct") == 0)
  1694. unsetenv("QT_QPA_PLATFORMTHEME");
  1695. #endif
  1696. /* NOTE: This disables an optimisation in Qt that attempts to determine if
  1697. * any "siblings" intersect with a widget when determining the approximate
  1698. * visible/unobscured area. However, by Qt's own admission this is slow
  1699. * and in the case of OBS it significantly slows down lists with many
  1700. * elements (e.g. Hotkeys) and it is actually faster to disable it. */
  1701. qputenv("QT_NO_SUBTRACTOPAQUESIBLINGS", "1");
  1702. OBSApp program(argc, argv, profilerNameStore.get());
  1703. try {
  1704. QAccessible::installFactory(accessibleFactory);
  1705. QFontDatabase::addApplicationFont(
  1706. ":/fonts/OpenSans-Regular.ttf");
  1707. QFontDatabase::addApplicationFont(":/fonts/OpenSans-Bold.ttf");
  1708. QFontDatabase::addApplicationFont(
  1709. ":/fonts/OpenSans-Italic.ttf");
  1710. bool created_log = false;
  1711. program.AppInit();
  1712. delete_oldest_file(false, "obs-studio/profiler_data");
  1713. OBSTranslator translator;
  1714. program.installTranslator(&translator);
  1715. /* --------------------------------------- */
  1716. /* check and warn if already running */
  1717. bool cancel_launch = false;
  1718. bool already_running = false;
  1719. #ifdef _WIN32
  1720. RunOnceMutex rom =
  1721. #endif
  1722. CheckIfAlreadyRunning(already_running);
  1723. if (!already_running) {
  1724. goto run;
  1725. }
  1726. if (!multi) {
  1727. QMessageBox mb(QMessageBox::Question,
  1728. QTStr("AlreadyRunning.Title"),
  1729. QTStr("AlreadyRunning.Text"));
  1730. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"),
  1731. QMessageBox::YesRole);
  1732. QPushButton *cancelButton = mb.addButton(
  1733. QTStr("Cancel"), QMessageBox::NoRole);
  1734. mb.setDefaultButton(cancelButton);
  1735. mb.exec();
  1736. cancel_launch = mb.clickedButton() == cancelButton;
  1737. }
  1738. if (cancel_launch)
  1739. return 0;
  1740. if (!created_log) {
  1741. create_log_file(logFile);
  1742. created_log = true;
  1743. }
  1744. if (multi) {
  1745. blog(LOG_INFO, "User enabled --multi flag and is now "
  1746. "running multiple instances of OBS.");
  1747. } else {
  1748. blog(LOG_WARNING, "================================");
  1749. blog(LOG_WARNING, "Warning: OBS is already running!");
  1750. blog(LOG_WARNING, "================================");
  1751. blog(LOG_WARNING, "User is now running multiple "
  1752. "instances of OBS!");
  1753. /* Clear unclean_shutdown flag as multiple instances
  1754. * running from the same config will lead to a
  1755. * false-positive detection.*/
  1756. unclean_shutdown = false;
  1757. }
  1758. /* --------------------------------------- */
  1759. run:
  1760. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1761. // Mounted by termina during chromeOS linux container startup
  1762. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1763. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1764. if (crosDir) {
  1765. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1766. QMessageBox mb(QMessageBox::Critical,
  1767. QTStr("ChromeOS.Title"),
  1768. QTStr("ChromeOS.Text"), buttons,
  1769. nullptr);
  1770. mb.exec();
  1771. return 0;
  1772. }
  1773. #endif
  1774. if (!created_log)
  1775. create_log_file(logFile);
  1776. if (unclean_shutdown) {
  1777. blog(LOG_WARNING,
  1778. "[Safe Mode] Unclean shutdown detected!");
  1779. }
  1780. if (unclean_shutdown && !safe_mode) {
  1781. QMessageBox mb(QMessageBox::Warning,
  1782. QTStr("AutoSafeMode.Title"),
  1783. QTStr("AutoSafeMode.Text"));
  1784. QPushButton *launchSafeButton =
  1785. mb.addButton(QTStr("AutoSafeMode.LaunchSafe"),
  1786. QMessageBox::AcceptRole);
  1787. QPushButton *launchNormalButton =
  1788. mb.addButton(QTStr("AutoSafeMode.LaunchNormal"),
  1789. QMessageBox::RejectRole);
  1790. mb.setDefaultButton(launchNormalButton);
  1791. mb.exec();
  1792. safe_mode = mb.clickedButton() == launchSafeButton;
  1793. if (safe_mode) {
  1794. blog(LOG_INFO,
  1795. "[Safe Mode] User has launched in Safe Mode.");
  1796. } else {
  1797. blog(LOG_WARNING,
  1798. "[Safe Mode] User elected to launch normally.");
  1799. }
  1800. }
  1801. qInstallMessageHandler([](QtMsgType type,
  1802. const QMessageLogContext &,
  1803. const QString &message) {
  1804. switch (type) {
  1805. #ifdef _DEBUG
  1806. case QtDebugMsg:
  1807. blog(LOG_DEBUG, "%s", QT_TO_UTF8(message));
  1808. break;
  1809. case QtInfoMsg:
  1810. blog(LOG_INFO, "%s", QT_TO_UTF8(message));
  1811. break;
  1812. #else
  1813. case QtDebugMsg:
  1814. case QtInfoMsg:
  1815. break;
  1816. #endif
  1817. case QtWarningMsg:
  1818. blog(LOG_WARNING, "%s", QT_TO_UTF8(message));
  1819. break;
  1820. case QtCriticalMsg:
  1821. case QtFatalMsg:
  1822. blog(LOG_ERROR, "%s", QT_TO_UTF8(message));
  1823. break;
  1824. }
  1825. });
  1826. #ifdef __APPLE__
  1827. MacPermissionStatus audio_permission =
  1828. CheckPermission(kAudioDeviceAccess);
  1829. MacPermissionStatus video_permission =
  1830. CheckPermission(kVideoDeviceAccess);
  1831. MacPermissionStatus accessibility_permission =
  1832. CheckPermission(kAccessibility);
  1833. MacPermissionStatus screen_permission =
  1834. CheckPermission(kScreenCapture);
  1835. int permissionsDialogLastShown =
  1836. config_get_int(App()->GetAppConfig(), "General",
  1837. "MacOSPermissionsDialogLastShown");
  1838. if (permissionsDialogLastShown <
  1839. MACOS_PERMISSIONS_DIALOG_VERSION) {
  1840. OBSPermissions check(nullptr, screen_permission,
  1841. video_permission, audio_permission,
  1842. accessibility_permission);
  1843. check.exec();
  1844. }
  1845. #endif
  1846. #ifdef _WIN32
  1847. if (IsRunningOnWine()) {
  1848. QMessageBox mb(QMessageBox::Question,
  1849. QTStr("Wine.Title"), QTStr("Wine.Text"));
  1850. mb.setTextFormat(Qt::RichText);
  1851. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"),
  1852. QMessageBox::AcceptRole);
  1853. QPushButton *closeButton =
  1854. mb.addButton(QMessageBox::Close);
  1855. mb.setDefaultButton(closeButton);
  1856. mb.exec();
  1857. if (mb.clickedButton() == closeButton)
  1858. return 0;
  1859. }
  1860. #endif
  1861. if (argc > 1) {
  1862. stringstream stor;
  1863. stor << argv[1];
  1864. for (int i = 2; i < argc; ++i) {
  1865. stor << " " << argv[i];
  1866. }
  1867. blog(LOG_INFO, "Command Line Arguments: %s",
  1868. stor.str().c_str());
  1869. }
  1870. if (!program.OBSInit())
  1871. return 0;
  1872. prof.Stop();
  1873. ret = program.exec();
  1874. } catch (const char *error) {
  1875. blog(LOG_ERROR, "%s", error);
  1876. OBSErrorBox(nullptr, "%s", error);
  1877. }
  1878. if (restart || restart_safe) {
  1879. arguments = qApp->arguments();
  1880. if (restart_safe) {
  1881. arguments.append("--safe-mode");
  1882. } else {
  1883. arguments.removeAll("--safe-mode");
  1884. }
  1885. }
  1886. return ret;
  1887. }
  1888. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1889. #ifdef _WIN32
  1890. #define CRASH_MESSAGE \
  1891. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1892. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1893. static void main_crash_handler(const char *format, va_list args,
  1894. void * /* param */)
  1895. {
  1896. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1897. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1898. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1899. string crashFilePath = "obs-studio/crashes";
  1900. delete_oldest_file(true, crashFilePath.c_str());
  1901. string name = crashFilePath + "/";
  1902. name += "Crash " + GenerateTimeDateFilename("txt");
  1903. BPtr<char> path(GetAppConfigPathPtr(name.c_str()));
  1904. fstream file;
  1905. #ifdef _WIN32
  1906. BPtr<wchar_t> wpath;
  1907. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1908. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1909. ios_base::binary);
  1910. #else
  1911. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1912. ios_base::binary);
  1913. #endif
  1914. file << text;
  1915. file.close();
  1916. string pathString(path.Get());
  1917. #ifdef _WIN32
  1918. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1919. #endif
  1920. string absolutePath =
  1921. canonical(filesystem::path(pathString)).u8string();
  1922. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1923. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1924. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
  1925. absolutePath.c_str());
  1926. string finalMessage =
  1927. string(message_buffer.get(), message_buffer.get() + size);
  1928. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
  1929. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1930. if (ret == IDYES) {
  1931. size_t len = strlen(text);
  1932. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1933. memcpy(GlobalLock(mem), text, len);
  1934. GlobalUnlock(mem);
  1935. OpenClipboard(0);
  1936. EmptyClipboard();
  1937. SetClipboardData(CF_TEXT, mem);
  1938. CloseClipboard();
  1939. }
  1940. exit(-1);
  1941. }
  1942. static void load_debug_privilege(void)
  1943. {
  1944. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1945. TOKEN_PRIVILEGES tp;
  1946. HANDLE token;
  1947. LUID val;
  1948. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1949. return;
  1950. }
  1951. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1952. tp.PrivilegeCount = 1;
  1953. tp.Privileges[0].Luid = val;
  1954. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1955. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1956. NULL);
  1957. }
  1958. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1959. tp.PrivilegeCount = 1;
  1960. tp.Privileges[0].Luid = val;
  1961. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1962. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1963. NULL)) {
  1964. blog(LOG_INFO, "Could not set privilege to "
  1965. "increase GPU priority");
  1966. }
  1967. }
  1968. CloseHandle(token);
  1969. }
  1970. #endif
  1971. #ifdef __APPLE__
  1972. #define BASE_PATH ".."
  1973. #else
  1974. #define BASE_PATH "../.."
  1975. #endif
  1976. #define CONFIG_PATH BASE_PATH "/config"
  1977. #if defined(ENABLE_PORTABLE_CONFIG) || defined(_WIN32)
  1978. #define ALLOW_PORTABLE_MODE 1
  1979. #else
  1980. #define ALLOW_PORTABLE_MODE 0
  1981. #endif
  1982. int GetAppConfigPath(char *path, size_t size, const char *name)
  1983. {
  1984. #if ALLOW_PORTABLE_MODE
  1985. if (portable_mode) {
  1986. if (name && *name) {
  1987. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1988. } else {
  1989. return snprintf(path, size, CONFIG_PATH);
  1990. }
  1991. } else {
  1992. return os_get_config_path(path, size, name);
  1993. }
  1994. #else
  1995. return os_get_config_path(path, size, name);
  1996. #endif
  1997. }
  1998. char *GetAppConfigPathPtr(const char *name)
  1999. {
  2000. #if ALLOW_PORTABLE_MODE
  2001. if (portable_mode) {
  2002. char path[512];
  2003. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  2004. return bstrdup(path);
  2005. } else {
  2006. return NULL;
  2007. }
  2008. } else {
  2009. return os_get_config_path_ptr(name);
  2010. }
  2011. #else
  2012. return os_get_config_path_ptr(name);
  2013. #endif
  2014. }
  2015. int GetProgramDataPath(char *path, size_t size, const char *name)
  2016. {
  2017. return os_get_program_data_path(path, size, name);
  2018. }
  2019. char *GetProgramDataPathPtr(const char *name)
  2020. {
  2021. return os_get_program_data_path_ptr(name);
  2022. }
  2023. bool GetFileSafeName(const char *name, std::string &file)
  2024. {
  2025. size_t base_len = strlen(name);
  2026. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  2027. std::wstring wfile;
  2028. if (!len)
  2029. return false;
  2030. wfile.resize(len);
  2031. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  2032. for (size_t i = wfile.size(); i > 0; i--) {
  2033. size_t im1 = i - 1;
  2034. if (iswspace(wfile[im1])) {
  2035. wfile[im1] = '_';
  2036. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  2037. wfile.erase(im1, 1);
  2038. }
  2039. }
  2040. if (wfile.size() == 0)
  2041. wfile = L"characters_only";
  2042. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  2043. if (!len)
  2044. return false;
  2045. file.resize(len);
  2046. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  2047. return true;
  2048. }
  2049. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  2050. {
  2051. size_t len = path.size();
  2052. if (extension) {
  2053. path += ".";
  2054. path += extension;
  2055. }
  2056. if (!os_file_exists(path.c_str()))
  2057. return true;
  2058. int index = 1;
  2059. do {
  2060. path.resize(len);
  2061. path += std::to_string(++index);
  2062. if (extension) {
  2063. path += ".";
  2064. path += extension;
  2065. }
  2066. } while (os_file_exists(path.c_str()));
  2067. return true;
  2068. }
  2069. bool WindowPositionValid(QRect rect)
  2070. {
  2071. for (QScreen *screen : QGuiApplication::screens()) {
  2072. if (screen->availableGeometry().intersects(rect))
  2073. return true;
  2074. }
  2075. return false;
  2076. }
  2077. static inline bool arg_is(const char *arg, const char *long_form,
  2078. const char *short_form)
  2079. {
  2080. return (long_form && strcmp(arg, long_form) == 0) ||
  2081. (short_form && strcmp(arg, short_form) == 0);
  2082. }
  2083. static void check_safe_mode_sentinel(void)
  2084. {
  2085. #ifndef NDEBUG
  2086. /* Safe Mode detection is disabled in Debug builds to keep developers
  2087. * somewhat sane. */
  2088. return;
  2089. #else
  2090. if (disable_shutdown_check)
  2091. return;
  2092. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  2093. if (os_file_exists(sentinelPath)) {
  2094. unclean_shutdown = true;
  2095. return;
  2096. }
  2097. os_quick_write_utf8_file(sentinelPath, nullptr, 0, false);
  2098. #endif
  2099. }
  2100. static void delete_safe_mode_sentinel(void)
  2101. {
  2102. #ifndef NDEBUG
  2103. return;
  2104. #else
  2105. BPtr sentinelPath = GetAppConfigPathPtr("obs-studio/safe_mode");
  2106. os_unlink(sentinelPath);
  2107. #endif
  2108. }
  2109. #ifndef _WIN32
  2110. void OBSApp::SigIntSignalHandler(int s)
  2111. {
  2112. /* Handles SIGINT and writes to a socket. Qt will read
  2113. * from the socket in the main thread event loop and trigger
  2114. * a call to the ProcessSigInt slot, where we can safely run
  2115. * shutdown code without signal safety issues. */
  2116. UNUSED_PARAMETER(s);
  2117. char a = 1;
  2118. send(sigintFd[0], &a, sizeof(a), 0);
  2119. }
  2120. #endif
  2121. void OBSApp::ProcessSigInt(void)
  2122. {
  2123. /* This looks weird, but we can't ifdef a Qt slot function so
  2124. * the SIGINT handler simply does nothing on Windows. */
  2125. #ifndef _WIN32
  2126. char tmp;
  2127. recv(sigintFd[1], &tmp, sizeof(tmp), 0);
  2128. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  2129. if (main)
  2130. main->close();
  2131. #endif
  2132. }
  2133. #ifdef _WIN32
  2134. void OBSApp::commitData(QSessionManager &manager)
  2135. {
  2136. if (auto main = App()->GetMainWindow()) {
  2137. QMetaObject::invokeMethod(main, "close", Qt::QueuedConnection);
  2138. manager.cancel();
  2139. }
  2140. }
  2141. #endif
  2142. #ifdef _WIN32
  2143. static constexpr char vcRunErrorTitle[] = "Outdated Visual C++ Runtime";
  2144. static constexpr char vcRunErrorMsg[] =
  2145. "OBS Studio requires a newer version of the Microsoft Visual C++ "
  2146. "Redistributables.\n\nYou will now be directed to the download page.";
  2147. static constexpr char vcRunInstallerUrl[] =
  2148. "https://obsproject.com/visual-studio-2022-runtimes";
  2149. static bool vc_runtime_outdated()
  2150. {
  2151. win_version_info ver;
  2152. if (!get_dll_ver(L"msvcp140.dll", &ver))
  2153. return true;
  2154. /* Major is always 14 (hence 140.dll), so we only care about minor. */
  2155. if (ver.minor >= 40)
  2156. return false;
  2157. int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle,
  2158. MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL);
  2159. if (choice == IDOK) {
  2160. /* Open the URL in the default browser. */
  2161. ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL,
  2162. SW_SHOWNORMAL);
  2163. }
  2164. return true;
  2165. }
  2166. #endif
  2167. int main(int argc, char *argv[])
  2168. {
  2169. #ifndef _WIN32
  2170. signal(SIGPIPE, SIG_IGN);
  2171. struct sigaction sig_handler;
  2172. sig_handler.sa_handler = OBSApp::SigIntSignalHandler;
  2173. sigemptyset(&sig_handler.sa_mask);
  2174. sig_handler.sa_flags = 0;
  2175. sigaction(SIGINT, &sig_handler, NULL);
  2176. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  2177. a closed pipe. */
  2178. sigset_t sigpipe_mask;
  2179. sigemptyset(&sigpipe_mask);
  2180. sigaddset(&sigpipe_mask, SIGPIPE);
  2181. sigset_t saved_mask;
  2182. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  2183. perror("pthread_sigmask");
  2184. exit(1);
  2185. }
  2186. #endif
  2187. #ifdef _WIN32
  2188. // Abort as early as possible if MSVC runtime is outdated
  2189. if (vc_runtime_outdated())
  2190. return 1;
  2191. // Try to keep this as early as possible
  2192. install_dll_blocklist_hook();
  2193. obs_init_win32_crash_handler();
  2194. SetErrorMode(SEM_FAILCRITICALERRORS);
  2195. load_debug_privilege();
  2196. base_set_crash_handler(main_crash_handler, nullptr);
  2197. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  2198. if (hRtwq) {
  2199. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  2200. PFN_RtwqStartup func =
  2201. (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  2202. func();
  2203. }
  2204. #endif
  2205. base_get_log_handler(&def_log_handler, nullptr);
  2206. obs_set_cmdline_args(argc, argv);
  2207. for (int i = 1; i < argc; i++) {
  2208. if (arg_is(argv[i], "--multi", "-m")) {
  2209. multi = true;
  2210. disable_shutdown_check = true;
  2211. #if ALLOW_PORTABLE_MODE
  2212. } else if (arg_is(argv[i], "--portable", "-p")) {
  2213. portable_mode = true;
  2214. #endif
  2215. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2216. log_verbose = true;
  2217. } else if (arg_is(argv[i], "--safe-mode", nullptr)) {
  2218. safe_mode = true;
  2219. } else if (arg_is(argv[i], "--only-bundled-plugins", nullptr)) {
  2220. disable_3p_plugins = true;
  2221. } else if (arg_is(argv[i], "--disable-shutdown-check",
  2222. nullptr)) {
  2223. /* This exists mostly to bypass the dialog during development. */
  2224. disable_shutdown_check = true;
  2225. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2226. opt_always_on_top = true;
  2227. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2228. unfiltered_log = true;
  2229. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2230. opt_start_streaming = true;
  2231. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2232. opt_start_recording = true;
  2233. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2234. opt_start_replaybuffer = true;
  2235. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2236. opt_start_virtualcam = true;
  2237. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2238. if (++i < argc)
  2239. opt_starting_collection = argv[i];
  2240. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2241. if (++i < argc)
  2242. opt_starting_profile = argv[i];
  2243. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2244. if (++i < argc)
  2245. opt_starting_scene = argv[i];
  2246. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2247. opt_minimize_tray = true;
  2248. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2249. opt_studio_mode = true;
  2250. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2251. opt_allow_opengl = true;
  2252. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2253. opt_disable_updater = true;
  2254. } else if (arg_is(argv[i], "--disable-missing-files-check",
  2255. nullptr)) {
  2256. opt_disable_missing_files_check = true;
  2257. } else if (arg_is(argv[i], "--steam", nullptr)) {
  2258. steam = true;
  2259. } else if (arg_is(argv[i], "--help", "-h")) {
  2260. std::string help =
  2261. "--help, -h: Get list of available commands.\n\n"
  2262. "--startstreaming: Automatically start streaming.\n"
  2263. "--startrecording: Automatically start recording.\n"
  2264. "--startreplaybuffer: Start replay buffer.\n"
  2265. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2266. "--collection <string>: Use specific scene collection."
  2267. "\n"
  2268. "--profile <string>: Use specific profile.\n"
  2269. "--scene <string>: Start with specific scene.\n\n"
  2270. "--studio-mode: Enable studio mode.\n"
  2271. "--minimize-to-tray: Minimize to system tray.\n"
  2272. #if ALLOW_PORTABLE_MODE
  2273. "--portable, -p: Use portable mode.\n"
  2274. #endif
  2275. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2276. "--safe-mode: Run in Safe Mode (disables third-party plugins, scripting, and WebSockets).\n"
  2277. "--only-bundled-plugins: Only load included (first-party) plugins\n"
  2278. "--disable-shutdown-check: Disable unclean shutdown detection.\n"
  2279. "--verbose: Make log more verbose.\n"
  2280. "--always-on-top: Start in 'always on top' mode.\n\n"
  2281. "--unfiltered_log: Make log unfiltered.\n\n"
  2282. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2283. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n";
  2284. #ifdef _WIN32
  2285. MessageBoxA(NULL, help.c_str(), "Help",
  2286. MB_OK | MB_ICONASTERISK);
  2287. #else
  2288. std::cout << help
  2289. << "--version, -V: Get current version.\n";
  2290. #endif
  2291. exit(0);
  2292. } else if (arg_is(argv[i], "--version", "-V")) {
  2293. std::cout << "OBS Studio - "
  2294. << App()->GetVersionString(false) << "\n";
  2295. exit(0);
  2296. }
  2297. }
  2298. #if ALLOW_PORTABLE_MODE
  2299. if (!portable_mode) {
  2300. portable_mode =
  2301. os_file_exists(BASE_PATH "/portable_mode") ||
  2302. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2303. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2304. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2305. }
  2306. if (!opt_disable_updater) {
  2307. opt_disable_updater =
  2308. os_file_exists(BASE_PATH "/disable_updater") ||
  2309. os_file_exists(BASE_PATH "/disable_updater.txt");
  2310. }
  2311. if (!opt_disable_missing_files_check) {
  2312. opt_disable_missing_files_check =
  2313. os_file_exists(BASE_PATH
  2314. "/disable_missing_files_check") ||
  2315. os_file_exists(BASE_PATH
  2316. "/disable_missing_files_check.txt");
  2317. }
  2318. #endif
  2319. check_safe_mode_sentinel();
  2320. fstream logFile;
  2321. curl_global_init(CURL_GLOBAL_ALL);
  2322. int ret = run_program(logFile, argc, argv);
  2323. #ifdef _WIN32
  2324. if (hRtwq) {
  2325. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  2326. PFN_RtwqShutdown func =
  2327. (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  2328. func();
  2329. FreeLibrary(hRtwq);
  2330. }
  2331. log_blocked_dlls();
  2332. #endif
  2333. delete_safe_mode_sentinel();
  2334. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2335. base_set_log_handler(nullptr, nullptr);
  2336. if (restart || restart_safe) {
  2337. auto executable = arguments.takeFirst();
  2338. QProcess::startDetached(executable, arguments);
  2339. }
  2340. return ret;
  2341. }