obs-app.cpp 84 KB

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