obs-app.cpp 60 KB

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