obs-app.cpp 82 KB

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