obs-app.cpp 74 KB

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