obs-app.cpp 85 KB

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