obs-app.cpp 66 KB

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