obs-app.cpp 68 KB

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