obs-app.cpp 77 KB

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