obs-app.cpp 42 KB

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