obs-app.cpp 41 KB

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