obs-app.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921
  1. /******************************************************************************
  2. Copyright (C) 2013 by Hugh Bailey <[email protected]>
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 2 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. ******************************************************************************/
  14. #include <time.h>
  15. #include <stdio.h>
  16. #include <wchar.h>
  17. #include <chrono>
  18. #include <ratio>
  19. #include <string>
  20. #include <sstream>
  21. #include <mutex>
  22. #include <util/bmem.h>
  23. #include <util/dstr.hpp>
  24. #include <util/platform.h>
  25. #include <util/profiler.hpp>
  26. #include <util/cf-parser.h>
  27. #include <obs-config.h>
  28. #include <obs.hpp>
  29. #include <QFile>
  30. #include <QGuiApplication>
  31. #include <QProxyStyle>
  32. #include <QScreen>
  33. #include <QProcess>
  34. #include <QAccessible>
  35. #include "qt-wrappers.hpp"
  36. #include "obs-app.hpp"
  37. #include "log-viewer.hpp"
  38. #include "slider-ignorewheel.hpp"
  39. #include "window-basic-main.hpp"
  40. #include "window-basic-settings.hpp"
  41. #include "crash-report.hpp"
  42. #include "platform.hpp"
  43. #include <fstream>
  44. #include <curl/curl.h>
  45. #ifdef _WIN32
  46. #include <windows.h>
  47. #include <filesystem>
  48. #else
  49. #include <signal.h>
  50. #include <pthread.h>
  51. #endif
  52. #if !defined(_WIN32) && !defined(__APPLE__)
  53. #include <obs-nix-platform.h>
  54. #include <qpa/qplatformnativeinterface.h>
  55. #endif
  56. #include <iostream>
  57. #include "ui-config.h"
  58. using namespace std;
  59. static log_handler_t def_log_handler;
  60. static string currentLogFile;
  61. static string lastLogFile;
  62. static string lastCrashLogFile;
  63. bool portable_mode = false;
  64. static bool multi = false;
  65. static bool log_verbose = false;
  66. static bool unfiltered_log = false;
  67. bool opt_start_streaming = false;
  68. bool opt_start_recording = false;
  69. bool opt_studio_mode = false;
  70. bool opt_start_replaybuffer = false;
  71. bool opt_start_virtualcam = false;
  72. bool opt_minimize_tray = false;
  73. bool opt_allow_opengl = false;
  74. bool opt_always_on_top = false;
  75. bool opt_disable_high_dpi_scaling = false;
  76. bool opt_disable_updater = false;
  77. bool opt_disable_missing_files_check = false;
  78. string opt_starting_collection;
  79. string opt_starting_profile;
  80. string opt_starting_scene;
  81. bool restart = false;
  82. QPointer<OBSLogViewer> obsLogViewer;
  83. // GPU hint exports for AMD/NVIDIA laptops
  84. #ifdef _MSC_VER
  85. extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
  86. extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
  87. #endif
  88. QObject *CreateShortcutFilter()
  89. {
  90. return new OBSEventFilter([](QObject *obj, QEvent *event) {
  91. auto mouse_event = [](QMouseEvent &event) {
  92. if (!App()->HotkeysEnabledInFocus() &&
  93. event.button() != Qt::LeftButton)
  94. return true;
  95. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  96. bool pressed = event.type() == QEvent::MouseButtonPress;
  97. switch (event.button()) {
  98. case Qt::NoButton:
  99. case Qt::LeftButton:
  100. case Qt::RightButton:
  101. case Qt::AllButtons:
  102. case Qt::MouseButtonMask:
  103. return false;
  104. case Qt::MiddleButton:
  105. hotkey.key = OBS_KEY_MOUSE3;
  106. break;
  107. #define MAP_BUTTON(i, j) \
  108. case Qt::ExtraButton##i: \
  109. hotkey.key = OBS_KEY_MOUSE##j; \
  110. break;
  111. MAP_BUTTON(1, 4);
  112. MAP_BUTTON(2, 5);
  113. MAP_BUTTON(3, 6);
  114. MAP_BUTTON(4, 7);
  115. MAP_BUTTON(5, 8);
  116. MAP_BUTTON(6, 9);
  117. MAP_BUTTON(7, 10);
  118. MAP_BUTTON(8, 11);
  119. MAP_BUTTON(9, 12);
  120. MAP_BUTTON(10, 13);
  121. MAP_BUTTON(11, 14);
  122. MAP_BUTTON(12, 15);
  123. MAP_BUTTON(13, 16);
  124. MAP_BUTTON(14, 17);
  125. MAP_BUTTON(15, 18);
  126. MAP_BUTTON(16, 19);
  127. MAP_BUTTON(17, 20);
  128. MAP_BUTTON(18, 21);
  129. MAP_BUTTON(19, 22);
  130. MAP_BUTTON(20, 23);
  131. MAP_BUTTON(21, 24);
  132. MAP_BUTTON(22, 25);
  133. MAP_BUTTON(23, 26);
  134. MAP_BUTTON(24, 27);
  135. #undef MAP_BUTTON
  136. }
  137. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  138. event.modifiers());
  139. obs_hotkey_inject_event(hotkey, pressed);
  140. return true;
  141. };
  142. auto key_event = [&](QKeyEvent *event) {
  143. int key = event->key();
  144. bool enabledInFocus = App()->HotkeysEnabledInFocus();
  145. if (key != Qt::Key_Enter && key != Qt::Key_Escape &&
  146. key != Qt::Key_Return && !enabledInFocus)
  147. return true;
  148. QDialog *dialog = qobject_cast<QDialog *>(obj);
  149. obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
  150. bool pressed = event->type() == QEvent::KeyPress;
  151. switch (key) {
  152. case Qt::Key_Shift:
  153. case Qt::Key_Control:
  154. case Qt::Key_Alt:
  155. case Qt::Key_Meta:
  156. break;
  157. #ifdef __APPLE__
  158. case Qt::Key_CapsLock:
  159. // kVK_CapsLock == 57
  160. hotkey.key = obs_key_from_virtual_key(57);
  161. pressed = true;
  162. break;
  163. #endif
  164. case Qt::Key_Enter:
  165. case Qt::Key_Escape:
  166. case Qt::Key_Return:
  167. if (dialog && pressed)
  168. return false;
  169. if (!enabledInFocus)
  170. return true;
  171. /* Falls through. */
  172. default:
  173. hotkey.key = obs_key_from_virtual_key(
  174. event->nativeVirtualKey());
  175. }
  176. if (event->isAutoRepeat())
  177. return true;
  178. hotkey.modifiers = TranslateQtKeyboardEventModifiers(
  179. event->modifiers());
  180. obs_hotkey_inject_event(hotkey, pressed);
  181. return true;
  182. };
  183. switch (event->type()) {
  184. case QEvent::MouseButtonPress:
  185. case QEvent::MouseButtonRelease:
  186. return mouse_event(*static_cast<QMouseEvent *>(event));
  187. /*case QEvent::MouseButtonDblClick:
  188. case QEvent::Wheel:*/
  189. case QEvent::KeyPress:
  190. case QEvent::KeyRelease:
  191. return key_event(static_cast<QKeyEvent *>(event));
  192. default:
  193. return false;
  194. }
  195. });
  196. }
  197. string CurrentTimeString()
  198. {
  199. using namespace std::chrono;
  200. struct tm tstruct;
  201. char buf[80];
  202. auto tp = system_clock::now();
  203. auto now = system_clock::to_time_t(tp);
  204. tstruct = *localtime(&now);
  205. size_t written = strftime(buf, sizeof(buf), "%T", &tstruct);
  206. if (ratio_less<system_clock::period, seconds::period>::value &&
  207. written && (sizeof(buf) - written) > 5) {
  208. auto tp_secs = time_point_cast<seconds>(tp);
  209. auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
  210. snprintf(buf + written, sizeof(buf) - written, ".%03u",
  211. static_cast<unsigned>(millis));
  212. }
  213. return buf;
  214. }
  215. string CurrentDateTimeString()
  216. {
  217. time_t now = time(0);
  218. struct tm tstruct;
  219. char buf[80];
  220. tstruct = *localtime(&now);
  221. strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
  222. return buf;
  223. }
  224. static inline void LogString(fstream &logFile, const char *timeString,
  225. char *str, int log_level)
  226. {
  227. string msg;
  228. msg += timeString;
  229. msg += str;
  230. logFile << msg << endl;
  231. if (!!obsLogViewer)
  232. QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine",
  233. Qt::QueuedConnection,
  234. Q_ARG(int, log_level),
  235. Q_ARG(QString, QString(msg.c_str())));
  236. }
  237. static inline void LogStringChunk(fstream &logFile, char *str, int log_level)
  238. {
  239. char *nextLine = str;
  240. string timeString = CurrentTimeString();
  241. timeString += ": ";
  242. while (*nextLine) {
  243. char *nextLine = strchr(str, '\n');
  244. if (!nextLine)
  245. break;
  246. if (nextLine != str && nextLine[-1] == '\r') {
  247. nextLine[-1] = 0;
  248. } else {
  249. nextLine[0] = 0;
  250. }
  251. LogString(logFile, timeString.c_str(), str, log_level);
  252. nextLine++;
  253. str = nextLine;
  254. }
  255. LogString(logFile, timeString.c_str(), str, log_level);
  256. }
  257. #define MAX_REPEATED_LINES 30
  258. #define MAX_CHAR_VARIATION (255 * 3)
  259. static inline int sum_chars(const char *str)
  260. {
  261. int val = 0;
  262. for (; *str != 0; str++)
  263. val += *str;
  264. return val;
  265. }
  266. static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
  267. const char *output_str)
  268. {
  269. static mutex log_mutex;
  270. static const char *last_msg_ptr = nullptr;
  271. static int last_char_sum = 0;
  272. static char cmp_str[4096];
  273. static int rep_count = 0;
  274. int new_sum = sum_chars(output_str);
  275. lock_guard<mutex> guard(log_mutex);
  276. if (unfiltered_log) {
  277. return false;
  278. }
  279. if (last_msg_ptr == msg) {
  280. int diff = std::abs(new_sum - last_char_sum);
  281. if (diff < MAX_CHAR_VARIATION) {
  282. return (rep_count++ >= MAX_REPEATED_LINES);
  283. }
  284. }
  285. if (rep_count > MAX_REPEATED_LINES) {
  286. logFile << CurrentTimeString()
  287. << ": Last log entry repeated for "
  288. << to_string(rep_count - MAX_REPEATED_LINES)
  289. << " more lines" << endl;
  290. }
  291. last_msg_ptr = msg;
  292. strcpy(cmp_str, output_str);
  293. last_char_sum = new_sum;
  294. rep_count = 0;
  295. return false;
  296. }
  297. static void do_log(int log_level, const char *msg, va_list args, void *param)
  298. {
  299. fstream &logFile = *static_cast<fstream *>(param);
  300. char str[4096];
  301. #ifndef _WIN32
  302. va_list args2;
  303. va_copy(args2, args);
  304. #endif
  305. vsnprintf(str, 4095, msg, args);
  306. #ifdef _WIN32
  307. if (IsDebuggerPresent()) {
  308. int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
  309. if (wNum > 1) {
  310. static wstring wide_buf;
  311. static mutex wide_mutex;
  312. lock_guard<mutex> lock(wide_mutex);
  313. wide_buf.reserve(wNum + 1);
  314. wide_buf.resize(wNum - 1);
  315. MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
  316. wNum);
  317. wide_buf.push_back('\n');
  318. OutputDebugStringW(wide_buf.c_str());
  319. }
  320. }
  321. #else
  322. def_log_handler(log_level, msg, args2, nullptr);
  323. va_end(args2);
  324. #endif
  325. if (log_level <= LOG_INFO || log_verbose) {
  326. if (too_many_repeated_entries(logFile, msg, str))
  327. return;
  328. LogStringChunk(logFile, str, log_level);
  329. }
  330. #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
  331. if (log_level <= LOG_ERROR && IsDebuggerPresent())
  332. __debugbreak();
  333. #endif
  334. }
  335. #define DEFAULT_LANG "en-US"
  336. bool OBSApp::InitGlobalConfigDefaults()
  337. {
  338. config_set_default_string(globalConfig, "General", "Language",
  339. DEFAULT_LANG);
  340. config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
  341. config_set_default_int(globalConfig, "General", "InfoIncrement", -1);
  342. config_set_default_string(globalConfig, "General", "ProcessPriority",
  343. "Normal");
  344. config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
  345. true);
  346. config_set_default_bool(globalConfig, "General", "ConfirmOnExit", true);
  347. #if _WIN32
  348. config_set_default_string(globalConfig, "Video", "Renderer",
  349. "Direct3D 11");
  350. #else
  351. config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
  352. #endif
  353. config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
  354. true);
  355. config_set_default_bool(globalConfig, "BasicWindow",
  356. "PreviewProgramMode", false);
  357. config_set_default_bool(globalConfig, "BasicWindow",
  358. "SceneDuplicationMode", true);
  359. config_set_default_bool(globalConfig, "BasicWindow", "SwapScenesMode",
  360. true);
  361. config_set_default_bool(globalConfig, "BasicWindow", "SnappingEnabled",
  362. true);
  363. config_set_default_bool(globalConfig, "BasicWindow", "ScreenSnapping",
  364. true);
  365. config_set_default_bool(globalConfig, "BasicWindow", "SourceSnapping",
  366. true);
  367. config_set_default_bool(globalConfig, "BasicWindow", "CenterSnapping",
  368. false);
  369. config_set_default_double(globalConfig, "BasicWindow", "SnapDistance",
  370. 10.0);
  371. config_set_default_bool(globalConfig, "BasicWindow",
  372. "RecordWhenStreaming", false);
  373. config_set_default_bool(globalConfig, "BasicWindow",
  374. "KeepRecordingWhenStreamStops", false);
  375. config_set_default_bool(globalConfig, "BasicWindow", "SysTrayEnabled",
  376. true);
  377. config_set_default_bool(globalConfig, "BasicWindow",
  378. "SysTrayWhenStarted", false);
  379. config_set_default_bool(globalConfig, "BasicWindow", "SaveProjectors",
  380. false);
  381. config_set_default_bool(globalConfig, "BasicWindow", "ShowTransitions",
  382. true);
  383. config_set_default_bool(globalConfig, "BasicWindow",
  384. "ShowListboxToolbars", true);
  385. config_set_default_bool(globalConfig, "BasicWindow", "ShowStatusBar",
  386. true);
  387. config_set_default_bool(globalConfig, "BasicWindow", "ShowSourceIcons",
  388. true);
  389. config_set_default_bool(globalConfig, "BasicWindow",
  390. "ShowContextToolbars", true);
  391. config_set_default_bool(globalConfig, "BasicWindow", "StudioModeLabels",
  392. true);
  393. if (!config_get_bool(globalConfig, "General", "Pre21Defaults")) {
  394. config_set_default_string(globalConfig, "General",
  395. "CurrentTheme", DEFAULT_THEME);
  396. }
  397. config_set_default_string(globalConfig, "General", "HotkeyFocusType",
  398. "NeverDisableHotkeys");
  399. config_set_default_bool(globalConfig, "BasicWindow",
  400. "VerticalVolControl", false);
  401. config_set_default_bool(globalConfig, "BasicWindow",
  402. "MultiviewMouseSwitch", true);
  403. config_set_default_bool(globalConfig, "BasicWindow",
  404. "MultiviewDrawNames", true);
  405. config_set_default_bool(globalConfig, "BasicWindow",
  406. "MultiviewDrawAreas", true);
  407. #ifdef _WIN32
  408. uint32_t winver = GetWindowsVersion();
  409. config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
  410. true);
  411. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  412. winver > 0x601);
  413. #endif
  414. #ifdef __APPLE__
  415. config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
  416. true);
  417. config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
  418. config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
  419. true);
  420. #endif
  421. config_set_default_bool(globalConfig, "BasicWindow",
  422. "MediaControlsCountdownTimer", true);
  423. return true;
  424. }
  425. static bool do_mkdir(const char *path)
  426. {
  427. if (os_mkdirs(path) == MKDIR_ERROR) {
  428. OBSErrorBox(NULL, "Failed to create directory %s", path);
  429. return false;
  430. }
  431. return true;
  432. }
  433. static bool MakeUserDirs()
  434. {
  435. char path[512];
  436. if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
  437. return false;
  438. if (!do_mkdir(path))
  439. return false;
  440. if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
  441. return false;
  442. if (!do_mkdir(path))
  443. return false;
  444. if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
  445. return false;
  446. if (!do_mkdir(path))
  447. return false;
  448. #ifdef _WIN32
  449. if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
  450. return false;
  451. if (!do_mkdir(path))
  452. return false;
  453. if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
  454. return false;
  455. if (!do_mkdir(path))
  456. return false;
  457. #endif
  458. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  459. return false;
  460. if (!do_mkdir(path))
  461. return false;
  462. return true;
  463. }
  464. static bool MakeUserProfileDirs()
  465. {
  466. char path[512];
  467. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  468. return false;
  469. if (!do_mkdir(path))
  470. return false;
  471. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  472. return false;
  473. if (!do_mkdir(path))
  474. return false;
  475. return true;
  476. }
  477. static string GetProfileDirFromName(const char *name)
  478. {
  479. string outputPath;
  480. os_glob_t *glob;
  481. char path[512];
  482. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
  483. return outputPath;
  484. strcat(path, "/*");
  485. if (os_glob(path, 0, &glob) != 0)
  486. return outputPath;
  487. for (size_t i = 0; i < glob->gl_pathc; i++) {
  488. struct os_globent ent = glob->gl_pathv[i];
  489. if (!ent.directory)
  490. continue;
  491. strcpy(path, ent.path);
  492. strcat(path, "/basic.ini");
  493. ConfigFile config;
  494. if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
  495. continue;
  496. const char *curName =
  497. config_get_string(config, "General", "Name");
  498. if (astrcmpi(curName, name) == 0) {
  499. outputPath = ent.path;
  500. break;
  501. }
  502. }
  503. os_globfree(glob);
  504. if (!outputPath.empty()) {
  505. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  506. const char *start = strrchr(outputPath.c_str(), '/');
  507. if (start)
  508. outputPath.erase(0, start - outputPath.c_str() + 1);
  509. }
  510. return outputPath;
  511. }
  512. static string GetSceneCollectionFileFromName(const char *name)
  513. {
  514. string outputPath;
  515. os_glob_t *glob;
  516. char path[512];
  517. if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
  518. return outputPath;
  519. strcat(path, "/*.json");
  520. if (os_glob(path, 0, &glob) != 0)
  521. return outputPath;
  522. for (size_t i = 0; i < glob->gl_pathc; i++) {
  523. struct os_globent ent = glob->gl_pathv[i];
  524. if (ent.directory)
  525. continue;
  526. OBSDataAutoRelease data =
  527. obs_data_create_from_json_file_safe(ent.path, "bak");
  528. const char *curName = obs_data_get_string(data, "name");
  529. if (astrcmpi(name, curName) == 0) {
  530. outputPath = ent.path;
  531. break;
  532. }
  533. }
  534. os_globfree(glob);
  535. if (!outputPath.empty()) {
  536. outputPath.resize(outputPath.size() - 5);
  537. replace(outputPath.begin(), outputPath.end(), '\\', '/');
  538. const char *start = strrchr(outputPath.c_str(), '/');
  539. if (start)
  540. outputPath.erase(0, start - outputPath.c_str() + 1);
  541. }
  542. return outputPath;
  543. }
  544. bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
  545. {
  546. if (!layout)
  547. return false;
  548. if (astrcmpi(layout, "horizontaltop") == 0) {
  549. config_set_int(
  550. globalConfig, "BasicWindow", "MultiviewLayout",
  551. static_cast<int>(
  552. MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
  553. return true;
  554. }
  555. if (astrcmpi(layout, "horizontalbottom") == 0) {
  556. config_set_int(
  557. globalConfig, "BasicWindow", "MultiviewLayout",
  558. static_cast<int>(
  559. MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
  560. return true;
  561. }
  562. if (astrcmpi(layout, "verticalleft") == 0) {
  563. config_set_int(
  564. globalConfig, "BasicWindow", "MultiviewLayout",
  565. static_cast<int>(
  566. MultiviewLayout::VERTICAL_LEFT_8_SCENES));
  567. return true;
  568. }
  569. if (astrcmpi(layout, "verticalright") == 0) {
  570. config_set_int(
  571. globalConfig, "BasicWindow", "MultiviewLayout",
  572. static_cast<int>(
  573. MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
  574. return true;
  575. }
  576. return false;
  577. }
  578. bool OBSApp::InitGlobalConfig()
  579. {
  580. char path[512];
  581. bool changed = false;
  582. int len = GetConfigPath(path, sizeof(path), "obs-studio/global.ini");
  583. if (len <= 0) {
  584. return false;
  585. }
  586. int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
  587. if (errorcode != CONFIG_SUCCESS) {
  588. OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
  589. return false;
  590. }
  591. if (!opt_starting_collection.empty()) {
  592. string path = GetSceneCollectionFileFromName(
  593. opt_starting_collection.c_str());
  594. if (!path.empty()) {
  595. config_set_string(globalConfig, "Basic",
  596. "SceneCollection",
  597. opt_starting_collection.c_str());
  598. config_set_string(globalConfig, "Basic",
  599. "SceneCollectionFile", path.c_str());
  600. changed = true;
  601. }
  602. }
  603. if (!opt_starting_profile.empty()) {
  604. string path =
  605. GetProfileDirFromName(opt_starting_profile.c_str());
  606. if (!path.empty()) {
  607. config_set_string(globalConfig, "Basic", "Profile",
  608. opt_starting_profile.c_str());
  609. config_set_string(globalConfig, "Basic", "ProfileDir",
  610. path.c_str());
  611. changed = true;
  612. }
  613. }
  614. uint32_t lastVersion =
  615. config_get_int(globalConfig, "General", "LastVersion");
  616. if (!config_has_user_value(globalConfig, "General", "Pre19Defaults")) {
  617. bool useOldDefaults = lastVersion &&
  618. lastVersion <
  619. MAKE_SEMANTIC_VERSION(19, 0, 0);
  620. config_set_bool(globalConfig, "General", "Pre19Defaults",
  621. useOldDefaults);
  622. changed = true;
  623. }
  624. if (!config_has_user_value(globalConfig, "General", "Pre21Defaults")) {
  625. bool useOldDefaults = lastVersion &&
  626. lastVersion <
  627. MAKE_SEMANTIC_VERSION(21, 0, 0);
  628. config_set_bool(globalConfig, "General", "Pre21Defaults",
  629. useOldDefaults);
  630. changed = true;
  631. }
  632. if (!config_has_user_value(globalConfig, "General", "Pre23Defaults")) {
  633. bool useOldDefaults = lastVersion &&
  634. lastVersion <
  635. MAKE_SEMANTIC_VERSION(23, 0, 0);
  636. config_set_bool(globalConfig, "General", "Pre23Defaults",
  637. useOldDefaults);
  638. changed = true;
  639. }
  640. #define PRE_24_1_DEFS "Pre24.1Defaults"
  641. if (!config_has_user_value(globalConfig, "General", PRE_24_1_DEFS)) {
  642. bool useOldDefaults = lastVersion &&
  643. lastVersion <
  644. MAKE_SEMANTIC_VERSION(24, 1, 0);
  645. config_set_bool(globalConfig, "General", PRE_24_1_DEFS,
  646. useOldDefaults);
  647. changed = true;
  648. }
  649. #undef PRE_24_1_DEFS
  650. if (config_has_user_value(globalConfig, "BasicWindow",
  651. "MultiviewLayout")) {
  652. const char *layout = config_get_string(
  653. globalConfig, "BasicWindow", "MultiviewLayout");
  654. changed |= UpdatePre22MultiviewLayout(layout);
  655. }
  656. if (lastVersion && lastVersion < MAKE_SEMANTIC_VERSION(24, 0, 0)) {
  657. bool disableHotkeysInFocus = config_get_bool(
  658. globalConfig, "General", "DisableHotkeysInFocus");
  659. if (disableHotkeysInFocus)
  660. config_set_string(globalConfig, "General",
  661. "HotkeyFocusType",
  662. "DisableHotkeysInFocus");
  663. changed = true;
  664. }
  665. if (changed)
  666. config_save_safe(globalConfig, "tmp", nullptr);
  667. return InitGlobalConfigDefaults();
  668. }
  669. bool OBSApp::InitLocale()
  670. {
  671. ProfileScope("OBSApp::InitLocale");
  672. const char *lang =
  673. config_get_string(globalConfig, "General", "Language");
  674. locale = lang;
  675. // set basic default application locale
  676. if (!locale.empty())
  677. QLocale::setDefault(QLocale(
  678. QString::fromStdString(locale).replace('-', '_')));
  679. string englishPath;
  680. if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
  681. OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
  682. return false;
  683. }
  684. textLookup = text_lookup_create(englishPath.c_str());
  685. if (!textLookup) {
  686. OBSErrorBox(NULL, "Failed to create locale from file '%s'",
  687. englishPath.c_str());
  688. return false;
  689. }
  690. bool userLocale =
  691. config_has_user_value(globalConfig, "General", "Language");
  692. bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;
  693. if (userLocale && defaultLang)
  694. return true;
  695. if (!userLocale && defaultLang) {
  696. for (auto &locale_ : GetPreferredLocales()) {
  697. if (locale_ == lang)
  698. return true;
  699. stringstream file;
  700. file << "locale/" << locale_ << ".ini";
  701. string path;
  702. if (!GetDataFilePath(file.str().c_str(), path))
  703. continue;
  704. if (!text_lookup_add(textLookup, path.c_str()))
  705. continue;
  706. blog(LOG_INFO, "Using preferred locale '%s'",
  707. locale_.c_str());
  708. locale = locale_;
  709. // set application default locale to the new choosen one
  710. if (!locale.empty())
  711. QLocale::setDefault(QLocale(
  712. QString::fromStdString(locale).replace(
  713. '-', '_')));
  714. return true;
  715. }
  716. return true;
  717. }
  718. stringstream file;
  719. file << "locale/" << lang << ".ini";
  720. string path;
  721. if (GetDataFilePath(file.str().c_str(), path)) {
  722. if (!text_lookup_add(textLookup, path.c_str()))
  723. blog(LOG_ERROR, "Failed to add locale file '%s'",
  724. path.c_str());
  725. } else {
  726. blog(LOG_ERROR, "Could not find locale file '%s'",
  727. file.str().c_str());
  728. }
  729. return true;
  730. }
  731. void OBSApp::AddExtraThemeColor(QPalette &pal, int group, const char *name,
  732. uint32_t color)
  733. {
  734. std::function<void(QPalette::ColorGroup)> func;
  735. #define DEF_PALETTE_ASSIGN(name) \
  736. do { \
  737. func = [&](QPalette::ColorGroup group) { \
  738. pal.setColor(group, QPalette::name, \
  739. QColor::fromRgb(color)); \
  740. }; \
  741. } while (false)
  742. if (astrcmpi(name, "alternateBase") == 0) {
  743. DEF_PALETTE_ASSIGN(AlternateBase);
  744. } else if (astrcmpi(name, "base") == 0) {
  745. DEF_PALETTE_ASSIGN(Base);
  746. } else if (astrcmpi(name, "brightText") == 0) {
  747. DEF_PALETTE_ASSIGN(BrightText);
  748. } else if (astrcmpi(name, "button") == 0) {
  749. DEF_PALETTE_ASSIGN(Button);
  750. } else if (astrcmpi(name, "buttonText") == 0) {
  751. DEF_PALETTE_ASSIGN(ButtonText);
  752. } else if (astrcmpi(name, "brightText") == 0) {
  753. DEF_PALETTE_ASSIGN(BrightText);
  754. } else if (astrcmpi(name, "dark") == 0) {
  755. DEF_PALETTE_ASSIGN(Dark);
  756. } else if (astrcmpi(name, "highlight") == 0) {
  757. DEF_PALETTE_ASSIGN(Highlight);
  758. } else if (astrcmpi(name, "highlightedText") == 0) {
  759. DEF_PALETTE_ASSIGN(HighlightedText);
  760. } else if (astrcmpi(name, "light") == 0) {
  761. DEF_PALETTE_ASSIGN(Light);
  762. } else if (astrcmpi(name, "link") == 0) {
  763. DEF_PALETTE_ASSIGN(Link);
  764. } else if (astrcmpi(name, "linkVisited") == 0) {
  765. DEF_PALETTE_ASSIGN(LinkVisited);
  766. } else if (astrcmpi(name, "mid") == 0) {
  767. DEF_PALETTE_ASSIGN(Mid);
  768. } else if (astrcmpi(name, "midlight") == 0) {
  769. DEF_PALETTE_ASSIGN(Midlight);
  770. } else if (astrcmpi(name, "shadow") == 0) {
  771. DEF_PALETTE_ASSIGN(Shadow);
  772. } else if (astrcmpi(name, "text") == 0 ||
  773. astrcmpi(name, "foreground") == 0) {
  774. DEF_PALETTE_ASSIGN(Text);
  775. } else if (astrcmpi(name, "toolTipBase") == 0) {
  776. DEF_PALETTE_ASSIGN(ToolTipBase);
  777. } else if (astrcmpi(name, "toolTipText") == 0) {
  778. DEF_PALETTE_ASSIGN(ToolTipText);
  779. } else if (astrcmpi(name, "windowText") == 0) {
  780. DEF_PALETTE_ASSIGN(WindowText);
  781. } else if (astrcmpi(name, "window") == 0 ||
  782. astrcmpi(name, "background") == 0) {
  783. DEF_PALETTE_ASSIGN(Window);
  784. } else {
  785. return;
  786. }
  787. #undef DEF_PALETTE_ASSIGN
  788. switch (group) {
  789. case QPalette::Disabled:
  790. case QPalette::Active:
  791. case QPalette::Inactive:
  792. func((QPalette::ColorGroup)group);
  793. break;
  794. default:
  795. func((QPalette::ColorGroup)QPalette::Disabled);
  796. func((QPalette::ColorGroup)QPalette::Active);
  797. func((QPalette::ColorGroup)QPalette::Inactive);
  798. }
  799. }
  800. struct CFParser {
  801. cf_parser cfp = {};
  802. inline ~CFParser() { cf_parser_free(&cfp); }
  803. inline operator cf_parser *() { return &cfp; }
  804. inline cf_parser *operator->() { return &cfp; }
  805. };
  806. void OBSApp::ParseExtraThemeData(const char *path)
  807. {
  808. BPtr<char> data = os_quick_read_utf8_file(path);
  809. QPalette pal = palette();
  810. CFParser cfp;
  811. int ret;
  812. cf_parser_parse(cfp, data, path);
  813. while (cf_go_to_token(cfp, "OBSTheme", nullptr)) {
  814. if (!cf_next_token(cfp))
  815. return;
  816. int group = -1;
  817. if (cf_token_is(cfp, ":")) {
  818. ret = cf_next_token_should_be(cfp, ":", nullptr,
  819. nullptr);
  820. if (ret != PARSE_SUCCESS)
  821. continue;
  822. if (!cf_next_token(cfp))
  823. return;
  824. if (cf_token_is(cfp, "disabled")) {
  825. group = QPalette::Disabled;
  826. } else if (cf_token_is(cfp, "active")) {
  827. group = QPalette::Active;
  828. } else if (cf_token_is(cfp, "inactive")) {
  829. group = QPalette::Inactive;
  830. } else {
  831. continue;
  832. }
  833. if (!cf_next_token(cfp))
  834. return;
  835. }
  836. if (!cf_token_is(cfp, "{"))
  837. continue;
  838. for (;;) {
  839. if (!cf_next_token(cfp))
  840. return;
  841. ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name",
  842. nullptr);
  843. if (ret != PARSE_SUCCESS)
  844. break;
  845. DStr name;
  846. dstr_copy_strref(name, &cfp->cur_token->str);
  847. ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
  848. if (ret != PARSE_SUCCESS)
  849. continue;
  850. if (!cf_next_token(cfp))
  851. return;
  852. const char *array;
  853. uint32_t color = 0;
  854. if (cf_token_is(cfp, "#")) {
  855. array = cfp->cur_token->str.array;
  856. color = strtol(array + 1, nullptr, 16);
  857. } else if (cf_token_is(cfp, "rgb")) {
  858. ret = cf_next_token_should_be(cfp, "(", ";",
  859. nullptr);
  860. if (ret != PARSE_SUCCESS)
  861. continue;
  862. if (!cf_next_token(cfp))
  863. return;
  864. array = cfp->cur_token->str.array;
  865. color |= strtol(array, nullptr, 10) << 16;
  866. ret = cf_next_token_should_be(cfp, ",", ";",
  867. nullptr);
  868. if (ret != PARSE_SUCCESS)
  869. continue;
  870. if (!cf_next_token(cfp))
  871. return;
  872. array = cfp->cur_token->str.array;
  873. color |= strtol(array, nullptr, 10) << 8;
  874. ret = cf_next_token_should_be(cfp, ",", ";",
  875. nullptr);
  876. if (ret != PARSE_SUCCESS)
  877. continue;
  878. if (!cf_next_token(cfp))
  879. return;
  880. array = cfp->cur_token->str.array;
  881. color |= strtol(array, nullptr, 10);
  882. } else if (cf_token_is(cfp, "white")) {
  883. color = 0xFFFFFF;
  884. } else if (cf_token_is(cfp, "black")) {
  885. color = 0;
  886. }
  887. if (!cf_go_to_token(cfp, ";", nullptr))
  888. return;
  889. AddExtraThemeColor(pal, group, name->array, color);
  890. }
  891. ret = cf_token_should_be(cfp, "}", "}", nullptr);
  892. if (ret != PARSE_SUCCESS)
  893. continue;
  894. }
  895. setPalette(pal);
  896. }
  897. bool OBSApp::SetTheme(std::string name, std::string path)
  898. {
  899. theme = name;
  900. /* Check user dir first, then preinstalled themes. */
  901. if (path == "") {
  902. char userDir[512];
  903. name = "themes/" + name + ".qss";
  904. string temp = "obs-studio/" + name;
  905. int ret = GetConfigPath(userDir, sizeof(userDir), temp.c_str());
  906. if (ret > 0 && QFile::exists(userDir)) {
  907. path = string(userDir);
  908. } else if (!GetDataFilePath(name.c_str(), path)) {
  909. OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
  910. return false;
  911. }
  912. }
  913. QString mpath = QString("file:///") + path.c_str();
  914. setPalette(defaultPalette);
  915. ParseExtraThemeData(path.c_str());
  916. setStyleSheet(mpath);
  917. QColor color = palette().text().color();
  918. themeDarkMode = !(color.redF() < 0.5);
  919. emit StyleChanged();
  920. return true;
  921. }
  922. bool OBSApp::InitTheme()
  923. {
  924. defaultPalette = palette();
  925. const char *themeName =
  926. config_get_string(globalConfig, "General", "CurrentTheme2");
  927. if (!themeName)
  928. /* Use deprecated "CurrentTheme" value if available */
  929. themeName = config_get_string(globalConfig, "General",
  930. "CurrentTheme");
  931. if (!themeName)
  932. /* Use deprecated "Theme" value if available */
  933. themeName = config_get_string(globalConfig, "General", "Theme");
  934. if (!themeName)
  935. themeName = DEFAULT_THEME;
  936. if (!themeName)
  937. themeName = "Dark";
  938. if (strcmp(themeName, "Default") == 0)
  939. themeName = "System";
  940. if (strcmp(themeName, "System") != 0 && SetTheme(themeName))
  941. return true;
  942. return SetTheme("System");
  943. }
  944. OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
  945. : QApplication(argc, argv), profilerNameStore(store)
  946. {
  947. /* fix float handling */
  948. #if defined(Q_OS_UNIX)
  949. if (!setlocale(LC_NUMERIC, "C"))
  950. blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale");
  951. #endif
  952. sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
  953. #ifndef __APPLE__
  954. setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
  955. #endif
  956. setDesktopFileName("com.obsproject.Studio");
  957. }
  958. OBSApp::~OBSApp()
  959. {
  960. #ifdef _WIN32
  961. bool disableAudioDucking =
  962. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  963. if (disableAudioDucking)
  964. DisableAudioDucking(false);
  965. #endif
  966. #ifdef __APPLE__
  967. bool vsyncDisabled =
  968. config_get_bool(globalConfig, "Video", "DisableOSXVSync");
  969. bool resetVSync =
  970. config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
  971. if (vsyncDisabled && resetVSync)
  972. EnableOSXVSync(true);
  973. #endif
  974. os_inhibit_sleep_set_active(sleepInhibitor, false);
  975. os_inhibit_sleep_destroy(sleepInhibitor);
  976. if (libobs_initialized)
  977. obs_shutdown();
  978. }
  979. static void move_basic_to_profiles(void)
  980. {
  981. char path[512];
  982. char new_path[512];
  983. os_glob_t *glob;
  984. /* if not first time use */
  985. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  986. return;
  987. if (!os_file_exists(path))
  988. return;
  989. /* if the profiles directory doesn't already exist */
  990. if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
  991. return;
  992. if (os_file_exists(new_path))
  993. return;
  994. if (os_mkdir(new_path) == MKDIR_ERROR)
  995. return;
  996. strcat(new_path, "/");
  997. strcat(new_path, Str("Untitled"));
  998. if (os_mkdir(new_path) == MKDIR_ERROR)
  999. return;
  1000. strcat(path, "/*.*");
  1001. if (os_glob(path, 0, &glob) != 0)
  1002. return;
  1003. strcpy(path, new_path);
  1004. for (size_t i = 0; i < glob->gl_pathc; i++) {
  1005. struct os_globent ent = glob->gl_pathv[i];
  1006. char *file;
  1007. if (ent.directory)
  1008. continue;
  1009. file = strrchr(ent.path, '/');
  1010. if (!file++)
  1011. continue;
  1012. if (astrcmpi(file, "scenes.json") == 0)
  1013. continue;
  1014. strcpy(new_path, path);
  1015. strcat(new_path, "/");
  1016. strcat(new_path, file);
  1017. os_rename(ent.path, new_path);
  1018. }
  1019. os_globfree(glob);
  1020. }
  1021. static void move_basic_to_scene_collections(void)
  1022. {
  1023. char path[512];
  1024. char new_path[512];
  1025. if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
  1026. return;
  1027. if (!os_file_exists(path))
  1028. return;
  1029. if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
  1030. return;
  1031. if (os_file_exists(new_path))
  1032. return;
  1033. if (os_mkdir(new_path) == MKDIR_ERROR)
  1034. return;
  1035. strcat(path, "/scenes.json");
  1036. strcat(new_path, "/");
  1037. strcat(new_path, Str("Untitled"));
  1038. strcat(new_path, ".json");
  1039. os_rename(path, new_path);
  1040. }
  1041. void OBSApp::AppInit()
  1042. {
  1043. ProfileScope("OBSApp::AppInit");
  1044. if (!MakeUserDirs())
  1045. throw "Failed to create required user directories";
  1046. if (!InitGlobalConfig())
  1047. throw "Failed to initialize global config";
  1048. if (!InitLocale())
  1049. throw "Failed to load locale";
  1050. if (!InitTheme())
  1051. throw "Failed to load theme";
  1052. config_set_default_string(globalConfig, "Basic", "Profile",
  1053. Str("Untitled"));
  1054. config_set_default_string(globalConfig, "Basic", "ProfileDir",
  1055. Str("Untitled"));
  1056. config_set_default_string(globalConfig, "Basic", "SceneCollection",
  1057. Str("Untitled"));
  1058. config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
  1059. Str("Untitled"));
  1060. config_set_default_bool(globalConfig, "Basic", "ConfigOnNewProfile",
  1061. true);
  1062. if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
  1063. config_set_string(globalConfig, "Basic", "Profile",
  1064. Str("Untitled"));
  1065. config_set_string(globalConfig, "Basic", "ProfileDir",
  1066. Str("Untitled"));
  1067. }
  1068. if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
  1069. config_set_string(globalConfig, "Basic", "SceneCollection",
  1070. Str("Untitled"));
  1071. config_set_string(globalConfig, "Basic", "SceneCollectionFile",
  1072. Str("Untitled"));
  1073. }
  1074. #ifdef _WIN32
  1075. bool disableAudioDucking =
  1076. config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
  1077. if (disableAudioDucking)
  1078. DisableAudioDucking(true);
  1079. #endif
  1080. #ifdef __APPLE__
  1081. if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
  1082. EnableOSXVSync(false);
  1083. #endif
  1084. UpdateHotkeyFocusSetting(false);
  1085. move_basic_to_profiles();
  1086. move_basic_to_scene_collections();
  1087. if (!MakeUserProfileDirs())
  1088. throw "Failed to create profile directories";
  1089. }
  1090. const char *OBSApp::GetRenderModule() const
  1091. {
  1092. const char *renderer =
  1093. config_get_string(globalConfig, "Video", "Renderer");
  1094. return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
  1095. }
  1096. static bool StartupOBS(const char *locale, profiler_name_store_t *store)
  1097. {
  1098. char path[512];
  1099. if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
  1100. return false;
  1101. return obs_startup(locale, path, store);
  1102. }
  1103. inline void OBSApp::ResetHotkeyState(bool inFocus)
  1104. {
  1105. obs_hotkey_enable_background_press(
  1106. (inFocus && enableHotkeysInFocus) ||
  1107. (!inFocus && enableHotkeysOutOfFocus));
  1108. }
  1109. void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
  1110. {
  1111. enableHotkeysInFocus = true;
  1112. enableHotkeysOutOfFocus = true;
  1113. const char *hotkeyFocusType =
  1114. config_get_string(globalConfig, "General", "HotkeyFocusType");
  1115. if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
  1116. enableHotkeysInFocus = false;
  1117. } else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
  1118. enableHotkeysOutOfFocus = false;
  1119. }
  1120. if (resetState)
  1121. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1122. }
  1123. void OBSApp::DisableHotkeys()
  1124. {
  1125. enableHotkeysInFocus = false;
  1126. enableHotkeysOutOfFocus = false;
  1127. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1128. }
  1129. Q_DECLARE_METATYPE(VoidFunc)
  1130. void OBSApp::Exec(VoidFunc func)
  1131. {
  1132. func();
  1133. }
  1134. static void ui_task_handler(obs_task_t task, void *param, bool wait)
  1135. {
  1136. auto doTask = [=]() {
  1137. /* to get clang-format to behave */
  1138. task(param);
  1139. };
  1140. QMetaObject::invokeMethod(App(), "Exec",
  1141. wait ? WaitConnection() : Qt::AutoConnection,
  1142. Q_ARG(VoidFunc, doTask));
  1143. }
  1144. bool OBSApp::OBSInit()
  1145. {
  1146. ProfileScope("OBSApp::OBSInit");
  1147. #if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
  1148. setAttribute(Qt::AA_UseHighDpiPixmaps);
  1149. #endif
  1150. qRegisterMetaType<VoidFunc>();
  1151. #if !defined(_WIN32) && !defined(__APPLE__)
  1152. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_GLX);
  1153. if (QApplication::platformName() == "xcb" && getenv("OBS_USE_EGL")) {
  1154. obs_set_nix_platform(OBS_NIX_PLATFORM_X11_EGL);
  1155. blog(LOG_INFO, "Using EGL/X11");
  1156. }
  1157. #ifdef ENABLE_WAYLAND
  1158. if (QApplication::platformName().contains("wayland")) {
  1159. obs_set_nix_platform(OBS_NIX_PLATFORM_WAYLAND);
  1160. setAttribute(Qt::AA_DontCreateNativeWidgetSiblings);
  1161. blog(LOG_INFO, "Platform: Wayland");
  1162. }
  1163. #endif
  1164. QPlatformNativeInterface *native =
  1165. QGuiApplication::platformNativeInterface();
  1166. obs_set_nix_platform_display(
  1167. native->nativeResourceForIntegration("display"));
  1168. #endif
  1169. if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
  1170. return false;
  1171. libobs_initialized = true;
  1172. obs_set_ui_task_handler(ui_task_handler);
  1173. #if defined(_WIN32) || defined(__APPLE__)
  1174. bool browserHWAccel =
  1175. config_get_bool(globalConfig, "General", "BrowserHWAccel");
  1176. OBSDataAutoRelease settings = obs_data_create();
  1177. obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
  1178. obs_apply_private_data(settings);
  1179. blog(LOG_INFO, "Current Date/Time: %s",
  1180. CurrentDateTimeString().c_str());
  1181. blog(LOG_INFO, "Browser Hardware Acceleration: %s",
  1182. browserHWAccel ? "true" : "false");
  1183. #endif
  1184. #ifdef _WIN32
  1185. bool hideFromCapture = config_get_bool(globalConfig, "BasicWindow",
  1186. "HideOBSWindowsFromCapture");
  1187. blog(LOG_INFO, "Hide OBS windows from screen capture: %s",
  1188. hideFromCapture ? "true" : "false");
  1189. #endif
  1190. blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(),
  1191. QT_VERSION_STR);
  1192. blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
  1193. setQuitOnLastWindowClosed(false);
  1194. mainWindow = new OBSBasic();
  1195. mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
  1196. connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
  1197. mainWindow->OBSInit();
  1198. connect(this, &QGuiApplication::applicationStateChanged,
  1199. [this](Qt::ApplicationState state) {
  1200. ResetHotkeyState(state == Qt::ApplicationActive);
  1201. });
  1202. ResetHotkeyState(applicationState() == Qt::ApplicationActive);
  1203. return true;
  1204. }
  1205. string OBSApp::GetVersionString() const
  1206. {
  1207. stringstream ver;
  1208. #ifdef HAVE_OBSCONFIG_H
  1209. ver << OBS_VERSION;
  1210. #else
  1211. ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
  1212. << LIBOBS_API_PATCH_VER;
  1213. #endif
  1214. ver << " (";
  1215. #ifdef _WIN32
  1216. if (sizeof(void *) == 8)
  1217. ver << "64-bit, ";
  1218. else
  1219. ver << "32-bit, ";
  1220. ver << "windows)";
  1221. #elif __APPLE__
  1222. ver << "mac)";
  1223. #elif __OpenBSD__
  1224. ver << "openbsd)";
  1225. #elif __FreeBSD__
  1226. ver << "freebsd)";
  1227. #else /* assume linux for the time being */
  1228. ver << "linux)";
  1229. #endif
  1230. return ver.str();
  1231. }
  1232. bool OBSApp::IsPortableMode()
  1233. {
  1234. return portable_mode;
  1235. }
  1236. bool OBSApp::IsUpdaterDisabled()
  1237. {
  1238. return opt_disable_updater;
  1239. }
  1240. bool OBSApp::IsMissingFilesCheckDisabled()
  1241. {
  1242. return opt_disable_missing_files_check;
  1243. }
  1244. #ifdef __APPLE__
  1245. #define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
  1246. #define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
  1247. #elif _WIN32
  1248. #define INPUT_AUDIO_SOURCE "wasapi_input_capture"
  1249. #define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
  1250. #else
  1251. #define INPUT_AUDIO_SOURCE "pulse_input_capture"
  1252. #define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
  1253. #endif
  1254. const char *OBSApp::InputAudioSource() const
  1255. {
  1256. return INPUT_AUDIO_SOURCE;
  1257. }
  1258. const char *OBSApp::OutputAudioSource() const
  1259. {
  1260. return OUTPUT_AUDIO_SOURCE;
  1261. }
  1262. const char *OBSApp::GetLastLog() const
  1263. {
  1264. return lastLogFile.c_str();
  1265. }
  1266. const char *OBSApp::GetCurrentLog() const
  1267. {
  1268. return currentLogFile.c_str();
  1269. }
  1270. const char *OBSApp::GetLastCrashLog() const
  1271. {
  1272. return lastCrashLogFile.c_str();
  1273. }
  1274. bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
  1275. {
  1276. for (obs_frontend_translate_ui_cb cb : translatorHooks) {
  1277. if (cb(lookupVal, out))
  1278. return true;
  1279. }
  1280. return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
  1281. }
  1282. // Global handler to receive all QEvent::Show events so we can apply
  1283. // display affinity on any newly created windows and dialogs without
  1284. // caring where they are coming from (e.g. plugins).
  1285. bool OBSApp::notify(QObject *receiver, QEvent *e)
  1286. {
  1287. QWidget *w;
  1288. QWindow *window;
  1289. int windowType;
  1290. if (!receiver->isWidgetType())
  1291. goto skip;
  1292. if (e->type() != QEvent::Show)
  1293. goto skip;
  1294. w = qobject_cast<QWidget *>(receiver);
  1295. if (!w->isWindow())
  1296. goto skip;
  1297. window = w->windowHandle();
  1298. if (!window)
  1299. goto skip;
  1300. windowType = window->flags() & Qt::WindowType::WindowType_Mask;
  1301. if (windowType == Qt::WindowType::Dialog ||
  1302. windowType == Qt::WindowType::Window ||
  1303. windowType == Qt::WindowType::Tool) {
  1304. OBSBasic *main = reinterpret_cast<OBSBasic *>(GetMainWindow());
  1305. if (main)
  1306. main->SetDisplayAffinity(window);
  1307. }
  1308. skip:
  1309. return QApplication::notify(receiver, e);
  1310. }
  1311. QString OBSTranslator::translate(const char *context, const char *sourceText,
  1312. const char *disambiguation, int n) const
  1313. {
  1314. const char *out = nullptr;
  1315. if (!App()->TranslateString(sourceText, &out))
  1316. return QString(sourceText);
  1317. UNUSED_PARAMETER(context);
  1318. UNUSED_PARAMETER(disambiguation);
  1319. UNUSED_PARAMETER(n);
  1320. return QT_UTF8(out);
  1321. }
  1322. static bool get_token(lexer *lex, string &str, base_token_type type)
  1323. {
  1324. base_token token;
  1325. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1326. return false;
  1327. if (token.type != type)
  1328. return false;
  1329. str.assign(token.text.array, token.text.len);
  1330. return true;
  1331. }
  1332. static bool expect_token(lexer *lex, const char *str, base_token_type type)
  1333. {
  1334. base_token token;
  1335. if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
  1336. return false;
  1337. if (token.type != type)
  1338. return false;
  1339. return strref_cmp(&token.text, str) == 0;
  1340. }
  1341. static uint64_t convert_log_name(bool has_prefix, const char *name)
  1342. {
  1343. BaseLexer lex;
  1344. string year, month, day, hour, minute, second;
  1345. lexer_start(lex, name);
  1346. if (has_prefix) {
  1347. string temp;
  1348. if (!get_token(lex, temp, BASETOKEN_ALPHA))
  1349. return 0;
  1350. }
  1351. if (!get_token(lex, year, BASETOKEN_DIGIT))
  1352. return 0;
  1353. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1354. return 0;
  1355. if (!get_token(lex, month, BASETOKEN_DIGIT))
  1356. return 0;
  1357. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1358. return 0;
  1359. if (!get_token(lex, day, BASETOKEN_DIGIT))
  1360. return 0;
  1361. if (!get_token(lex, hour, BASETOKEN_DIGIT))
  1362. return 0;
  1363. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1364. return 0;
  1365. if (!get_token(lex, minute, BASETOKEN_DIGIT))
  1366. return 0;
  1367. if (!expect_token(lex, "-", BASETOKEN_OTHER))
  1368. return 0;
  1369. if (!get_token(lex, second, BASETOKEN_DIGIT))
  1370. return 0;
  1371. stringstream timestring;
  1372. timestring << year << month << day << hour << minute << second;
  1373. return std::stoull(timestring.str());
  1374. }
  1375. static void delete_oldest_file(bool has_prefix, const char *location)
  1376. {
  1377. BPtr<char> logDir(GetConfigPathPtr(location));
  1378. string oldestLog;
  1379. uint64_t oldest_ts = (uint64_t)-1;
  1380. struct os_dirent *entry;
  1381. unsigned int maxLogs = (unsigned int)config_get_uint(
  1382. App()->GlobalConfig(), "General", "MaxLogs");
  1383. os_dir_t *dir = os_opendir(logDir);
  1384. if (dir) {
  1385. unsigned int count = 0;
  1386. while ((entry = os_readdir(dir)) != NULL) {
  1387. if (entry->directory || *entry->d_name == '.')
  1388. continue;
  1389. uint64_t ts =
  1390. convert_log_name(has_prefix, entry->d_name);
  1391. if (ts) {
  1392. if (ts < oldest_ts) {
  1393. oldestLog = entry->d_name;
  1394. oldest_ts = ts;
  1395. }
  1396. count++;
  1397. }
  1398. }
  1399. os_closedir(dir);
  1400. if (count > maxLogs) {
  1401. stringstream delPath;
  1402. delPath << logDir << "/" << oldestLog;
  1403. os_unlink(delPath.str().c_str());
  1404. }
  1405. }
  1406. }
  1407. static void get_last_log(bool has_prefix, const char *subdir_to_use,
  1408. std::string &last)
  1409. {
  1410. BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
  1411. struct os_dirent *entry;
  1412. os_dir_t *dir = os_opendir(logDir);
  1413. uint64_t highest_ts = 0;
  1414. if (dir) {
  1415. while ((entry = os_readdir(dir)) != NULL) {
  1416. if (entry->directory || *entry->d_name == '.')
  1417. continue;
  1418. uint64_t ts =
  1419. convert_log_name(has_prefix, entry->d_name);
  1420. if (ts > highest_ts) {
  1421. last = entry->d_name;
  1422. highest_ts = ts;
  1423. }
  1424. }
  1425. os_closedir(dir);
  1426. }
  1427. }
  1428. string GenerateTimeDateFilename(const char *extension, bool noSpace)
  1429. {
  1430. time_t now = time(0);
  1431. char file[256] = {};
  1432. struct tm *cur_time;
  1433. cur_time = localtime(&now);
  1434. snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
  1435. cur_time->tm_year + 1900, cur_time->tm_mon + 1,
  1436. cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
  1437. cur_time->tm_min, cur_time->tm_sec, extension);
  1438. return string(file);
  1439. }
  1440. string GenerateSpecifiedFilename(const char *extension, bool noSpace,
  1441. const char *format)
  1442. {
  1443. BPtr<char> filename =
  1444. os_generate_formatted_filename(extension, !noSpace, format);
  1445. return string(filename);
  1446. }
  1447. static void FindBestFilename(string &strPath, bool noSpace)
  1448. {
  1449. int num = 2;
  1450. if (!os_file_exists(strPath.c_str()))
  1451. return;
  1452. const char *ext = strrchr(strPath.c_str(), '.');
  1453. if (!ext)
  1454. return;
  1455. int extStart = int(ext - strPath.c_str());
  1456. for (;;) {
  1457. string testPath = strPath;
  1458. string numStr;
  1459. numStr = noSpace ? "_" : " (";
  1460. numStr += to_string(num++);
  1461. if (!noSpace)
  1462. numStr += ")";
  1463. testPath.insert(extStart, numStr);
  1464. if (!os_file_exists(testPath.c_str())) {
  1465. strPath = testPath;
  1466. break;
  1467. }
  1468. }
  1469. }
  1470. static void ensure_directory_exists(string &path)
  1471. {
  1472. replace(path.begin(), path.end(), '\\', '/');
  1473. size_t last = path.rfind('/');
  1474. if (last == string::npos)
  1475. return;
  1476. string directory = path.substr(0, last);
  1477. os_mkdirs(directory.c_str());
  1478. }
  1479. static void remove_reserved_file_characters(string &s)
  1480. {
  1481. replace(s.begin(), s.end(), '\\', '/');
  1482. replace(s.begin(), s.end(), '*', '_');
  1483. replace(s.begin(), s.end(), '?', '_');
  1484. replace(s.begin(), s.end(), '"', '_');
  1485. replace(s.begin(), s.end(), '|', '_');
  1486. replace(s.begin(), s.end(), ':', '_');
  1487. replace(s.begin(), s.end(), '>', '_');
  1488. replace(s.begin(), s.end(), '<', '_');
  1489. }
  1490. string GetFormatString(const char *format, const char *prefix,
  1491. const char *suffix)
  1492. {
  1493. string f;
  1494. f = format;
  1495. if (prefix && *prefix) {
  1496. string str_prefix = prefix;
  1497. if (str_prefix.back() != ' ')
  1498. str_prefix += " ";
  1499. size_t insert_pos = 0;
  1500. size_t tmp;
  1501. tmp = f.find_last_of('/');
  1502. if (tmp != string::npos && tmp > insert_pos)
  1503. insert_pos = tmp + 1;
  1504. tmp = f.find_last_of('\\');
  1505. if (tmp != string::npos && tmp > insert_pos)
  1506. insert_pos = tmp + 1;
  1507. f.insert(insert_pos, str_prefix);
  1508. }
  1509. if (suffix && *suffix) {
  1510. if (*suffix != ' ')
  1511. f += " ";
  1512. f += suffix;
  1513. }
  1514. remove_reserved_file_characters(f);
  1515. return f;
  1516. }
  1517. string GetOutputFilename(const char *path, const char *ext, bool noSpace,
  1518. bool overwrite, const char *format)
  1519. {
  1520. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  1521. os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr;
  1522. if (!dir) {
  1523. if (main->isVisible())
  1524. OBSMessageBox::warning(main,
  1525. QTStr("Output.BadPath.Title"),
  1526. QTStr("Output.BadPath.Text"));
  1527. else
  1528. main->SysTrayNotify(QTStr("Output.BadPath.Text"),
  1529. QSystemTrayIcon::Warning);
  1530. return "";
  1531. }
  1532. os_closedir(dir);
  1533. string strPath;
  1534. strPath += path;
  1535. char lastChar = strPath.back();
  1536. if (lastChar != '/' && lastChar != '\\')
  1537. strPath += "/";
  1538. strPath += GenerateSpecifiedFilename(ext, noSpace, format);
  1539. ensure_directory_exists(strPath);
  1540. if (!overwrite)
  1541. FindBestFilename(strPath, noSpace);
  1542. return strPath;
  1543. }
  1544. vector<pair<string, string>> GetLocaleNames()
  1545. {
  1546. string path;
  1547. if (!GetDataFilePath("locale.ini", path))
  1548. throw "Could not find locale.ini path";
  1549. ConfigFile ini;
  1550. if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
  1551. throw "Could not open locale.ini";
  1552. size_t sections = config_num_sections(ini);
  1553. vector<pair<string, string>> names;
  1554. names.reserve(sections);
  1555. for (size_t i = 0; i < sections; i++) {
  1556. const char *tag = config_get_section(ini, i);
  1557. const char *name = config_get_string(ini, tag, "Name");
  1558. names.emplace_back(tag, name);
  1559. }
  1560. return names;
  1561. }
  1562. static void create_log_file(fstream &logFile)
  1563. {
  1564. stringstream dst;
  1565. get_last_log(false, "obs-studio/logs", lastLogFile);
  1566. #ifdef _WIN32
  1567. get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
  1568. #endif
  1569. currentLogFile = GenerateTimeDateFilename("txt");
  1570. dst << "obs-studio/logs/" << currentLogFile.c_str();
  1571. BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
  1572. #ifdef _WIN32
  1573. BPtr<wchar_t> wpath;
  1574. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1575. logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
  1576. #else
  1577. logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
  1578. #endif
  1579. if (logFile.is_open()) {
  1580. delete_oldest_file(false, "obs-studio/logs");
  1581. base_set_log_handler(do_log, &logFile);
  1582. } else {
  1583. blog(LOG_ERROR, "Failed to open log file");
  1584. }
  1585. }
  1586. static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
  1587. profiler_name_store_free(store);
  1588. };
  1589. using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
  1590. decltype(ProfilerNameStoreRelease)>;
  1591. ProfilerNameStore CreateNameStore()
  1592. {
  1593. return ProfilerNameStore{profiler_name_store_create(),
  1594. ProfilerNameStoreRelease};
  1595. }
  1596. static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
  1597. profile_snapshot_free(snap);
  1598. };
  1599. using ProfilerSnapshot =
  1600. std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;
  1601. ProfilerSnapshot GetSnapshot()
  1602. {
  1603. return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
  1604. }
  1605. static void SaveProfilerData(const ProfilerSnapshot &snap)
  1606. {
  1607. if (currentLogFile.empty())
  1608. return;
  1609. auto pos = currentLogFile.rfind('.');
  1610. if (pos == currentLogFile.npos)
  1611. return;
  1612. #define LITERAL_SIZE(x) x, (sizeof(x) - 1)
  1613. ostringstream dst;
  1614. dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
  1615. dst.write(currentLogFile.c_str(), pos);
  1616. dst.write(LITERAL_SIZE(".csv.gz"));
  1617. #undef LITERAL_SIZE
  1618. BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
  1619. if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
  1620. blog(LOG_WARNING, "Could not save profiler data to '%s'",
  1621. static_cast<const char *>(path));
  1622. }
  1623. static auto ProfilerFree = [](void *) {
  1624. profiler_stop();
  1625. auto snap = GetSnapshot();
  1626. profiler_print(snap.get());
  1627. profiler_print_time_between_calls(snap.get());
  1628. SaveProfilerData(snap);
  1629. profiler_free();
  1630. };
  1631. QAccessibleInterface *accessibleFactory(const QString &classname,
  1632. QObject *object)
  1633. {
  1634. if (classname == QLatin1String("VolumeSlider") && object &&
  1635. object->isWidgetType())
  1636. return new VolumeAccessibleInterface(
  1637. static_cast<QWidget *>(object));
  1638. return nullptr;
  1639. }
  1640. static const char *run_program_init = "run_program_init";
  1641. static int run_program(fstream &logFile, int argc, char *argv[])
  1642. {
  1643. int ret = -1;
  1644. auto profilerNameStore = CreateNameStore();
  1645. std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
  1646. static_cast<void *>(&ProfilerFree), ProfilerFree);
  1647. profiler_start();
  1648. profile_register_root(run_program_init, 0);
  1649. ScopeProfiler prof{run_program_init};
  1650. #if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
  1651. QGuiApplication::setAttribute(opt_disable_high_dpi_scaling
  1652. ? Qt::AA_DisableHighDpiScaling
  1653. : Qt::AA_EnableHighDpiScaling);
  1654. #endif
  1655. #if (QT_VERSION >= QT_VERSION_CHECK(5, 14, 0)) && defined(_WIN32)
  1656. QGuiApplication::setHighDpiScaleFactorRoundingPolicy(
  1657. Qt::HighDpiScaleFactorRoundingPolicy::PassThrough);
  1658. #endif
  1659. QCoreApplication::addLibraryPath(".");
  1660. #if __APPLE__
  1661. InstallNSApplicationSubclass();
  1662. if (!isInBundle()) {
  1663. blog(LOG_ERROR,
  1664. "OBS cannot be run as a standalone binary on macOS. Run the Application bundle instead.");
  1665. return ret;
  1666. }
  1667. #endif
  1668. #if !defined(_WIN32) && !defined(__APPLE__) && defined(USE_XDG) && \
  1669. defined(ENABLE_WAYLAND)
  1670. /* NOTE: Qt doesn't use the Wayland platform on GNOME, so we have to
  1671. * force it using the QT_QPA_PLATFORM env var. It's still possible to
  1672. * use other QPA platforms using this env var, or the -platform command
  1673. * line option. */
  1674. const char *session_type = getenv("XDG_SESSION_TYPE");
  1675. if (session_type && strcmp(session_type, "wayland") == 0)
  1676. setenv("QT_QPA_PLATFORM", "wayland", false);
  1677. #endif
  1678. OBSApp program(argc, argv, profilerNameStore.get());
  1679. try {
  1680. QAccessible::installFactory(accessibleFactory);
  1681. bool created_log = false;
  1682. program.AppInit();
  1683. delete_oldest_file(false, "obs-studio/profiler_data");
  1684. OBSTranslator translator;
  1685. program.installTranslator(&translator);
  1686. /* --------------------------------------- */
  1687. /* check and warn if already running */
  1688. bool cancel_launch = false;
  1689. bool already_running = false;
  1690. #ifdef _WIN32
  1691. RunOnceMutex rom =
  1692. #endif
  1693. CheckIfAlreadyRunning(already_running);
  1694. if (!already_running) {
  1695. goto run;
  1696. }
  1697. if (!multi) {
  1698. QMessageBox::StandardButtons buttons(
  1699. QMessageBox::Yes | QMessageBox::Cancel);
  1700. QMessageBox mb(QMessageBox::Question,
  1701. QTStr("AlreadyRunning.Title"),
  1702. QTStr("AlreadyRunning.Text"), buttons,
  1703. nullptr);
  1704. mb.setButtonText(QMessageBox::Yes,
  1705. QTStr("AlreadyRunning.LaunchAnyway"));
  1706. mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
  1707. mb.setDefaultButton(QMessageBox::Cancel);
  1708. QMessageBox::StandardButton button;
  1709. button = (QMessageBox::StandardButton)mb.exec();
  1710. cancel_launch = button == QMessageBox::Cancel;
  1711. }
  1712. if (cancel_launch)
  1713. return 0;
  1714. if (!created_log) {
  1715. create_log_file(logFile);
  1716. created_log = true;
  1717. }
  1718. if (multi) {
  1719. blog(LOG_INFO, "User enabled --multi flag and is now "
  1720. "running multiple instances of OBS.");
  1721. } else {
  1722. blog(LOG_WARNING, "================================");
  1723. blog(LOG_WARNING, "Warning: OBS is already running!");
  1724. blog(LOG_WARNING, "================================");
  1725. blog(LOG_WARNING, "User is now running multiple "
  1726. "instances of OBS!");
  1727. }
  1728. /* --------------------------------------- */
  1729. run:
  1730. #if !defined(_WIN32) && !defined(__APPLE__) && !defined(__FreeBSD__)
  1731. // Mounted by termina during chromeOS linux container startup
  1732. // https://chromium.googlesource.com/chromiumos/overlays/board-overlays/+/master/project-termina/chromeos-base/termina-lxd-scripts/files/lxd_setup.sh
  1733. os_dir_t *crosDir = os_opendir("/opt/google/cros-containers");
  1734. if (crosDir) {
  1735. QMessageBox::StandardButtons buttons(QMessageBox::Ok);
  1736. QMessageBox mb(QMessageBox::Critical,
  1737. QTStr("ChromeOS.Title"),
  1738. QTStr("ChromeOS.Text"), buttons,
  1739. nullptr);
  1740. mb.exec();
  1741. return 0;
  1742. }
  1743. #endif
  1744. if (!created_log) {
  1745. create_log_file(logFile);
  1746. created_log = true;
  1747. }
  1748. #ifdef __APPLE__
  1749. bool rosettaTranslated = ProcessIsRosettaTranslated();
  1750. blog(LOG_INFO, "Rosetta translation used: %s",
  1751. rosettaTranslated ? "true" : "false");
  1752. #endif
  1753. #ifdef _WIN32
  1754. if (IsRunningOnWine()) {
  1755. QMessageBox mb(QMessageBox::Question,
  1756. QTStr("Wine.Title"), QTStr("Wine.Text"));
  1757. mb.setTextFormat(Qt::RichText);
  1758. mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"),
  1759. QMessageBox::AcceptRole);
  1760. QPushButton *closeButton =
  1761. mb.addButton(QMessageBox::Close);
  1762. mb.setDefaultButton(closeButton);
  1763. mb.exec();
  1764. if (mb.clickedButton() == closeButton)
  1765. return 0;
  1766. }
  1767. #endif
  1768. if (argc > 1) {
  1769. stringstream stor;
  1770. stor << argv[1];
  1771. for (int i = 2; i < argc; ++i) {
  1772. stor << " " << argv[i];
  1773. }
  1774. blog(LOG_INFO, "Command Line Arguments: %s",
  1775. stor.str().c_str());
  1776. }
  1777. if (!program.OBSInit())
  1778. return 0;
  1779. prof.Stop();
  1780. ret = program.exec();
  1781. } catch (const char *error) {
  1782. blog(LOG_ERROR, "%s", error);
  1783. OBSErrorBox(nullptr, "%s", error);
  1784. }
  1785. if (restart)
  1786. QProcess::startDetached(qApp->arguments()[0],
  1787. qApp->arguments());
  1788. return ret;
  1789. }
  1790. #define MAX_CRASH_REPORT_SIZE (150 * 1024)
  1791. #ifdef _WIN32
  1792. #define CRASH_MESSAGE \
  1793. "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
  1794. "to the clipboard? The crash log will still be saved to:\n\n%s"
  1795. static void main_crash_handler(const char *format, va_list args, void *param)
  1796. {
  1797. char *text = new char[MAX_CRASH_REPORT_SIZE];
  1798. vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
  1799. text[MAX_CRASH_REPORT_SIZE - 1] = 0;
  1800. string crashFilePath = "obs-studio/crashes";
  1801. delete_oldest_file(true, crashFilePath.c_str());
  1802. string name = crashFilePath + "/";
  1803. name += "Crash " + GenerateTimeDateFilename("txt");
  1804. BPtr<char> path(GetConfigPathPtr(name.c_str()));
  1805. fstream file;
  1806. #ifdef _WIN32
  1807. BPtr<wchar_t> wpath;
  1808. os_utf8_to_wcs_ptr(path, 0, &wpath);
  1809. file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
  1810. ios_base::binary);
  1811. #else
  1812. file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
  1813. ios_base::binary);
  1814. #endif
  1815. file << text;
  1816. file.close();
  1817. string pathString(path.Get());
  1818. #ifdef _WIN32
  1819. std::replace(pathString.begin(), pathString.end(), '/', '\\');
  1820. #endif
  1821. string absolutePath =
  1822. canonical(filesystem::path(pathString)).u8string();
  1823. size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());
  1824. unique_ptr<char[]> message_buffer(new char[size + 1]);
  1825. snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
  1826. absolutePath.c_str());
  1827. string finalMessage =
  1828. string(message_buffer.get(), message_buffer.get() + size);
  1829. int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
  1830. MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
  1831. if (ret == IDYES) {
  1832. size_t len = strlen(text);
  1833. HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
  1834. memcpy(GlobalLock(mem), text, len);
  1835. GlobalUnlock(mem);
  1836. OpenClipboard(0);
  1837. EmptyClipboard();
  1838. SetClipboardData(CF_TEXT, mem);
  1839. CloseClipboard();
  1840. }
  1841. exit(-1);
  1842. UNUSED_PARAMETER(param);
  1843. }
  1844. static void load_debug_privilege(void)
  1845. {
  1846. const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
  1847. TOKEN_PRIVILEGES tp;
  1848. HANDLE token;
  1849. LUID val;
  1850. if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
  1851. return;
  1852. }
  1853. if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
  1854. tp.PrivilegeCount = 1;
  1855. tp.Privileges[0].Luid = val;
  1856. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1857. AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1858. NULL);
  1859. }
  1860. if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
  1861. tp.PrivilegeCount = 1;
  1862. tp.Privileges[0].Luid = val;
  1863. tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
  1864. if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
  1865. NULL)) {
  1866. blog(LOG_INFO, "Could not set privilege to "
  1867. "increase GPU priority");
  1868. }
  1869. }
  1870. CloseHandle(token);
  1871. }
  1872. #endif
  1873. #ifdef __APPLE__
  1874. #define BASE_PATH ".."
  1875. #else
  1876. #define BASE_PATH "../.."
  1877. #endif
  1878. #define CONFIG_PATH BASE_PATH "/config"
  1879. #ifndef LINUX_PORTABLE
  1880. #define LINUX_PORTABLE 0
  1881. #endif
  1882. int GetConfigPath(char *path, size_t size, const char *name)
  1883. {
  1884. if (LINUX_PORTABLE && portable_mode) {
  1885. if (name && *name) {
  1886. return snprintf(path, size, CONFIG_PATH "/%s", name);
  1887. } else {
  1888. return snprintf(path, size, CONFIG_PATH);
  1889. }
  1890. } else {
  1891. return os_get_config_path(path, size, name);
  1892. }
  1893. }
  1894. char *GetConfigPathPtr(const char *name)
  1895. {
  1896. if (LINUX_PORTABLE && portable_mode) {
  1897. char path[512];
  1898. if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
  1899. return bstrdup(path);
  1900. } else {
  1901. return NULL;
  1902. }
  1903. } else {
  1904. return os_get_config_path_ptr(name);
  1905. }
  1906. }
  1907. int GetProgramDataPath(char *path, size_t size, const char *name)
  1908. {
  1909. return os_get_program_data_path(path, size, name);
  1910. }
  1911. char *GetProgramDataPathPtr(const char *name)
  1912. {
  1913. return os_get_program_data_path_ptr(name);
  1914. }
  1915. bool GetFileSafeName(const char *name, std::string &file)
  1916. {
  1917. size_t base_len = strlen(name);
  1918. size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
  1919. std::wstring wfile;
  1920. if (!len)
  1921. return false;
  1922. wfile.resize(len);
  1923. os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
  1924. for (size_t i = wfile.size(); i > 0; i--) {
  1925. size_t im1 = i - 1;
  1926. if (iswspace(wfile[im1])) {
  1927. wfile[im1] = '_';
  1928. } else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
  1929. wfile.erase(im1, 1);
  1930. }
  1931. }
  1932. if (wfile.size() == 0)
  1933. wfile = L"characters_only";
  1934. len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
  1935. if (!len)
  1936. return false;
  1937. file.resize(len);
  1938. os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
  1939. return true;
  1940. }
  1941. bool GetClosestUnusedFileName(std::string &path, const char *extension)
  1942. {
  1943. size_t len = path.size();
  1944. if (extension) {
  1945. path += ".";
  1946. path += extension;
  1947. }
  1948. if (!os_file_exists(path.c_str()))
  1949. return true;
  1950. int index = 1;
  1951. do {
  1952. path.resize(len);
  1953. path += std::to_string(++index);
  1954. if (extension) {
  1955. path += ".";
  1956. path += extension;
  1957. }
  1958. } while (os_file_exists(path.c_str()));
  1959. return true;
  1960. }
  1961. bool GetUnusedSceneCollectionFile(std::string &name, std::string &file)
  1962. {
  1963. char path[512];
  1964. int ret;
  1965. if (!GetFileSafeName(name.c_str(), file)) {
  1966. blog(LOG_WARNING, "Failed to create safe file name for '%s'",
  1967. name.c_str());
  1968. return false;
  1969. }
  1970. ret = GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes/");
  1971. if (ret <= 0) {
  1972. blog(LOG_WARNING, "Failed to get scene collection config path");
  1973. return false;
  1974. }
  1975. file.insert(0, path);
  1976. if (!GetClosestUnusedFileName(file, "json")) {
  1977. blog(LOG_WARNING, "Failed to get closest file name for %s",
  1978. file.c_str());
  1979. return false;
  1980. }
  1981. file.erase(file.size() - 5, 5);
  1982. file.erase(0, strlen(path));
  1983. return true;
  1984. }
  1985. bool WindowPositionValid(QRect rect)
  1986. {
  1987. for (QScreen *screen : QGuiApplication::screens()) {
  1988. if (screen->availableGeometry().intersects(rect))
  1989. return true;
  1990. }
  1991. return false;
  1992. }
  1993. static inline bool arg_is(const char *arg, const char *long_form,
  1994. const char *short_form)
  1995. {
  1996. return (long_form && strcmp(arg, long_form) == 0) ||
  1997. (short_form && strcmp(arg, short_form) == 0);
  1998. }
  1999. #if !defined(_WIN32) && !defined(__APPLE__)
  2000. #define IS_UNIX 1
  2001. #endif
  2002. /* if using XDG and was previously using an older build of OBS, move config
  2003. * files to XDG directory */
  2004. #if defined(USE_XDG) && defined(IS_UNIX)
  2005. static void move_to_xdg(void)
  2006. {
  2007. char old_path[512];
  2008. char new_path[512];
  2009. char *home = getenv("HOME");
  2010. if (!home)
  2011. return;
  2012. if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
  2013. return;
  2014. /* make base xdg path if it doesn't already exist */
  2015. if (GetConfigPath(new_path, 512, "") <= 0)
  2016. return;
  2017. if (os_mkdirs(new_path) == MKDIR_ERROR)
  2018. return;
  2019. if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
  2020. return;
  2021. if (os_file_exists(old_path) && !os_file_exists(new_path)) {
  2022. rename(old_path, new_path);
  2023. }
  2024. }
  2025. #endif
  2026. static bool update_ffmpeg_output(ConfigFile &config)
  2027. {
  2028. if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
  2029. return false;
  2030. const char *url = config_get_string(config, "AdvOut", "FFURL");
  2031. if (!url)
  2032. return false;
  2033. bool isActualURL = strstr(url, "://") != nullptr;
  2034. if (isActualURL)
  2035. return false;
  2036. string urlStr = url;
  2037. string extension;
  2038. for (size_t i = urlStr.length(); i > 0; i--) {
  2039. size_t idx = i - 1;
  2040. if (urlStr[idx] == '.') {
  2041. extension = &urlStr[i];
  2042. }
  2043. if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
  2044. urlStr[idx] = 0;
  2045. break;
  2046. }
  2047. }
  2048. if (urlStr.empty() || extension.empty())
  2049. return false;
  2050. config_remove_value(config, "AdvOut", "FFURL");
  2051. config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
  2052. config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
  2053. config_set_bool(config, "AdvOut", "FFOutputToFile", true);
  2054. return true;
  2055. }
  2056. static bool move_reconnect_settings(ConfigFile &config, const char *sec)
  2057. {
  2058. bool changed = false;
  2059. if (config_has_user_value(config, sec, "Reconnect")) {
  2060. bool reconnect = config_get_bool(config, sec, "Reconnect");
  2061. config_set_bool(config, "Output", "Reconnect", reconnect);
  2062. changed = true;
  2063. }
  2064. if (config_has_user_value(config, sec, "RetryDelay")) {
  2065. int delay = (int)config_get_uint(config, sec, "RetryDelay");
  2066. config_set_uint(config, "Output", "RetryDelay", delay);
  2067. changed = true;
  2068. }
  2069. if (config_has_user_value(config, sec, "MaxRetries")) {
  2070. int retries = (int)config_get_uint(config, sec, "MaxRetries");
  2071. config_set_uint(config, "Output", "MaxRetries", retries);
  2072. changed = true;
  2073. }
  2074. return changed;
  2075. }
  2076. static bool update_reconnect(ConfigFile &config)
  2077. {
  2078. if (!config_has_user_value(config, "Output", "Mode"))
  2079. return false;
  2080. const char *mode = config_get_string(config, "Output", "Mode");
  2081. if (!mode)
  2082. return false;
  2083. const char *section = (strcmp(mode, "Advanced") == 0) ? "AdvOut"
  2084. : "SimpleOutput";
  2085. if (move_reconnect_settings(config, section)) {
  2086. config_remove_value(config, "SimpleOutput", "Reconnect");
  2087. config_remove_value(config, "SimpleOutput", "RetryDelay");
  2088. config_remove_value(config, "SimpleOutput", "MaxRetries");
  2089. config_remove_value(config, "AdvOut", "Reconnect");
  2090. config_remove_value(config, "AdvOut", "RetryDelay");
  2091. config_remove_value(config, "AdvOut", "MaxRetries");
  2092. return true;
  2093. }
  2094. return false;
  2095. }
  2096. static void convert_x264_settings(obs_data_t *data)
  2097. {
  2098. bool use_bufsize = obs_data_get_bool(data, "use_bufsize");
  2099. if (use_bufsize) {
  2100. int buffer_size = (int)obs_data_get_int(data, "buffer_size");
  2101. if (buffer_size == 0)
  2102. obs_data_set_string(data, "rate_control", "CRF");
  2103. }
  2104. }
  2105. static void convert_14_2_encoder_setting(const char *encoder, const char *file)
  2106. {
  2107. OBSDataAutoRelease data =
  2108. obs_data_create_from_json_file_safe(file, "bak");
  2109. obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
  2110. obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
  2111. bool modified = false;
  2112. bool cbr = true;
  2113. if (cbr_item) {
  2114. cbr = obs_data_item_get_bool(cbr_item);
  2115. obs_data_item_unset_user_value(cbr_item);
  2116. obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");
  2117. modified = true;
  2118. }
  2119. if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
  2120. if (!cbr_item)
  2121. obs_data_set_string(data, "rate_control", "CBR");
  2122. else if (!cbr)
  2123. convert_x264_settings(data);
  2124. modified = true;
  2125. }
  2126. if (modified)
  2127. obs_data_save_json_safe(data, file, "tmp", "bak");
  2128. obs_data_item_release(&rc_item);
  2129. obs_data_item_release(&cbr_item);
  2130. }
  2131. static void upgrade_settings(void)
  2132. {
  2133. char path[512];
  2134. int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");
  2135. if (pathlen <= 0)
  2136. return;
  2137. if (!os_file_exists(path))
  2138. return;
  2139. os_dir_t *dir = os_opendir(path);
  2140. if (!dir)
  2141. return;
  2142. struct os_dirent *ent = os_readdir(dir);
  2143. while (ent) {
  2144. if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
  2145. strcmp(ent->d_name, "..") != 0) {
  2146. strcat(path, "/");
  2147. strcat(path, ent->d_name);
  2148. strcat(path, "/basic.ini");
  2149. ConfigFile config;
  2150. int ret;
  2151. ret = config.Open(path, CONFIG_OPEN_EXISTING);
  2152. if (ret == CONFIG_SUCCESS) {
  2153. if (update_ffmpeg_output(config) ||
  2154. update_reconnect(config)) {
  2155. config_save_safe(config, "tmp",
  2156. nullptr);
  2157. }
  2158. }
  2159. if (config) {
  2160. const char *sEnc = config_get_string(
  2161. config, "AdvOut", "Encoder");
  2162. const char *rEnc = config_get_string(
  2163. config, "AdvOut", "RecEncoder");
  2164. /* replace "cbr" option with "rate_control" for
  2165. * each profile's encoder data */
  2166. path[pathlen] = 0;
  2167. strcat(path, "/");
  2168. strcat(path, ent->d_name);
  2169. strcat(path, "/recordEncoder.json");
  2170. convert_14_2_encoder_setting(rEnc, path);
  2171. path[pathlen] = 0;
  2172. strcat(path, "/");
  2173. strcat(path, ent->d_name);
  2174. strcat(path, "/streamEncoder.json");
  2175. convert_14_2_encoder_setting(sEnc, path);
  2176. }
  2177. path[pathlen] = 0;
  2178. }
  2179. ent = os_readdir(dir);
  2180. }
  2181. os_closedir(dir);
  2182. }
  2183. void ctrlc_handler(int s)
  2184. {
  2185. UNUSED_PARAMETER(s);
  2186. OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
  2187. main->close();
  2188. }
  2189. int main(int argc, char *argv[])
  2190. {
  2191. #ifndef _WIN32
  2192. signal(SIGPIPE, SIG_IGN);
  2193. struct sigaction sig_handler;
  2194. sig_handler.sa_handler = ctrlc_handler;
  2195. sigemptyset(&sig_handler.sa_mask);
  2196. sig_handler.sa_flags = 0;
  2197. sigaction(SIGINT, &sig_handler, NULL);
  2198. /* Block SIGPIPE in all threads, this can happen if a thread calls write on
  2199. a closed pipe. */
  2200. sigset_t sigpipe_mask;
  2201. sigemptyset(&sigpipe_mask);
  2202. sigaddset(&sigpipe_mask, SIGPIPE);
  2203. sigset_t saved_mask;
  2204. if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
  2205. perror("pthread_sigmask");
  2206. exit(1);
  2207. }
  2208. #endif
  2209. #ifdef _WIN32
  2210. obs_init_win32_crash_handler();
  2211. SetErrorMode(SEM_FAILCRITICALERRORS);
  2212. load_debug_privilege();
  2213. base_set_crash_handler(main_crash_handler, nullptr);
  2214. const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll");
  2215. if (hRtwq) {
  2216. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)();
  2217. PFN_RtwqStartup func =
  2218. (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup");
  2219. func();
  2220. }
  2221. #endif
  2222. base_get_log_handler(&def_log_handler, nullptr);
  2223. #if defined(USE_XDG) && defined(IS_UNIX)
  2224. move_to_xdg();
  2225. #endif
  2226. obs_set_cmdline_args(argc, argv);
  2227. for (int i = 1; i < argc; i++) {
  2228. if (arg_is(argv[i], "--portable", "-p")) {
  2229. portable_mode = true;
  2230. } else if (arg_is(argv[i], "--multi", "-m")) {
  2231. multi = true;
  2232. } else if (arg_is(argv[i], "--verbose", nullptr)) {
  2233. log_verbose = true;
  2234. } else if (arg_is(argv[i], "--always-on-top", nullptr)) {
  2235. opt_always_on_top = true;
  2236. } else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
  2237. unfiltered_log = true;
  2238. } else if (arg_is(argv[i], "--startstreaming", nullptr)) {
  2239. opt_start_streaming = true;
  2240. } else if (arg_is(argv[i], "--startrecording", nullptr)) {
  2241. opt_start_recording = true;
  2242. } else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
  2243. opt_start_replaybuffer = true;
  2244. } else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
  2245. opt_start_virtualcam = true;
  2246. } else if (arg_is(argv[i], "--collection", nullptr)) {
  2247. if (++i < argc)
  2248. opt_starting_collection = argv[i];
  2249. } else if (arg_is(argv[i], "--profile", nullptr)) {
  2250. if (++i < argc)
  2251. opt_starting_profile = argv[i];
  2252. } else if (arg_is(argv[i], "--scene", nullptr)) {
  2253. if (++i < argc)
  2254. opt_starting_scene = argv[i];
  2255. } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
  2256. opt_minimize_tray = true;
  2257. } else if (arg_is(argv[i], "--studio-mode", nullptr)) {
  2258. opt_studio_mode = true;
  2259. } else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
  2260. opt_allow_opengl = true;
  2261. } else if (arg_is(argv[i], "--disable-updater", nullptr)) {
  2262. opt_disable_updater = true;
  2263. } else if (arg_is(argv[i], "--disable-missing-files-check",
  2264. nullptr)) {
  2265. opt_disable_missing_files_check = true;
  2266. } else if (arg_is(argv[i], "--disable-high-dpi-scaling",
  2267. nullptr)) {
  2268. opt_disable_high_dpi_scaling = true;
  2269. } else if (arg_is(argv[i], "--help", "-h")) {
  2270. std::string help =
  2271. "--help, -h: Get list of available commands.\n\n"
  2272. "--startstreaming: Automatically start streaming.\n"
  2273. "--startrecording: Automatically start recording.\n"
  2274. "--startreplaybuffer: Start replay buffer.\n"
  2275. "--startvirtualcam: Start virtual camera (if available).\n\n"
  2276. "--collection <string>: Use specific scene collection."
  2277. "\n"
  2278. "--profile <string>: Use specific profile.\n"
  2279. "--scene <string>: Start with specific scene.\n\n"
  2280. "--studio-mode: Enable studio mode.\n"
  2281. "--minimize-to-tray: Minimize to system tray.\n"
  2282. "--portable, -p: Use portable mode.\n"
  2283. "--multi, -m: Don't warn when launching multiple instances.\n\n"
  2284. "--verbose: Make log more verbose.\n"
  2285. "--always-on-top: Start in 'always on top' mode.\n\n"
  2286. "--unfiltered_log: Make log unfiltered.\n\n"
  2287. "--disable-updater: Disable built-in updater (Windows/Mac only)\n\n"
  2288. "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n"
  2289. "--disable-high-dpi-scaling: Disable automatic high-DPI scaling\n\n";
  2290. #ifdef _WIN32
  2291. MessageBoxA(NULL, help.c_str(), "Help",
  2292. MB_OK | MB_ICONASTERISK);
  2293. #else
  2294. std::cout << help
  2295. << "--version, -V: Get current version.\n";
  2296. #endif
  2297. exit(0);
  2298. } else if (arg_is(argv[i], "--version", "-V")) {
  2299. std::cout << "OBS Studio - "
  2300. << App()->GetVersionString() << "\n";
  2301. exit(0);
  2302. }
  2303. }
  2304. #if defined(LINUX_PORTABLE)
  2305. if (!portable_mode) {
  2306. portable_mode =
  2307. os_file_exists(BASE_PATH "/portable_mode") ||
  2308. os_file_exists(BASE_PATH "/obs_portable_mode") ||
  2309. os_file_exists(BASE_PATH "/portable_mode.txt") ||
  2310. os_file_exists(BASE_PATH "/obs_portable_mode.txt");
  2311. }
  2312. if (!opt_disable_updater) {
  2313. opt_disable_updater =
  2314. os_file_exists(BASE_PATH "/disable_updater") ||
  2315. os_file_exists(BASE_PATH "/disable_updater.txt");
  2316. }
  2317. if (!opt_disable_missing_files_check) {
  2318. opt_disable_missing_files_check =
  2319. os_file_exists(BASE_PATH
  2320. "/disable_missing_files_check") ||
  2321. os_file_exists(BASE_PATH
  2322. "/disable_missing_files_check.txt");
  2323. }
  2324. #endif
  2325. upgrade_settings();
  2326. fstream logFile;
  2327. curl_global_init(CURL_GLOBAL_ALL);
  2328. int ret = run_program(logFile, argc, argv);
  2329. #ifdef _WIN32
  2330. if (hRtwq) {
  2331. typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)();
  2332. PFN_RtwqShutdown func =
  2333. (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown");
  2334. func();
  2335. FreeLibrary(hRtwq);
  2336. }
  2337. #endif
  2338. blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
  2339. base_set_log_handler(nullptr, nullptr);
  2340. return ret;
  2341. }