obs-app.cpp 59 KB

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