1
0

obs-app.cpp 70 KB

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