obs-app.cpp 79 KB

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