obs-app.cpp 71 KB

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