obs-app.cpp 68 KB

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