obs-app.cpp 55 KB

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