obs-app.cpp 73 KB

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