obs-app.cpp 54 KB

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