obs-app.cpp 84 KB

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