obs-app.cpp 86 KB

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