obs-app.cpp 74 KB

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