obs-app.cpp 58 KB

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