obs-app.cpp 65 KB

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