obs-app.cpp 63 KB

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