obs-app.cpp 40 KB

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