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