1
0

obs-app.cpp 74 KB

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