obs-app.cpp 66 KB

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