obs-app.cpp 41 KB

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