obs-app.cpp 71 KB

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