obs-app.cpp 42 KB

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