obs-app.cpp 57 KB

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