obs-app.cpp 59.8 KB
Newer Older
1 2 3 4 5
/******************************************************************************
    Copyright (C) 2013 by Hugh Bailey <obs.jim@gmail.com>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
6
    the Free Software Foundation, either version 2 of the License, or
7 8 9 10 11 12 13 14 15 16 17
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/

J
jp9000 已提交
18 19
#include <time.h>
#include <stdio.h>
20
#include <wchar.h>
21 22
#include <chrono>
#include <ratio>
23
#include <string>
24
#include <sstream>
25
#include <mutex>
J
jp9000 已提交
26
#include <util/bmem.h>
27
#include <util/dstr.hpp>
28
#include <util/platform.h>
P
Palana 已提交
29
#include <util/profiler.hpp>
30
#include <util/cf-parser.h>
J
jp9000 已提交
31
#include <obs-config.h>
J
jp9000 已提交
32 33
#include <obs.hpp>

34
#include <QGuiApplication>
35
#include <QProxyStyle>
36
#include <QScreen>
37
#include <QProcess>
38

J
jp9000 已提交
39
#include "qt-wrappers.hpp"
J
jp9000 已提交
40
#include "obs-app.hpp"
41
#include "window-basic-main.hpp"
S
Socapex 已提交
42
#include "window-basic-settings.hpp"
J
jp9000 已提交
43
#include "crash-report.hpp"
44
#include "platform.hpp"
45

46
#include <fstream>
J
jp9000 已提交
47

48 49
#include <curl/curl.h>

J
jp9000 已提交
50
#ifdef _WIN32
J
jp9000 已提交
51
#include <windows.h>
52
#include <filesystem>
53 54
#else
#include <signal.h>
55
#include <pthread.h>
56
#endif
57

C
cg2121 已提交
58 59
#include <iostream>

60 61
#include "ui-config.h"

J
jp9000 已提交
62
using namespace std;
63

J
jp9000 已提交
64 65
static log_handler_t def_log_handler;

J
jp9000 已提交
66 67
static string currentLogFile;
static string lastLogFile;
J
jp9000 已提交
68
static string lastCrashLogFile;
J
jp9000 已提交
69

70
bool portable_mode = false;
71
static bool multi = false;
72 73
static bool log_verbose = false;
static bool unfiltered_log = false;
74 75
bool opt_start_streaming = false;
bool opt_start_recording = false;
C
cg2121 已提交
76 77
bool opt_studio_mode = false;
bool opt_start_replaybuffer = false;
J
jp9000 已提交
78
bool opt_start_virtualcam = false;
C
cg2121 已提交
79
bool opt_minimize_tray = false;
80
bool opt_allow_opengl = false;
81
bool opt_always_on_top = false;
82 83
string opt_starting_collection;
string opt_starting_profile;
84
string opt_starting_scene;
J
jp9000 已提交
85

C
cg2121 已提交
86 87 88
bool remuxAfterRecord = false;
string remuxFilename;

89 90
bool restart = false;

J
jp9000 已提交
91
// GPU hint exports for AMD/NVIDIA laptops
92
#ifdef _MSC_VER
J
jp9000 已提交
93
extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 1;
94 95 96
extern "C" __declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1;
#endif

P
Palana 已提交
97 98
QObject *CreateShortcutFilter()
{
J
jp9000 已提交
99 100
	return new OBSEventFilter([](QObject *obj, QEvent *event) {
		auto mouse_event = [](QMouseEvent &event) {
101 102
			if (!App()->HotkeysEnabledInFocus() &&
			    event.button() != Qt::LeftButton)
103 104
				return true;

P
Palana 已提交
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
			obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
			bool pressed = event.type() == QEvent::MouseButtonPress;

			switch (event.button()) {
			case Qt::NoButton:
			case Qt::LeftButton:
			case Qt::RightButton:
			case Qt::AllButtons:
			case Qt::MouseButtonMask:
				return false;

			case Qt::MidButton:
				hotkey.key = OBS_KEY_MOUSE3;
				break;

J
jp9000 已提交
120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
#define MAP_BUTTON(i, j)                       \
	case Qt::ExtraButton##i:               \
		hotkey.key = OBS_KEY_MOUSE##j; \
		break;
				MAP_BUTTON(1, 4);
				MAP_BUTTON(2, 5);
				MAP_BUTTON(3, 6);
				MAP_BUTTON(4, 7);
				MAP_BUTTON(5, 8);
				MAP_BUTTON(6, 9);
				MAP_BUTTON(7, 10);
				MAP_BUTTON(8, 11);
				MAP_BUTTON(9, 12);
				MAP_BUTTON(10, 13);
				MAP_BUTTON(11, 14);
				MAP_BUTTON(12, 15);
				MAP_BUTTON(13, 16);
				MAP_BUTTON(14, 17);
				MAP_BUTTON(15, 18);
				MAP_BUTTON(16, 19);
				MAP_BUTTON(17, 20);
				MAP_BUTTON(18, 21);
				MAP_BUTTON(19, 22);
				MAP_BUTTON(20, 23);
				MAP_BUTTON(21, 24);
				MAP_BUTTON(22, 25);
				MAP_BUTTON(23, 26);
				MAP_BUTTON(24, 27);
P
Palana 已提交
148 149 150 151
#undef MAP_BUTTON
			}

			hotkey.modifiers = TranslateQtKeyboardEventModifiers(
J
jp9000 已提交
152
				event.modifiers());
P
Palana 已提交
153 154 155 156 157

			obs_hotkey_inject_event(hotkey, pressed);
			return true;
		};

J
jp9000 已提交
158
		auto key_event = [&](QKeyEvent *event) {
159 160 161
			if (!App()->HotkeysEnabledInFocus())
				return true;

J
jp9000 已提交
162
			QDialog *dialog = qobject_cast<QDialog *>(obj);
163

P
Palana 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
			obs_key_combination_t hotkey = {0, OBS_KEY_NONE};
			bool pressed = event->type() == QEvent::KeyPress;

			switch (event->key()) {
			case Qt::Key_Shift:
			case Qt::Key_Control:
			case Qt::Key_Alt:
			case Qt::Key_Meta:
				break;

#ifdef __APPLE__
			case Qt::Key_CapsLock:
				// kVK_CapsLock == 57
				hotkey.key = obs_key_from_virtual_key(57);
				pressed = true;
				break;
#endif

182 183 184 185 186
			case Qt::Key_Enter:
			case Qt::Key_Escape:
			case Qt::Key_Return:
				if (dialog && pressed)
					return false;
187
				/* Falls through. */
P
Palana 已提交
188 189 190 191 192 193
			default:
				hotkey.key = obs_key_from_virtual_key(
					event->nativeVirtualKey());
			}

			hotkey.modifiers = TranslateQtKeyboardEventModifiers(
J
jp9000 已提交
194
				event->modifiers());
P
Palana 已提交
195 196

			obs_hotkey_inject_event(hotkey, pressed);
197
			return true;
P
Palana 已提交
198 199 200 201 202
		};

		switch (event->type()) {
		case QEvent::MouseButtonPress:
		case QEvent::MouseButtonRelease:
J
jp9000 已提交
203
			return mouse_event(*static_cast<QMouseEvent *>(event));
P
Palana 已提交
204 205 206 207 208

		/*case QEvent::MouseButtonDblClick:
		case QEvent::Wheel:*/
		case QEvent::KeyPress:
		case QEvent::KeyRelease:
J
jp9000 已提交
209
			return key_event(static_cast<QKeyEvent *>(event));
P
Palana 已提交
210 211 212 213 214 215 216

		default:
			return false;
		}
	});
}

J
jp9000 已提交
217 218
string CurrentTimeString()
{
219 220
	using namespace std::chrono;

J
jp9000 已提交
221 222
	struct tm tstruct;
	char buf[80];
223 224 225

	auto tp = system_clock::now();
	auto now = system_clock::to_time_t(tp);
J
jp9000 已提交
226
	tstruct = *localtime(&now);
227 228 229

	size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
	if (ratio_less<system_clock::period, seconds::period>::value &&
J
jp9000 已提交
230 231 232
	    written && (sizeof(buf) - written) > 5) {
		auto tp_secs = time_point_cast<seconds>(tp);
		auto millis = duration_cast<milliseconds>(tp - tp_secs).count();
233 234

		snprintf(buf + written, sizeof(buf) - written, ".%03u",
J
jp9000 已提交
235
			 static_cast<unsigned>(millis));
236 237
	}

J
jp9000 已提交
238 239 240 241 242
	return buf;
}

string CurrentDateTimeString()
{
J
jp9000 已提交
243 244 245
	time_t now = time(0);
	struct tm tstruct;
	char buf[80];
J
jp9000 已提交
246 247 248 249 250
	tstruct = *localtime(&now);
	strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
	return buf;
}

251
static inline void LogString(fstream &logFile, const char *timeString,
J
jp9000 已提交
252
			     char *str)
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281
{
	logFile << timeString << str << endl;
}

static inline void LogStringChunk(fstream &logFile, char *str)
{
	char *nextLine = str;
	string timeString = CurrentTimeString();
	timeString += ": ";

	while (*nextLine) {
		char *nextLine = strchr(str, '\n');
		if (!nextLine)
			break;

		if (nextLine != str && nextLine[-1] == '\r') {
			nextLine[-1] = 0;
		} else {
			nextLine[0] = 0;
		}

		LogString(logFile, timeString.c_str(), str);
		nextLine++;
		str = nextLine;
	}

	LogString(logFile, timeString.c_str(), str);
}

282 283 284 285 286 287 288 289 290 291 292 293 294
#define MAX_REPEATED_LINES 30
#define MAX_CHAR_VARIATION (255 * 3)

static inline int sum_chars(const char *str)
{
	int val = 0;
	for (; *str != 0; str++)
		val += *str;

	return val;
}

static inline bool too_many_repeated_entries(fstream &logFile, const char *msg,
J
jp9000 已提交
295
					     const char *output_str)
296 297 298 299 300 301 302 303 304 305 306
{
	static mutex log_mutex;
	static const char *last_msg_ptr = nullptr;
	static int last_char_sum = 0;
	static char cmp_str[4096];
	static int rep_count = 0;

	int new_sum = sum_chars(output_str);

	lock_guard<mutex> guard(log_mutex);

307 308 309 310
	if (unfiltered_log) {
		return false;
	}

311 312 313 314 315 316 317 318
	if (last_msg_ptr == msg) {
		int diff = std::abs(new_sum - last_char_sum);
		if (diff < MAX_CHAR_VARIATION) {
			return (rep_count++ >= MAX_REPEATED_LINES);
		}
	}

	if (rep_count > MAX_REPEATED_LINES) {
J
jp9000 已提交
319 320 321 322
		logFile << CurrentTimeString()
			<< ": Last log entry repeated for "
			<< to_string(rep_count - MAX_REPEATED_LINES)
			<< " more lines" << endl;
323 324 325 326 327 328 329 330 331 332
	}

	last_msg_ptr = msg;
	strcpy(cmp_str, output_str);
	last_char_sum = new_sum;
	rep_count = 0;

	return false;
}

333 334
static void do_log(int log_level, const char *msg, va_list args, void *param)
{
J
jp9000 已提交
335
	fstream &logFile = *static_cast<fstream *>(param);
J
jp9000 已提交
336 337
	char str[4096];

J
jp9000 已提交
338
#ifndef _WIN32
J
jp9000 已提交
339
	va_list args2;
J
jp9000 已提交
340
	va_copy(args2, args);
J
jp9000 已提交
341
#endif
342

J
jp9000 已提交
343 344 345
	vsnprintf(str, 4095, msg, args);

#ifdef _WIN32
346 347 348
	if (IsDebuggerPresent()) {
		int wNum = MultiByteToWideChar(CP_UTF8, 0, str, -1, NULL, 0);
		if (wNum > 1) {
349 350 351 352
			static wstring wide_buf;
			static mutex wide_mutex;

			lock_guard<mutex> lock(wide_mutex);
353 354 355
			wide_buf.reserve(wNum + 1);
			wide_buf.resize(wNum - 1);
			MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0],
J
jp9000 已提交
356
					    wNum);
357 358 359 360 361
			wide_buf.push_back('\n');

			OutputDebugStringW(wide_buf.c_str());
		}
	}
J
jp9000 已提交
362 363
#else
	def_log_handler(log_level, msg, args2, nullptr);
D
Dmitry-Me 已提交
364
	va_end(args2);
J
jp9000 已提交
365
#endif
366

367 368 369
	if (log_level <= LOG_INFO || log_verbose) {
		if (too_many_repeated_entries(logFile, msg, str))
			return;
370
		LogStringChunk(logFile, str);
371
	}
372

373
#if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
374
	if (log_level <= LOG_ERROR && IsDebuggerPresent())
375
		__debugbreak();
376
#endif
J
jp9000 已提交
377
}
378

379 380
#define DEFAULT_LANG "en-US"

381
bool OBSApp::InitGlobalConfigDefaults()
382
{
383
	config_set_default_string(globalConfig, "General", "Language",
J
jp9000 已提交
384
				  DEFAULT_LANG);
J
jp9000 已提交
385
	config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
J
jp9000 已提交
386
	config_set_default_int(globalConfig, "General", "InfoIncrement", -1);
387
	config_set_default_string(globalConfig, "General", "ProcessPriority",
J
jp9000 已提交
388
				  "Normal");
J
jp9000 已提交
389
	config_set_default_bool(globalConfig, "General", "EnableAutoUpdates",
J
jp9000 已提交
390
				true);
391

J
jp9000 已提交
392 393
#if _WIN32
	config_set_default_string(globalConfig, "Video", "Renderer",
J
jp9000 已提交
394
				  "Direct3D 11");
J
jp9000 已提交
395
#else
396
	config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
J
jp9000 已提交
397 398
#endif

J
jp9000 已提交
399
	config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
J
jp9000 已提交
400
				true);
401
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
402
				"PreviewProgramMode", false);
403
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
404 405 406 407 408 409 410 411 412 413 414 415 416
				"SceneDuplicationMode", true);
	config_set_default_bool(globalConfig, "BasicWindow", "SwapScenesMode",
				true);
	config_set_default_bool(globalConfig, "BasicWindow", "SnappingEnabled",
				true);
	config_set_default_bool(globalConfig, "BasicWindow", "ScreenSnapping",
				true);
	config_set_default_bool(globalConfig, "BasicWindow", "SourceSnapping",
				true);
	config_set_default_bool(globalConfig, "BasicWindow", "CenterSnapping",
				false);
	config_set_default_double(globalConfig, "BasicWindow", "SnapDistance",
				  10.0);
417
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
418
				"RecordWhenStreaming", false);
C
cg2121 已提交
419
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
420 421 422
				"KeepRecordingWhenStreamStops", false);
	config_set_default_bool(globalConfig, "BasicWindow", "SysTrayEnabled",
				true);
C
cg2121 已提交
423
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
424 425 426 427 428
				"SysTrayWhenStarted", false);
	config_set_default_bool(globalConfig, "BasicWindow", "SaveProjectors",
				false);
	config_set_default_bool(globalConfig, "BasicWindow", "ShowTransitions",
				true);
C
cg2121 已提交
429
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
430 431 432
				"ShowListboxToolbars", true);
	config_set_default_bool(globalConfig, "BasicWindow", "ShowStatusBar",
				true);
433 434
	config_set_default_bool(globalConfig, "BasicWindow", "ShowSourceIcons",
				true);
J
jp9000 已提交
435 436
	config_set_default_bool(globalConfig, "BasicWindow", "StudioModeLabels",
				true);
437

438 439
	if (!config_get_bool(globalConfig, "General", "Pre21Defaults")) {
		config_set_default_string(globalConfig, "General",
J
jp9000 已提交
440
					  "CurrentTheme", DEFAULT_THEME);
441 442
	}

443 444 445
	config_set_default_string(globalConfig, "General", "HotkeyFocusType",
				  "NeverDisableHotkeys");

S
Shaolin 已提交
446
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
447
				"VerticalVolControl", false);
S
Shaolin 已提交
448

449
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
450
				"MultiviewMouseSwitch", true);
451

452
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
453
				"MultiviewDrawNames", true);
454

455
	config_set_default_bool(globalConfig, "BasicWindow",
J
jp9000 已提交
456
				"MultiviewDrawAreas", true);
457

458
#ifdef _WIN32
459 460
	uint32_t winver = GetWindowsVersion();

461
	config_set_default_bool(globalConfig, "Audio", "DisableAudioDucking",
J
jp9000 已提交
462
				true);
463
	config_set_default_bool(globalConfig, "General", "BrowserHWAccel",
J
jp9000 已提交
464
				winver > 0x601);
465 466
#endif

467 468 469
#ifdef __APPLE__
	config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
	config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
J
jp9000 已提交
470
				true);
471
#endif
472
	return true;
473 474 475 476
}

static bool do_mkdir(const char *path)
{
477
	if (os_mkdirs(path) == MKDIR_ERROR) {
478
		OBSErrorBox(NULL, "Failed to create directory %s", path);
479 480 481 482 483 484 485 486
		return false;
	}

	return true;
}

static bool MakeUserDirs()
{
487
	char path[512];
J
jp9000 已提交
488

489
	if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
490
		return false;
J
jp9000 已提交
491
	if (!do_mkdir(path))
492 493
		return false;

494
	if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
495
		return false;
J
jp9000 已提交
496
	if (!do_mkdir(path))
497
		return false;
P
Palana 已提交
498 499 500 501 502 503

	if (GetConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;

J
jp9000 已提交
504
#ifdef _WIN32
505
	if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
J
jp9000 已提交
506 507 508
		return false;
	if (!do_mkdir(path))
		return false;
J
jp9000 已提交
509 510 511 512 513

	if (GetConfigPath(path, sizeof(path), "obs-studio/updates") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;
J
jp9000 已提交
514
#endif
J
jp9000 已提交
515

516 517 518 519
	if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;
J
jp9000 已提交
520

521
	return true;
522 523
}

J
jp9000 已提交
524 525 526 527
static bool MakeUserProfileDirs()
{
	char path[512];

J
jp9000 已提交
528 529 530 531 532
	if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;

J
jp9000 已提交
533 534 535 536 537 538 539 540
	if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;

	return true;
}

541 542 543 544 545 546 547 548 549
static string GetProfileDirFromName(const char *name)
{
	string outputPath;
	os_glob_t *glob;
	char path[512];

	if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
		return outputPath;

550
	strcat(path, "/*");
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566

	if (os_glob(path, 0, &glob) != 0)
		return outputPath;

	for (size_t i = 0; i < glob->gl_pathc; i++) {
		struct os_globent ent = glob->gl_pathv[i];
		if (!ent.directory)
			continue;

		strcpy(path, ent.path);
		strcat(path, "/basic.ini");

		ConfigFile config;
		if (config.Open(path, CONFIG_OPEN_EXISTING) != 0)
			continue;

J
jp9000 已提交
567 568
		const char *curName =
			config_get_string(config, "General", "Name");
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
		if (astrcmpi(curName, name) == 0) {
			outputPath = ent.path;
			break;
		}
	}

	os_globfree(glob);

	if (!outputPath.empty()) {
		replace(outputPath.begin(), outputPath.end(), '\\', '/');
		const char *start = strrchr(outputPath.c_str(), '/');
		if (start)
			outputPath.erase(0, start - outputPath.c_str() + 1);
	}

	return outputPath;
}

static string GetSceneCollectionFileFromName(const char *name)
{
	string outputPath;
	os_glob_t *glob;
	char path[512];

	if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
		return outputPath;

	strcat(path, "/*.json");

	if (os_glob(path, 0, &glob) != 0)
		return outputPath;

	for (size_t i = 0; i < glob->gl_pathc; i++) {
		struct os_globent ent = glob->gl_pathv[i];
		if (ent.directory)
			continue;

		obs_data_t *data =
			obs_data_create_from_json_file_safe(ent.path, "bak");
		const char *curName = obs_data_get_string(data, "name");

		if (astrcmpi(name, curName) == 0) {
			outputPath = ent.path;
			obs_data_release(data);
			break;
		}

		obs_data_release(data);
	}

	os_globfree(glob);

	if (!outputPath.empty()) {
		outputPath.resize(outputPath.size() - 5);
		replace(outputPath.begin(), outputPath.end(), '\\', '/');
		const char *start = strrchr(outputPath.c_str(), '/');
		if (start)
			outputPath.erase(0, start - outputPath.c_str() + 1);
	}

	return outputPath;
}

632 633 634 635 636 637
bool OBSApp::UpdatePre22MultiviewLayout(const char *layout)
{
	if (!layout)
		return false;

	if (astrcmpi(layout, "horizontaltop") == 0) {
J
jp9000 已提交
638 639
		config_set_int(
			globalConfig, "BasicWindow", "MultiviewLayout",
S
Shaolin 已提交
640 641
			static_cast<int>(
				MultiviewLayout::HORIZONTAL_TOP_8_SCENES));
642 643 644 645
		return true;
	}

	if (astrcmpi(layout, "horizontalbottom") == 0) {
J
jp9000 已提交
646 647
		config_set_int(
			globalConfig, "BasicWindow", "MultiviewLayout",
S
Shaolin 已提交
648 649
			static_cast<int>(
				MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES));
650 651 652 653
		return true;
	}

	if (astrcmpi(layout, "verticalleft") == 0) {
J
jp9000 已提交
654 655
		config_set_int(
			globalConfig, "BasicWindow", "MultiviewLayout",
S
Shaolin 已提交
656 657
			static_cast<int>(
				MultiviewLayout::VERTICAL_LEFT_8_SCENES));
658 659 660 661
		return true;
	}

	if (astrcmpi(layout, "verticalright") == 0) {
J
jp9000 已提交
662 663
		config_set_int(
			globalConfig, "BasicWindow", "MultiviewLayout",
S
Shaolin 已提交
664 665
			static_cast<int>(
				MultiviewLayout::VERTICAL_RIGHT_8_SCENES));
666 667 668 669 670 671
		return true;
	}

	return false;
}

672 673
bool OBSApp::InitGlobalConfig()
{
674
	char path[512];
675
	bool changed = false;
676

J
jp9000 已提交
677
	int len = GetConfigPath(path, sizeof(path), "obs-studio/global.ini");
678 679 680
	if (len <= 0) {
		return false;
	}
681

682
	int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
683
	if (errorcode != CONFIG_SUCCESS) {
684
		OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
685 686 687
		return false;
	}

688 689
	if (!opt_starting_collection.empty()) {
		string path = GetSceneCollectionFileFromName(
J
jp9000 已提交
690
			opt_starting_collection.c_str());
691
		if (!path.empty()) {
J
jp9000 已提交
692 693 694 695 696
			config_set_string(globalConfig, "Basic",
					  "SceneCollection",
					  opt_starting_collection.c_str());
			config_set_string(globalConfig, "Basic",
					  "SceneCollectionFile", path.c_str());
697
			changed = true;
698 699 700 701
		}
	}

	if (!opt_starting_profile.empty()) {
J
jp9000 已提交
702 703
		string path =
			GetProfileDirFromName(opt_starting_profile.c_str());
704 705
		if (!path.empty()) {
			config_set_string(globalConfig, "Basic", "Profile",
J
jp9000 已提交
706
					  opt_starting_profile.c_str());
707
			config_set_string(globalConfig, "Basic", "ProfileDir",
J
jp9000 已提交
708
					  path.c_str());
709
			changed = true;
710 711 712
		}
	}

713 714 715
	uint32_t lastVersion =
		config_get_int(globalConfig, "General", "LastVersion");

716
	if (!config_has_user_value(globalConfig, "General", "Pre19Defaults")) {
717
		bool useOldDefaults = lastVersion &&
J
jp9000 已提交
718 719
				      lastVersion <
					      MAKE_SEMANTIC_VERSION(19, 0, 0);
720 721 722 723 724 725

		config_set_bool(globalConfig, "General", "Pre19Defaults",
				useOldDefaults);
		changed = true;
	}

726 727
	if (!config_has_user_value(globalConfig, "General", "Pre21Defaults")) {
		bool useOldDefaults = lastVersion &&
J
jp9000 已提交
728 729
				      lastVersion <
					      MAKE_SEMANTIC_VERSION(21, 0, 0);
730 731 732 733 734 735

		config_set_bool(globalConfig, "General", "Pre21Defaults",
				useOldDefaults);
		changed = true;
	}

736 737
	if (!config_has_user_value(globalConfig, "General", "Pre23Defaults")) {
		bool useOldDefaults = lastVersion &&
J
jp9000 已提交
738 739
				      lastVersion <
					      MAKE_SEMANTIC_VERSION(23, 0, 0);
740 741 742 743 744 745

		config_set_bool(globalConfig, "General", "Pre23Defaults",
				useOldDefaults);
		changed = true;
	}

746 747 748 749 750 751 752 753 754 755 756 757
#define PRE_24_1_DEFS "Pre24.1Defaults"
	if (!config_has_user_value(globalConfig, "General", PRE_24_1_DEFS)) {
		bool useOldDefaults = lastVersion &&
				      lastVersion <
					      MAKE_SEMANTIC_VERSION(24, 1, 0);

		config_set_bool(globalConfig, "General", PRE_24_1_DEFS,
				useOldDefaults);
		changed = true;
	}
#undef PRE_24_1_DEFS

758
	if (config_has_user_value(globalConfig, "BasicWindow",
J
jp9000 已提交
759 760 761
				  "MultiviewLayout")) {
		const char *layout = config_get_string(
			globalConfig, "BasicWindow", "MultiviewLayout");
762 763 764
		changed |= UpdatePre22MultiviewLayout(layout);
	}

765 766 767 768 769 770 771 772 773 774
	if (lastVersion && lastVersion < MAKE_SEMANTIC_VERSION(24, 0, 0)) {
		bool disableHotkeysInFocus = config_get_bool(
			globalConfig, "General", "DisableHotkeysInFocus");
		if (disableHotkeysInFocus)
			config_set_string(globalConfig, "General",
					  "HotkeyFocusType",
					  "DisableHotkeysInFocus");
		changed = true;
	}

775 776 777
	if (changed)
		config_save_safe(globalConfig, "tmp", nullptr);

778
	return InitGlobalConfigDefaults();
779
}
780

781 782
bool OBSApp::InitLocale()
{
P
Palana 已提交
783
	ProfileScope("OBSApp::InitLocale");
J
jp9000 已提交
784 785
	const char *lang =
		config_get_string(globalConfig, "General", "Language");
786

787 788
	locale = lang;

789
	string englishPath;
790 791
	if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
		OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
792 793 794 795 796 797
		return false;
	}

	textLookup = text_lookup_create(englishPath.c_str());
	if (!textLookup) {
		OBSErrorBox(NULL, "Failed to create locale from file '%s'",
J
jp9000 已提交
798
			    englishPath.c_str());
799 800 801
		return false;
	}

J
jp9000 已提交
802 803
	bool userLocale =
		config_has_user_value(globalConfig, "General", "Language");
804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824
	bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0;

	if (userLocale && defaultLang)
		return true;

	if (!userLocale && defaultLang) {
		for (auto &locale_ : GetPreferredLocales()) {
			if (locale_ == lang)
				return true;

			stringstream file;
			file << "locale/" << locale_ << ".ini";

			string path;
			if (!GetDataFilePath(file.str().c_str(), path))
				continue;

			if (!text_lookup_add(textLookup, path.c_str()))
				continue;

			blog(LOG_INFO, "Using preferred locale '%s'",
J
jp9000 已提交
825
			     locale_.c_str());
826 827 828 829
			locale = locale_;
			return true;
		}

830
		return true;
831 832 833 834
	}

	stringstream file;
	file << "locale/" << lang << ".ini";
835

836
	string path;
837 838
	if (GetDataFilePath(file.str().c_str(), path)) {
		if (!text_lookup_add(textLookup, path.c_str()))
J
jp9000 已提交
839
			blog(LOG_ERROR, "Failed to add locale file '%s'",
J
jp9000 已提交
840
			     path.c_str());
841
	} else {
J
jp9000 已提交
842
		blog(LOG_ERROR, "Could not find locale file '%s'",
J
jp9000 已提交
843
		     file.str().c_str());
844 845 846 847 848
	}

	return true;
}

J
jp9000 已提交
849 850
void OBSApp::AddExtraThemeColor(QPalette &pal, int group, const char *name,
				uint32_t color)
851 852 853
{
	std::function<void(QPalette::ColorGroup)> func;

J
jp9000 已提交
854 855 856 857 858 859
#define DEF_PALETTE_ASSIGN(name)                              \
	do {                                                  \
		func = [&](QPalette::ColorGroup group) {      \
			pal.setColor(group, QPalette::name,   \
				     QColor::fromRgb(color)); \
		};                                            \
860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892
	} while (false)

	if (astrcmpi(name, "alternateBase") == 0) {
		DEF_PALETTE_ASSIGN(AlternateBase);
	} else if (astrcmpi(name, "base") == 0) {
		DEF_PALETTE_ASSIGN(Base);
	} else if (astrcmpi(name, "brightText") == 0) {
		DEF_PALETTE_ASSIGN(BrightText);
	} else if (astrcmpi(name, "button") == 0) {
		DEF_PALETTE_ASSIGN(Button);
	} else if (astrcmpi(name, "buttonText") == 0) {
		DEF_PALETTE_ASSIGN(ButtonText);
	} else if (astrcmpi(name, "brightText") == 0) {
		DEF_PALETTE_ASSIGN(BrightText);
	} else if (astrcmpi(name, "dark") == 0) {
		DEF_PALETTE_ASSIGN(Dark);
	} else if (astrcmpi(name, "highlight") == 0) {
		DEF_PALETTE_ASSIGN(Highlight);
	} else if (astrcmpi(name, "highlightedText") == 0) {
		DEF_PALETTE_ASSIGN(HighlightedText);
	} else if (astrcmpi(name, "light") == 0) {
		DEF_PALETTE_ASSIGN(Light);
	} else if (astrcmpi(name, "link") == 0) {
		DEF_PALETTE_ASSIGN(Link);
	} else if (astrcmpi(name, "linkVisited") == 0) {
		DEF_PALETTE_ASSIGN(LinkVisited);
	} else if (astrcmpi(name, "mid") == 0) {
		DEF_PALETTE_ASSIGN(Mid);
	} else if (astrcmpi(name, "midlight") == 0) {
		DEF_PALETTE_ASSIGN(Midlight);
	} else if (astrcmpi(name, "shadow") == 0) {
		DEF_PALETTE_ASSIGN(Shadow);
	} else if (astrcmpi(name, "text") == 0 ||
J
jp9000 已提交
893
		   astrcmpi(name, "foreground") == 0) {
894 895 896 897 898 899 900 901
		DEF_PALETTE_ASSIGN(Text);
	} else if (astrcmpi(name, "toolTipBase") == 0) {
		DEF_PALETTE_ASSIGN(ToolTipBase);
	} else if (astrcmpi(name, "toolTipText") == 0) {
		DEF_PALETTE_ASSIGN(ToolTipText);
	} else if (astrcmpi(name, "windowText") == 0) {
		DEF_PALETTE_ASSIGN(WindowText);
	} else if (astrcmpi(name, "window") == 0 ||
J
jp9000 已提交
902
		   astrcmpi(name, "background") == 0) {
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924
		DEF_PALETTE_ASSIGN(Window);
	} else {
		return;
	}

#undef DEF_PALETTE_ASSIGN

	switch (group) {
	case QPalette::Disabled:
	case QPalette::Active:
	case QPalette::Inactive:
		func((QPalette::ColorGroup)group);
		break;
	default:
		func((QPalette::ColorGroup)QPalette::Disabled);
		func((QPalette::ColorGroup)QPalette::Active);
		func((QPalette::ColorGroup)QPalette::Inactive);
	}
}

struct CFParser {
	cf_parser cfp = {};
J
jp9000 已提交
925 926 927
	inline ~CFParser() { cf_parser_free(&cfp); }
	inline operator cf_parser *() { return &cfp; }
	inline cf_parser *operator->() { return &cfp; }
928 929 930 931 932 933 934 935 936 937 938 939
};

void OBSApp::ParseExtraThemeData(const char *path)
{
	BPtr<char> data = os_quick_read_utf8_file(path);
	QPalette pal = palette();
	CFParser cfp;
	int ret;

	cf_parser_parse(cfp, data, path);

	while (cf_go_to_token(cfp, "OBSTheme", nullptr)) {
J
jp9000 已提交
940 941
		if (!cf_next_token(cfp))
			return;
942 943 944 945 946

		int group = -1;

		if (cf_token_is(cfp, ":")) {
			ret = cf_next_token_should_be(cfp, ":", nullptr,
J
jp9000 已提交
947 948 949
						      nullptr);
			if (ret != PARSE_SUCCESS)
				continue;
950

J
jp9000 已提交
951 952
			if (!cf_next_token(cfp))
				return;
953 954 955 956 957 958 959 960 961 962 963

			if (cf_token_is(cfp, "disabled")) {
				group = QPalette::Disabled;
			} else if (cf_token_is(cfp, "active")) {
				group = QPalette::Active;
			} else if (cf_token_is(cfp, "inactive")) {
				group = QPalette::Inactive;
			} else {
				continue;
			}

J
jp9000 已提交
964 965
			if (!cf_next_token(cfp))
				return;
966 967
		}

J
jp9000 已提交
968 969
		if (!cf_token_is(cfp, "{"))
			continue;
970 971

		for (;;) {
J
jp9000 已提交
972 973
			if (!cf_next_token(cfp))
				return;
974 975

			ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name",
J
jp9000 已提交
976
					       nullptr);
977 978 979 980 981 982
			if (ret != PARSE_SUCCESS)
				break;

			DStr name;
			dstr_copy_strref(name, &cfp->cur_token->str);

J
jp9000 已提交
983 984 985
			ret = cf_next_token_should_be(cfp, ":", ";", nullptr);
			if (ret != PARSE_SUCCESS)
				continue;
986

J
jp9000 已提交
987 988
			if (!cf_next_token(cfp))
				return;
989 990 991 992 993 994 995 996 997 998

			const char *array;
			uint32_t color = 0;

			if (cf_token_is(cfp, "#")) {
				array = cfp->cur_token->str.array;
				color = strtol(array + 1, nullptr, 16);

			} else if (cf_token_is(cfp, "rgb")) {
				ret = cf_next_token_should_be(cfp, "(", ";",
J
jp9000 已提交
999 1000 1001 1002 1003
							      nullptr);
				if (ret != PARSE_SUCCESS)
					continue;
				if (!cf_next_token(cfp))
					return;
1004 1005 1006 1007 1008

				array = cfp->cur_token->str.array;
				color |= strtol(array, nullptr, 10) << 16;

				ret = cf_next_token_should_be(cfp, ",", ";",
J
jp9000 已提交
1009 1010 1011 1012 1013
							      nullptr);
				if (ret != PARSE_SUCCESS)
					continue;
				if (!cf_next_token(cfp))
					return;
1014 1015 1016 1017 1018

				array = cfp->cur_token->str.array;
				color |= strtol(array, nullptr, 10) << 8;

				ret = cf_next_token_should_be(cfp, ",", ";",
J
jp9000 已提交
1019 1020 1021 1022 1023
							      nullptr);
				if (ret != PARSE_SUCCESS)
					continue;
				if (!cf_next_token(cfp))
					return;
1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034

				array = cfp->cur_token->str.array;
				color |= strtol(array, nullptr, 10);

			} else if (cf_token_is(cfp, "white")) {
				color = 0xFFFFFF;

			} else if (cf_token_is(cfp, "black")) {
				color = 0;
			}

J
jp9000 已提交
1035 1036
			if (!cf_go_to_token(cfp, ";", nullptr))
				return;
1037 1038 1039 1040 1041

			AddExtraThemeColor(pal, group, name->array, color);
		}

		ret = cf_token_should_be(cfp, "}", "}", nullptr);
J
jp9000 已提交
1042 1043
		if (ret != PARSE_SUCCESS)
			continue;
1044 1045 1046 1047 1048
	}

	setPalette(pal);
}

S
Socapex 已提交
1049 1050 1051 1052 1053 1054 1055 1056 1057
bool OBSApp::SetTheme(std::string name, std::string path)
{
	theme = name;

	/* Check user dir first, then preinstalled themes. */
	if (path == "") {
		char userDir[512];
		name = "themes/" + name + ".qss";
		string temp = "obs-studio/" + name;
J
jp9000 已提交
1058
		int ret = GetConfigPath(userDir, sizeof(userDir), temp.c_str());
S
Socapex 已提交
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068

		if (ret > 0 && QFile::exists(userDir)) {
			path = string(userDir);
		} else if (!GetDataFilePath(name.c_str(), path)) {
			OBSErrorBox(NULL, "Failed to find %s.", name.c_str());
			return false;
		}
	}

	QString mpath = QString("file:///") + path.c_str();
1069
	setPalette(defaultPalette);
S
Socapex 已提交
1070
	setStyleSheet(mpath);
1071 1072
	ParseExtraThemeData(path.c_str());

1073
	emit StyleChanged();
S
Socapex 已提交
1074 1075 1076 1077 1078
	return true;
}

bool OBSApp::InitTheme()
{
1079 1080
	defaultPalette = palette();

J
jp9000 已提交
1081
	const char *themeName =
1082
		config_get_string(globalConfig, "General", "CurrentTheme2");
1083

1084 1085 1086 1087 1088
	if (!themeName)
		/* Use deprecated "CurrentTheme" value if available */
		themeName = config_get_string(globalConfig, "General",
					      "CurrentTheme");
	if (!themeName)
1089
		/* Use deprecated "Theme" value if available */
J
jp9000 已提交
1090
		themeName = config_get_string(globalConfig, "General", "Theme");
1091 1092 1093 1094
	if (!themeName)
		themeName = DEFAULT_THEME;
	if (!themeName)
		themeName = "Dark";
S
Socapex 已提交
1095

1096 1097
	if (strcmp(themeName, "Default") == 0)
		themeName = "System";
1098

1099 1100 1101 1102
	if (strcmp(themeName, "System") != 0 && SetTheme(themeName))
		return true;

	return SetTheme("System");
S
Socapex 已提交
1103 1104
}

P
Palana 已提交
1105
OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
J
jp9000 已提交
1106
	: QApplication(argc, argv), profilerNameStore(store)
1107 1108
{
	sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
1109 1110

	setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png")));
1111 1112 1113 1114
}

OBSApp::~OBSApp()
{
1115
#ifdef _WIN32
J
jp9000 已提交
1116 1117
	bool disableAudioDucking =
		config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
1118 1119 1120 1121
	if (disableAudioDucking)
		DisableAudioDucking(false);
#endif

1122
#ifdef __APPLE__
J
jp9000 已提交
1123 1124 1125 1126
	bool vsyncDiabled =
		config_get_bool(globalConfig, "Video", "DisableOSXVSync");
	bool resetVSync =
		config_get_bool(globalConfig, "Video", "ResetOSXVSyncOnExit");
1127 1128 1129 1130
	if (vsyncDiabled && resetVSync)
		EnableOSXVSync(true);
#endif

1131 1132 1133
	os_inhibit_sleep_set_active(sleepInhibitor, false);
	os_inhibit_sleep_destroy(sleepInhibitor);
}
1134

J
jp9000 已提交
1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
static void move_basic_to_profiles(void)
{
	char path[512];
	char new_path[512];
	os_glob_t *glob;

	/* if not first time use */
	if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
		return;
	if (!os_file_exists(path))
		return;

	/* if the profiles directory doesn't already exist */
	if (GetConfigPath(new_path, 512, "obs-studio/basic/profiles") <= 0)
		return;
	if (os_file_exists(new_path))
		return;

	if (os_mkdir(new_path) == MKDIR_ERROR)
		return;

	strcat(new_path, "/");
	strcat(new_path, Str("Untitled"));
	if (os_mkdir(new_path) == MKDIR_ERROR)
		return;

	strcat(path, "/*.*");
	if (os_glob(path, 0, &glob) != 0)
		return;

	strcpy(path, new_path);

	for (size_t i = 0; i < glob->gl_pathc; i++) {
		struct os_globent ent = glob->gl_pathv[i];
		char *file;

		if (ent.directory)
			continue;

		file = strrchr(ent.path, '/');
		if (!file++)
			continue;

		if (astrcmpi(file, "scenes.json") == 0)
			continue;

		strcpy(new_path, path);
		strcat(new_path, "/");
		strcat(new_path, file);
		os_rename(ent.path, new_path);
	}

	os_globfree(glob);
}

J
jp9000 已提交
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
static void move_basic_to_scene_collections(void)
{
	char path[512];
	char new_path[512];

	if (GetConfigPath(path, 512, "obs-studio/basic") <= 0)
		return;
	if (!os_file_exists(path))
		return;

	if (GetConfigPath(new_path, 512, "obs-studio/basic/scenes") <= 0)
		return;
	if (os_file_exists(new_path))
		return;

	if (os_mkdir(new_path) == MKDIR_ERROR)
		return;

	strcat(path, "/scenes.json");
	strcat(new_path, "/");
	strcat(new_path, Str("Untitled"));
	strcat(new_path, ".json");

	os_rename(path, new_path);
}

1216
void OBSApp::AppInit()
1217
{
P
Palana 已提交
1218 1219
	ProfileScope("OBSApp::AppInit");

1220
	if (!InitApplicationBundle())
J
jp9000 已提交
1221
		throw "Failed to initialize application bundle";
1222
	if (!MakeUserDirs())
J
jp9000 已提交
1223
		throw "Failed to create required user directories";
1224
	if (!InitGlobalConfig())
J
jp9000 已提交
1225
		throw "Failed to initialize global config";
1226
	if (!InitLocale())
J
jp9000 已提交
1227
		throw "Failed to load locale";
S
Socapex 已提交
1228 1229
	if (!InitTheme())
		throw "Failed to load theme";
J
jp9000 已提交
1230 1231

	config_set_default_string(globalConfig, "Basic", "Profile",
J
jp9000 已提交
1232
				  Str("Untitled"));
J
jp9000 已提交
1233
	config_set_default_string(globalConfig, "Basic", "ProfileDir",
J
jp9000 已提交
1234
				  Str("Untitled"));
J
jp9000 已提交
1235
	config_set_default_string(globalConfig, "Basic", "SceneCollection",
J
jp9000 已提交
1236
				  Str("Untitled"));
J
jp9000 已提交
1237
	config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
J
jp9000 已提交
1238
				  Str("Untitled"));
J
jp9000 已提交
1239

1240 1241
	if (!config_has_user_value(globalConfig, "Basic", "Profile")) {
		config_set_string(globalConfig, "Basic", "Profile",
J
jp9000 已提交
1242
				  Str("Untitled"));
1243
		config_set_string(globalConfig, "Basic", "ProfileDir",
J
jp9000 已提交
1244
				  Str("Untitled"));
1245 1246 1247
	}

	if (!config_has_user_value(globalConfig, "Basic", "SceneCollection")) {
J
jp9000 已提交
1248 1249 1250 1251
		config_set_string(globalConfig, "Basic", "SceneCollection",
				  Str("Untitled"));
		config_set_string(globalConfig, "Basic", "SceneCollectionFile",
				  Str("Untitled"));
1252 1253
	}

1254
#ifdef _WIN32
J
jp9000 已提交
1255 1256
	bool disableAudioDucking =
		config_get_bool(globalConfig, "Audio", "DisableAudioDucking");
1257 1258 1259 1260
	if (disableAudioDucking)
		DisableAudioDucking(true);
#endif

1261 1262 1263 1264 1265
#ifdef __APPLE__
	if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
		EnableOSXVSync(false);
#endif

1266
	UpdateHotkeyFocusSetting(false);
1267

J
jp9000 已提交
1268
	move_basic_to_profiles();
J
jp9000 已提交
1269 1270 1271 1272
	move_basic_to_scene_collections();

	if (!MakeUserProfileDirs())
		throw "Failed to create profile directories";
J
jp9000 已提交
1273
}
J
jp9000 已提交
1274

J
jp9000 已提交
1275
const char *OBSApp::GetRenderModule() const
1276
{
J
jp9000 已提交
1277 1278
	const char *renderer =
		config_get_string(globalConfig, "Video", "Renderer");
J
jp9000 已提交
1279

J
jp9000 已提交
1280
	return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL;
J
jp9000 已提交
1281
}
J
jp9000 已提交
1282

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
static bool StartupOBS(const char *locale, profiler_name_store_t *store)
{
	char path[512];

	if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
		return false;

	return obs_startup(locale, path, store);
}

1293 1294
inline void OBSApp::ResetHotkeyState(bool inFocus)
{
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315
	obs_hotkey_enable_background_press(
		(inFocus && enableHotkeysInFocus) ||
		(!inFocus && enableHotkeysOutOfFocus));
}

void OBSApp::UpdateHotkeyFocusSetting(bool resetState)
{
	enableHotkeysInFocus = true;
	enableHotkeysOutOfFocus = true;

	const char *hotkeyFocusType =
		config_get_string(globalConfig, "General", "HotkeyFocusType");

	if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) {
		enableHotkeysInFocus = false;
	} else if (astrcmpi(hotkeyFocusType, "DisableHotkeysOutOfFocus") == 0) {
		enableHotkeysOutOfFocus = false;
	}

	if (resetState)
		ResetHotkeyState(applicationState() == Qt::ApplicationActive);
1316 1317
}

1318
void OBSApp::DisableHotkeys()
1319
{
1320 1321
	enableHotkeysInFocus = false;
	enableHotkeysOutOfFocus = false;
1322
	ResetHotkeyState(applicationState() == Qt::ApplicationActive);
1323 1324
}

1325 1326 1327 1328 1329 1330 1331
Q_DECLARE_METATYPE(VoidFunc)

void OBSApp::Exec(VoidFunc func)
{
	func();
}

J
jp9000 已提交
1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342
static void ui_task_handler(obs_task_t task, void *param, bool wait)
{
	auto doTask = [=]() {
		/* to get clang-format to behave */
		task(param);
	};
	QMetaObject::invokeMethod(App(), "Exec",
				  wait ? WaitConnection() : Qt::AutoConnection,
				  Q_ARG(VoidFunc, doTask));
}

J
jp9000 已提交
1343
bool OBSApp::OBSInit()
1344
{
P
Palana 已提交
1345 1346
	ProfileScope("OBSApp::OBSInit");

1347 1348
	setAttribute(Qt::AA_UseHighDpiPixmaps);

1349 1350
	qRegisterMetaType<VoidFunc>();

C
cg2121 已提交
1351 1352
	if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
		return false;
1353

J
jp9000 已提交
1354 1355
	obs_set_ui_task_handler(ui_task_handler);

1356
#ifdef _WIN32
J
jp9000 已提交
1357 1358
	bool browserHWAccel =
		config_get_bool(globalConfig, "General", "BrowserHWAccel");
1359

C
cg2121 已提交
1360 1361 1362 1363
	obs_data_t *settings = obs_data_create();
	obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel);
	obs_apply_private_data(settings);
	obs_data_release(settings);
1364

J
jp9000 已提交
1365 1366
	blog(LOG_INFO, "Current Date/Time: %s",
	     CurrentDateTimeString().c_str());
J
jp9000 已提交
1367

C
cg2121 已提交
1368
	blog(LOG_INFO, "Browser Hardware Acceleration: %s",
J
jp9000 已提交
1369
	     browserHWAccel ? "true" : "false");
1370 1371
#endif

J
jp9000 已提交
1372
	blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false");
1373

C
cg2121 已提交
1374
	setQuitOnLastWindowClosed(false);
1375

C
cg2121 已提交
1376
	mainWindow = new OBSBasic();
1377

C
cg2121 已提交
1378 1379
	mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
	connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));
1380

C
cg2121 已提交
1381
	mainWindow->OBSInit();
J
jp9000 已提交
1382

C
cg2121 已提交
1383
	connect(this, &QGuiApplication::applicationStateChanged,
J
jp9000 已提交
1384
		[this](Qt::ApplicationState state) {
1385
			ResetHotkeyState(state == Qt::ApplicationActive);
J
jp9000 已提交
1386
		});
1387
	ResetHotkeyState(applicationState() == Qt::ApplicationActive);
C
cg2121 已提交
1388
	return true;
1389 1390
}

J
jp9000 已提交
1391 1392 1393
string OBSApp::GetVersionString() const
{
	stringstream ver;
J
jp9000 已提交
1394

J
jp9000 已提交
1395
#ifdef HAVE_OBSCONFIG_H
1396 1397
	ver << OBS_VERSION;
#else
J
jp9000 已提交
1398 1399
	ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "."
	    << LIBOBS_API_PATCH_VER;
1400

J
jp9000 已提交
1401
#endif
1402
	ver << " (";
J
jp9000 已提交
1403 1404

#ifdef _WIN32
J
jp9000 已提交
1405
	if (sizeof(void *) == 8)
1406 1407 1408
		ver << "64-bit, ";
	else
		ver << "32-bit, ";
J
jp9000 已提交
1409

J
jp9000 已提交
1410 1411 1412
	ver << "windows)";
#elif __APPLE__
	ver << "mac)";
1413 1414
#elif __FreeBSD__
	ver << "freebsd)";
J
jp9000 已提交
1415 1416 1417
#else /* assume linux for the time being */
	ver << "linux)";
#endif
J
jp9000 已提交
1418

J
jp9000 已提交
1419 1420 1421
	return ver.str();
}

1422 1423 1424 1425 1426
bool OBSApp::IsPortableMode()
{
	return portable_mode;
}

J
jp9000 已提交
1427
#ifdef __APPLE__
J
jp9000 已提交
1428
#define INPUT_AUDIO_SOURCE "coreaudio_input_capture"
J
jp9000 已提交
1429
#define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
J
jp9000 已提交
1430
#elif _WIN32
J
jp9000 已提交
1431
#define INPUT_AUDIO_SOURCE "wasapi_input_capture"
J
jp9000 已提交
1432 1433
#define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
#else
J
jp9000 已提交
1434
#define INPUT_AUDIO_SOURCE "pulse_input_capture"
1435
#define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
J
jp9000 已提交
1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
#endif

const char *OBSApp::InputAudioSource() const
{
	return INPUT_AUDIO_SOURCE;
}

const char *OBSApp::OutputAudioSource() const
{
	return OUTPUT_AUDIO_SOURCE;
}

J
jp9000 已提交
1448 1449 1450 1451 1452 1453 1454 1455 1456 1457
const char *OBSApp::GetLastLog() const
{
	return lastLogFile.c_str();
}

const char *OBSApp::GetCurrentLog() const
{
	return currentLogFile.c_str();
}

J
jp9000 已提交
1458 1459 1460 1461 1462
const char *OBSApp::GetLastCrashLog() const
{
	return lastCrashLogFile.c_str();
}

J
jp9000 已提交
1463 1464 1465 1466 1467 1468 1469 1470 1471 1472
bool OBSApp::TranslateString(const char *lookupVal, const char **out) const
{
	for (obs_frontend_translate_ui_cb cb : translatorHooks) {
		if (cb(lookupVal, out))
			return true;
	}

	return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out);
}

J
jp9000 已提交
1473
QString OBSTranslator::translate(const char *context, const char *sourceText,
J
jp9000 已提交
1474
				 const char *disambiguation, int n) const
J
jp9000 已提交
1475 1476
{
	const char *out = nullptr;
J
jp9000 已提交
1477 1478
	if (!App()->TranslateString(sourceText, &out))
		return QString(sourceText);
J
jp9000 已提交
1479 1480 1481 1482 1483 1484 1485

	UNUSED_PARAMETER(context);
	UNUSED_PARAMETER(disambiguation);
	UNUSED_PARAMETER(n);
	return QT_UTF8(out);
}

J
jp9000 已提交
1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
static bool get_token(lexer *lex, string &str, base_token_type type)
{
	base_token token;
	if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
		return false;
	if (token.type != type)
		return false;

	str.assign(token.text.array, token.text.len);
	return true;
}

static bool expect_token(lexer *lex, const char *str, base_token_type type)
{
	base_token token;
	if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE))
		return false;
	if (token.type != type)
		return false;

	return strref_cmp(&token.text, str) == 0;
}

1509
static uint64_t convert_log_name(bool has_prefix, const char *name)
J
jp9000 已提交
1510
{
J
jp9000 已提交
1511 1512
	BaseLexer lex;
	string year, month, day, hour, minute, second;
J
jp9000 已提交
1513 1514 1515

	lexer_start(lex, name);

1516 1517
	if (has_prefix) {
		string temp;
J
jp9000 已提交
1518 1519
		if (!get_token(lex, temp, BASETOKEN_ALPHA))
			return 0;
1520 1521
	}

J
jp9000 已提交
1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541
	if (!get_token(lex, year, BASETOKEN_DIGIT))
		return 0;
	if (!expect_token(lex, "-", BASETOKEN_OTHER))
		return 0;
	if (!get_token(lex, month, BASETOKEN_DIGIT))
		return 0;
	if (!expect_token(lex, "-", BASETOKEN_OTHER))
		return 0;
	if (!get_token(lex, day, BASETOKEN_DIGIT))
		return 0;
	if (!get_token(lex, hour, BASETOKEN_DIGIT))
		return 0;
	if (!expect_token(lex, "-", BASETOKEN_OTHER))
		return 0;
	if (!get_token(lex, minute, BASETOKEN_DIGIT))
		return 0;
	if (!expect_token(lex, "-", BASETOKEN_OTHER))
		return 0;
	if (!get_token(lex, second, BASETOKEN_DIGIT))
		return 0;
J
jp9000 已提交
1542 1543 1544 1545 1546 1547

	stringstream timestring;
	timestring << year << month << day << hour << minute << second;
	return std::stoull(timestring.str());
}

1548
static void delete_oldest_file(bool has_prefix, const char *location)
J
jp9000 已提交
1549
{
J
jp9000 已提交
1550 1551 1552
	BPtr<char> logDir(GetConfigPathPtr(location));
	string oldestLog;
	uint64_t oldest_ts = (uint64_t)-1;
J
jp9000 已提交
1553
	struct os_dirent *entry;
1554

J
jp9000 已提交
1555
	unsigned int maxLogs = (unsigned int)config_get_uint(
J
jp9000 已提交
1556
		App()->GlobalConfig(), "General", "MaxLogs");
1557

1558
	os_dir_t *dir = os_opendir(logDir);
J
jp9000 已提交
1559 1560
	if (dir) {
		unsigned int count = 0;
1561

J
jp9000 已提交
1562
		while ((entry = os_readdir(dir)) != NULL) {
J
jp9000 已提交
1563
			if (entry->directory || *entry->d_name == '.')
J
jp9000 已提交
1564 1565
				continue;

J
jp9000 已提交
1566 1567
			uint64_t ts =
				convert_log_name(has_prefix, entry->d_name);
J
jp9000 已提交
1568

J
jp9000 已提交
1569 1570 1571 1572 1573
			if (ts) {
				if (ts < oldest_ts) {
					oldestLog = entry->d_name;
					oldest_ts = ts;
				}
J
jp9000 已提交
1574

J
jp9000 已提交
1575 1576
				count++;
			}
J
jp9000 已提交
1577 1578 1579 1580
		}

		os_closedir(dir);

J
jp9000 已提交
1581
		if (count > maxLogs) {
J
jp9000 已提交
1582 1583
			stringstream delPath;

J
jp9000 已提交
1584
			delPath << logDir << "/" << oldestLog;
J
jp9000 已提交
1585 1586 1587 1588 1589
			os_unlink(delPath.str().c_str());
		}
	}
}

1590
static void get_last_log(bool has_prefix, const char *subdir_to_use,
J
jp9000 已提交
1591
			 std::string &last)
J
jp9000 已提交
1592
{
J
jp9000 已提交
1593
	BPtr<char> logDir(GetConfigPathPtr(subdir_to_use));
J
jp9000 已提交
1594
	struct os_dirent *entry;
J
jp9000 已提交
1595 1596
	os_dir_t *dir = os_opendir(logDir);
	uint64_t highest_ts = 0;
J
jp9000 已提交
1597 1598 1599 1600 1601 1602

	if (dir) {
		while ((entry = os_readdir(dir)) != NULL) {
			if (entry->directory || *entry->d_name == '.')
				continue;

J
jp9000 已提交
1603 1604
			uint64_t ts =
				convert_log_name(has_prefix, entry->d_name);
J
jp9000 已提交
1605 1606

			if (ts > highest_ts) {
1607 1608
				last = entry->d_name;
				highest_ts = ts;
J
jp9000 已提交
1609 1610 1611 1612 1613 1614 1615
			}
		}

		os_closedir(dir);
	}
}

1616
string GenerateTimeDateFilename(const char *extension, bool noSpace)
J
jp9000 已提交
1617
{
J
jp9000 已提交
1618 1619
	time_t now = time(0);
	char file[256] = {};
1620
	struct tm *cur_time;
J
jp9000 已提交
1621

J
jp9000 已提交
1622
	cur_time = localtime(&now);
1623
	snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
J
jp9000 已提交
1624 1625 1626
		 cur_time->tm_year + 1900, cur_time->tm_mon + 1,
		 cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour,
		 cur_time->tm_min, cur_time->tm_sec, extension);
1627 1628 1629

	return string(file);
}
J
jp9000 已提交
1630

B
bl 已提交
1631
string GenerateSpecifiedFilename(const char *extension, bool noSpace,
J
jp9000 已提交
1632
				 const char *format)
B
bl 已提交
1633
{
J
jp9000 已提交
1634
	OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
C
cg2121 已提交
1635 1636 1637 1638 1639
	bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux");

	if ((strcmp(extension, "mp4") == 0) && autoRemux)
		extension = "mkv";

J
jp9000 已提交
1640 1641
	BPtr<char> filename =
		os_generate_formatted_filename(extension, !noSpace, format);
C
cg2121 已提交
1642 1643 1644 1645

	remuxFilename = string(filename);
	remuxAfterRecord = autoRemux;

1646
	return string(filename);
B
bl 已提交
1647 1648
}

1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671
vector<pair<string, string>> GetLocaleNames()
{
	string path;
	if (!GetDataFilePath("locale.ini", path))
		throw "Could not find locale.ini path";

	ConfigFile ini;
	if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0)
		throw "Could not open locale.ini";

	size_t sections = config_num_sections(ini);

	vector<pair<string, string>> names;
	names.reserve(sections);
	for (size_t i = 0; i < sections; i++) {
		const char *tag = config_get_section(ini, i);
		const char *name = config_get_string(ini, tag, "Name");
		names.emplace_back(tag, name);
	}

	return names;
}

1672 1673 1674
static void create_log_file(fstream &logFile)
{
	stringstream dst;
J
jp9000 已提交
1675

1676
	get_last_log(false, "obs-studio/logs", lastLogFile);
J
jp9000 已提交
1677 1678 1679
#ifdef _WIN32
	get_last_log(true, "obs-studio/crashes", lastCrashLogFile);
#endif
J
jp9000 已提交
1680

1681 1682
	currentLogFile = GenerateTimeDateFilename("txt");
	dst << "obs-studio/logs/" << currentLogFile.c_str();
J
jp9000 已提交
1683

1684
	BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
1685 1686 1687 1688

#ifdef _WIN32
	BPtr<wchar_t> wpath;
	os_utf8_to_wcs_ptr(path, 0, &wpath);
J
jp9000 已提交
1689
	logFile.open(wpath, ios_base::in | ios_base::out | ios_base::trunc);
1690
#else
J
jp9000 已提交
1691
	logFile.open(path, ios_base::in | ios_base::out | ios_base::trunc);
1692
#endif
J
jp9000 已提交
1693 1694

	if (logFile.is_open()) {
1695
		delete_oldest_file(false, "obs-studio/logs");
1696
		base_set_log_handler(do_log, &logFile);
J
jp9000 已提交
1697 1698 1699 1700 1701
	} else {
		blog(LOG_ERROR, "Failed to open log file");
	}
}

J
jp9000 已提交
1702
static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) {
P
Palana 已提交
1703 1704 1705
	profiler_name_store_free(store);
};

J
jp9000 已提交
1706 1707
using ProfilerNameStore = std::unique_ptr<profiler_name_store_t,
					  decltype(ProfilerNameStoreRelease)>;
P
Palana 已提交
1708 1709 1710 1711

ProfilerNameStore CreateNameStore()
{
	return ProfilerNameStore{profiler_name_store_create(),
J
jp9000 已提交
1712
				 ProfilerNameStoreRelease};
P
Palana 已提交
1713 1714
}

J
jp9000 已提交
1715
static auto SnapshotRelease = [](profiler_snapshot_t *snap) {
P
Palana 已提交
1716 1717 1718
	profile_snapshot_free(snap);
};

J
jp9000 已提交
1719
using ProfilerSnapshot =
P
Palana 已提交
1720 1721 1722 1723 1724 1725 1726
	std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;

ProfilerSnapshot GetSnapshot()
{
	return ProfilerSnapshot{profile_snapshot_create(), SnapshotRelease};
}

P
Palana 已提交
1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745
static void SaveProfilerData(const ProfilerSnapshot &snap)
{
	if (currentLogFile.empty())
		return;

	auto pos = currentLogFile.rfind('.');
	if (pos == currentLogFile.npos)
		return;

#define LITERAL_SIZE(x) x, (sizeof(x) - 1)
	ostringstream dst;
	dst.write(LITERAL_SIZE("obs-studio/profiler_data/"));
	dst.write(currentLogFile.c_str(), pos);
	dst.write(LITERAL_SIZE(".csv.gz"));
#undef LITERAL_SIZE

	BPtr<char> path = GetConfigPathPtr(dst.str().c_str());
	if (!profiler_snapshot_dump_csv_gz(snap.get(), path))
		blog(LOG_WARNING, "Could not save profiler data to '%s'",
J
jp9000 已提交
1746
		     static_cast<const char *>(path));
P
Palana 已提交
1747 1748
}

J
jp9000 已提交
1749
static auto ProfilerFree = [](void *) {
P
Palana 已提交
1750 1751 1752 1753 1754 1755 1756
	profiler_stop();

	auto snap = GetSnapshot();

	profiler_print(snap.get());
	profiler_print_time_between_calls(snap.get());

P
Palana 已提交
1757 1758
	SaveProfilerData(snap);

P
Palana 已提交
1759 1760 1761
	profiler_free();
};

P
Palana 已提交
1762
static const char *run_program_init = "run_program_init";
J
jp9000 已提交
1763 1764 1765
static int run_program(fstream &logFile, int argc, char *argv[])
{
	int ret = -1;
P
Palana 已提交
1766 1767 1768

	auto profilerNameStore = CreateNameStore();

J
jp9000 已提交
1769 1770
	std::unique_ptr<void, decltype(ProfilerFree)> prof_release(
		static_cast<void *>(&ProfilerFree), ProfilerFree);
P
Palana 已提交
1771 1772

	profiler_start();
P
Palana 已提交
1773 1774 1775
	profile_register_root(run_program_init, 0);

	ScopeProfiler prof{run_program_init};
P
Palana 已提交
1776

1777 1778 1779 1780
#if (QT_VERSION >= QT_VERSION_CHECK(5, 11, 0))
	QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif

1781 1782 1783 1784
#if !defined(_WIN32) && !defined(__APPLE__) && BROWSER_AVAILABLE
	setenv("QT_NO_GLIB", "1", true);
#endif

J
jp9000 已提交
1785
	QCoreApplication::addLibraryPath(".");
J
jp9000 已提交
1786

1787 1788 1789 1790
#if __APPLE__
	InstallNSApplicationSubclass();
#endif

P
Palana 已提交
1791
	OBSApp program(argc, argv, profilerNameStore.get());
J
jp9000 已提交
1792
	try {
1793
		bool created_log = false;
J
jp9000 已提交
1794

1795
		program.AppInit();
1796
		delete_oldest_file(false, "obs-studio/profiler_data");
J
jp9000 已提交
1797

1798
		OBSTranslator translator;
J
jp9000 已提交
1799 1800
		program.installTranslator(&translator);

1801 1802 1803 1804
#ifdef _WIN32
		/* --------------------------------------- */
		/* check and warn if already running       */

1805
		bool cancel_launch = false;
1806 1807 1808
		bool already_running = false;
		RunOnceMutex rom = GetRunOnceMutex(already_running);

1809 1810 1811
		if (!already_running) {
			goto run;
		}
1812

1813
		if (!multi) {
1814
			QMessageBox::StandardButtons buttons(
J
jp9000 已提交
1815
				QMessageBox::Yes | QMessageBox::Cancel);
1816
			QMessageBox mb(QMessageBox::Question,
J
jp9000 已提交
1817 1818 1819
				       QTStr("AlreadyRunning.Title"),
				       QTStr("AlreadyRunning.Text"), buttons,
				       nullptr);
1820
			mb.setButtonText(QMessageBox::Yes,
J
jp9000 已提交
1821
					 QTStr("AlreadyRunning.LaunchAnyway"));
1822 1823 1824 1825 1826
			mb.setButtonText(QMessageBox::Cancel, QTStr("Cancel"));
			mb.setDefaultButton(QMessageBox::Cancel);

			QMessageBox::StandardButton button;
			button = (QMessageBox::StandardButton)mb.exec();
1827 1828
			cancel_launch = button == QMessageBox::Cancel;
		}
1829

1830
		if (cancel_launch)
1831
			return 0;
1832 1833 1834 1835 1836

		if (!created_log) {
			create_log_file(logFile);
			created_log = true;
		}
1837

1838
		if (multi) {
1839
			blog(LOG_INFO, "User enabled --multi flag and is now "
J
jp9000 已提交
1840
				       "running multiple instances of OBS.");
1841 1842 1843 1844 1845
		} else {
			blog(LOG_WARNING, "================================");
			blog(LOG_WARNING, "Warning: OBS is already running!");
			blog(LOG_WARNING, "================================");
			blog(LOG_WARNING, "User is now running multiple "
J
jp9000 已提交
1846
					  "instances of OBS!");
1847 1848 1849
		}

		/* --------------------------------------- */
J
jp9000 已提交
1850
	run:
1851
#endif
1852 1853 1854 1855 1856 1857

		if (!created_log) {
			create_log_file(logFile);
			created_log = true;
		}

V
VodBox 已提交
1858 1859 1860 1861 1862 1863
		if (argc > 1) {
			stringstream stor;
			stor << argv[1];
			for (int i = 2; i < argc; ++i) {
				stor << " " << argv[i];
			}
J
jp9000 已提交
1864 1865
			blog(LOG_INFO, "Command Line Arguments: %s",
			     stor.str().c_str());
V
VodBox 已提交
1866
		}
1867

P
Palana 已提交
1868
		if (!program.OBSInit())
1869
			return 0;
P
Palana 已提交
1870

P
Palana 已提交
1871 1872
		prof.Stop();

1873
		ret = program.exec();
J
jp9000 已提交
1874 1875 1876

	} catch (const char *error) {
		blog(LOG_ERROR, "%s", error);
1877
		OBSErrorBox(nullptr, "%s", error);
J
jp9000 已提交
1878 1879
	}

1880 1881 1882 1883
	if (restart)
		QProcess::startDetached(qApp->arguments()[0],
					qApp->arguments());

J
jp9000 已提交
1884 1885 1886
	return ret;
}

1887
#define MAX_CRASH_REPORT_SIZE (150 * 1024)
J
jp9000 已提交
1888

J
jp9000 已提交
1889 1890
#ifdef _WIN32

J
jp9000 已提交
1891
#define CRASH_MESSAGE                                                      \
J
jp9000 已提交
1892
	"Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
1893
	"to the clipboard? The crash log will still be saved to:\n\n%s"
J
jp9000 已提交
1894

J
jp9000 已提交
1895 1896
static void main_crash_handler(const char *format, va_list args, void *param)
{
J
jp9000 已提交
1897 1898 1899
	char *text = new char[MAX_CRASH_REPORT_SIZE];

	vsnprintf(text, MAX_CRASH_REPORT_SIZE, format, args);
1900
	text[MAX_CRASH_REPORT_SIZE - 1] = 0;
J
jp9000 已提交
1901

1902
	string crashFilePath = "obs-studio/crashes";
J
jp9000 已提交
1903

1904 1905 1906 1907
	delete_oldest_file(true, crashFilePath.c_str());

	string name = crashFilePath + "/";
	name += "Crash " + GenerateTimeDateFilename("txt");
J
jp9000 已提交
1908

1909
	BPtr<char> path(GetConfigPathPtr(name.c_str()));
J
jp9000 已提交
1910 1911

	fstream file;
1912 1913 1914 1915 1916

#ifdef _WIN32
	BPtr<wchar_t> wpath;
	os_utf8_to_wcs_ptr(path, 0, &wpath);
	file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc |
J
jp9000 已提交
1917
				 ios_base::binary);
1918
#else
J
jp9000 已提交
1919 1920
	file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
				ios_base::binary);
1921
#endif
J
jp9000 已提交
1922 1923 1924
	file << text;
	file.close();

1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944
	string pathString(path.Get());

#ifdef _WIN32
	std::replace(pathString.begin(), pathString.end(), '/', '\\');
#endif

	string absolutePath =
		canonical(filesystem::path(pathString)).u8string();

	size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str());

	unique_ptr<char[]> message_buffer(new char[size + 1]);

	snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE,
		 absolutePath.c_str());

	string finalMessage =
		string(message_buffer.get(), message_buffer.get() + size);

	int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!",
J
jp9000 已提交
1945
			      MB_YESNO | MB_ICONERROR | MB_TASKMODAL);
J
jp9000 已提交
1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958

	if (ret == IDYES) {
		size_t len = strlen(text);

		HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, len);
		memcpy(GlobalLock(mem), text, len);
		GlobalUnlock(mem);

		OpenClipboard(0);
		EmptyClipboard();
		SetClipboardData(CF_TEXT, mem);
		CloseClipboard();
	}
J
jp9000 已提交
1959 1960 1961 1962 1963 1964

	exit(-1);

	UNUSED_PARAMETER(param);
}

J
jp9000 已提交
1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980
static void load_debug_privilege(void)
{
	const DWORD flags = TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY;
	TOKEN_PRIVILEGES tp;
	HANDLE token;
	LUID val;

	if (!OpenProcessToken(GetCurrentProcess(), flags, &token)) {
		return;
	}

	if (!!LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &val)) {
		tp.PrivilegeCount = 1;
		tp.Privileges[0].Luid = val;
		tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

J
jp9000 已提交
1981 1982
		AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
				      NULL);
J
jp9000 已提交
1983 1984
	}

J
jp9000 已提交
1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996
	if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) {
		tp.PrivilegeCount = 1;
		tp.Privileges[0].Luid = val;
		tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;

		if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL,
					   NULL)) {
			blog(LOG_INFO, "Could not set privilege to "
				       "increase GPU priority");
		}
	}

J
jp9000 已提交
1997 1998 1999 2000
	CloseHandle(token);
}
#endif

J
jp9000 已提交
2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040
#ifdef __APPLE__
#define BASE_PATH ".."
#else
#define BASE_PATH "../.."
#endif

#define CONFIG_PATH BASE_PATH "/config"

#ifndef OBS_UNIX_STRUCTURE
#define OBS_UNIX_STRUCTURE 0
#endif

int GetConfigPath(char *path, size_t size, const char *name)
{
	if (!OBS_UNIX_STRUCTURE && portable_mode) {
		if (name && *name) {
			return snprintf(path, size, CONFIG_PATH "/%s", name);
		} else {
			return snprintf(path, size, CONFIG_PATH);
		}
	} else {
		return os_get_config_path(path, size, name);
	}
}

char *GetConfigPathPtr(const char *name)
{
	if (!OBS_UNIX_STRUCTURE && portable_mode) {
		char path[512];

		if (snprintf(path, sizeof(path), CONFIG_PATH "/%s", name) > 0) {
			return bstrdup(path);
		} else {
			return NULL;
		}
	} else {
		return os_get_config_path_ptr(name);
	}
}

2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
int GetProgramDataPath(char *path, size_t size, const char *name)
{
	return os_get_program_data_path(path, size, name);
}

char *GetProgramDataPathPtr(const char *name)
{
	return os_get_program_data_path_ptr(name);
}

2051 2052 2053 2054 2055 2056 2057 2058 2059 2060
bool GetFileSafeName(const char *name, std::string &file)
{
	size_t base_len = strlen(name);
	size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0);
	std::wstring wfile;

	if (!len)
		return false;

	wfile.resize(len);
J
jp9000 已提交
2061
	os_utf8_to_wcs(name, base_len, &wfile[0], len + 1);
2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080

	for (size_t i = wfile.size(); i > 0; i--) {
		size_t im1 = i - 1;

		if (iswspace(wfile[im1])) {
			wfile[im1] = '_';
		} else if (wfile[im1] != '_' && !iswalnum(wfile[im1])) {
			wfile.erase(im1, 1);
		}
	}

	if (wfile.size() == 0)
		wfile = L"characters_only";

	len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0);
	if (!len)
		return false;

	file.resize(len);
J
jp9000 已提交
2081
	os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1);
2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109
	return true;
}

bool GetClosestUnusedFileName(std::string &path, const char *extension)
{
	size_t len = path.size();
	if (extension) {
		path += ".";
		path += extension;
	}

	if (!os_file_exists(path.c_str()))
		return true;

	int index = 1;

	do {
		path.resize(len);
		path += std::to_string(++index);
		if (extension) {
			path += ".";
			path += extension;
		}
	} while (os_file_exists(path.c_str()));

	return true;
}

2110
bool WindowPositionValid(QRect rect)
2111
{
J
jp9000 已提交
2112
	for (QScreen *screen : QGuiApplication::screens()) {
2113
		if (screen->availableGeometry().intersects(rect))
2114 2115 2116 2117 2118
			return true;
	}
	return false;
}

J
jp9000 已提交
2119 2120
static inline bool arg_is(const char *arg, const char *long_form,
			  const char *short_form)
J
jp9000 已提交
2121
{
J
jp9000 已提交
2122
	return (long_form && strcmp(arg, long_form) == 0) ||
J
jp9000 已提交
2123 2124 2125
	       (short_form && strcmp(arg, short_form) == 0);
}

2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142
#if !defined(_WIN32) && !defined(__APPLE__)
#define IS_UNIX 1
#endif

/* if using XDG and was previously using an older build of OBS, move config
 * files to XDG directory */
#if defined(USE_XDG) && defined(IS_UNIX)
static void move_to_xdg(void)
{
	char old_path[512];
	char new_path[512];
	char *home = getenv("HOME");
	if (!home)
		return;

	if (snprintf(old_path, 512, "%s/.obs-studio", home) <= 0)
		return;
2143 2144 2145 2146 2147 2148 2149

	/* make base xdg path if it doesn't already exist */
	if (GetConfigPath(new_path, 512, "") <= 0)
		return;
	if (os_mkdirs(new_path) == MKDIR_ERROR)
		return;

2150 2151 2152 2153 2154 2155 2156 2157 2158
	if (GetConfigPath(new_path, 512, "obs-studio") <= 0)
		return;

	if (os_file_exists(old_path) && !os_file_exists(new_path)) {
		rename(old_path, new_path);
	}
}
#endif

J
jp9000 已提交
2159
static bool update_ffmpeg_output(ConfigFile &config)
2160 2161
{
	if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
J
jp9000 已提交
2162
		return false;
2163 2164 2165

	const char *url = config_get_string(config, "AdvOut", "FFURL");
	if (!url)
J
jp9000 已提交
2166
		return false;
2167 2168 2169

	bool isActualURL = strstr(url, "://") != nullptr;
	if (isActualURL)
J
jp9000 已提交
2170
		return false;
2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188

	string urlStr = url;
	string extension;

	for (size_t i = urlStr.length(); i > 0; i--) {
		size_t idx = i - 1;

		if (urlStr[idx] == '.') {
			extension = &urlStr[i];
		}

		if (urlStr[idx] == '\\' || urlStr[idx] == '/') {
			urlStr[idx] = 0;
			break;
		}
	}

	if (urlStr.empty() || extension.empty())
J
jp9000 已提交
2189
		return false;
2190 2191 2192 2193 2194

	config_remove_value(config, "AdvOut", "FFURL");
	config_set_string(config, "AdvOut", "FFFilePath", urlStr.c_str());
	config_set_string(config, "AdvOut", "FFExtension", extension.c_str());
	config_set_bool(config, "AdvOut", "FFOutputToFile", true);
J
jp9000 已提交
2195
	return true;
2196 2197
}

2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229
static bool move_reconnect_settings(ConfigFile &config, const char *sec)
{
	bool changed = false;

	if (config_has_user_value(config, sec, "Reconnect")) {
		bool reconnect = config_get_bool(config, sec, "Reconnect");
		config_set_bool(config, "Output", "Reconnect", reconnect);
		changed = true;
	}
	if (config_has_user_value(config, sec, "RetryDelay")) {
		int delay = (int)config_get_uint(config, sec, "RetryDelay");
		config_set_uint(config, "Output", "RetryDelay", delay);
		changed = true;
	}
	if (config_has_user_value(config, sec, "MaxRetries")) {
		int retries = (int)config_get_uint(config, sec, "MaxRetries");
		config_set_uint(config, "Output", "MaxRetries", retries);
		changed = true;
	}

	return changed;
}

static bool update_reconnect(ConfigFile &config)
{
	if (!config_has_user_value(config, "Output", "Mode"))
		return false;

	const char *mode = config_get_string(config, "Output", "Mode");
	if (!mode)
		return false;

J
jp9000 已提交
2230 2231
	const char *section = (strcmp(mode, "Advanced") == 0) ? "AdvOut"
							      : "SimpleOutput";
2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245

	if (move_reconnect_settings(config, section)) {
		config_remove_value(config, "SimpleOutput", "Reconnect");
		config_remove_value(config, "SimpleOutput", "RetryDelay");
		config_remove_value(config, "SimpleOutput", "MaxRetries");
		config_remove_value(config, "AdvOut", "Reconnect");
		config_remove_value(config, "AdvOut", "RetryDelay");
		config_remove_value(config, "AdvOut", "MaxRetries");
		return true;
	}

	return false;
}

2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261
static void convert_x264_settings(obs_data_t *data)
{
	bool use_bufsize = obs_data_get_bool(data, "use_bufsize");

	if (use_bufsize) {
		int buffer_size = (int)obs_data_get_int(data, "buffer_size");
		if (buffer_size == 0)
			obs_data_set_string(data, "rate_control", "CRF");
	}
}

static void convert_14_2_encoder_setting(const char *encoder, const char *file)
{
	obs_data_t *data = obs_data_create_from_json_file_safe(file, "bak");
	obs_data_item_t *cbr_item = obs_data_item_byname(data, "cbr");
	obs_data_item_t *rc_item = obs_data_item_byname(data, "rate_control");
2262 2263
	bool modified = false;
	bool cbr = true;
2264

2265 2266 2267
	if (cbr_item) {
		cbr = obs_data_item_get_bool(cbr_item);
		obs_data_item_unset_user_value(cbr_item);
2268

2269 2270 2271 2272
		obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");

		modified = true;
	}
2273

2274 2275
	if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
		if (!cbr_item)
2276
			obs_data_set_string(data, "rate_control", "CBR");
2277
		else if (!cbr)
2278 2279
			convert_x264_settings(data);

2280
		modified = true;
2281 2282
	}

2283 2284 2285
	if (modified)
		obs_data_save_json_safe(data, file, "tmp", "bak");

2286 2287 2288 2289 2290
	obs_data_item_release(&rc_item);
	obs_data_item_release(&cbr_item);
	obs_data_release(data);
}

2291
static void upgrade_settings(void)
2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307
{
	char path[512];
	int pathlen = GetConfigPath(path, 512, "obs-studio/basic/profiles");

	if (pathlen <= 0)
		return;
	if (!os_file_exists(path))
		return;

	os_dir_t *dir = os_opendir(path);
	if (!dir)
		return;

	struct os_dirent *ent = os_readdir(dir);

	while (ent) {
2308
		if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
J
jp9000 已提交
2309
		    strcmp(ent->d_name, "..") != 0) {
2310 2311 2312 2313
			strcat(path, "/");
			strcat(path, ent->d_name);
			strcat(path, "/basic.ini");

J
jp9000 已提交
2314 2315 2316 2317 2318
			ConfigFile config;
			int ret;

			ret = config.Open(path, CONFIG_OPEN_EXISTING);
			if (ret == CONFIG_SUCCESS) {
2319 2320
				if (update_ffmpeg_output(config) ||
				    update_reconnect(config)) {
J
jp9000 已提交
2321
					config_save_safe(config, "tmp",
J
jp9000 已提交
2322
							 nullptr);
J
jp9000 已提交
2323 2324
				}
			}
2325

2326
			if (config) {
J
jp9000 已提交
2327 2328 2329 2330
				const char *sEnc = config_get_string(
					config, "AdvOut", "Encoder");
				const char *rEnc = config_get_string(
					config, "AdvOut", "RecEncoder");
2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346

				/* replace "cbr" option with "rate_control" for
				 * each profile's encoder data */
				path[pathlen] = 0;
				strcat(path, "/");
				strcat(path, ent->d_name);
				strcat(path, "/recordEncoder.json");
				convert_14_2_encoder_setting(rEnc, path);

				path[pathlen] = 0;
				strcat(path, "/");
				strcat(path, ent->d_name);
				strcat(path, "/streamEncoder.json");
				convert_14_2_encoder_setting(sEnc, path);
			}

2347 2348 2349 2350 2351 2352 2353 2354 2355
			path[pathlen] = 0;
		}

		ent = os_readdir(dir);
	}

	os_closedir(dir);
}

J
jp9000 已提交
2356 2357
void ctrlc_handler(int s)
{
2358 2359
	UNUSED_PARAMETER(s);

J
jp9000 已提交
2360
	OBSBasic *main = reinterpret_cast<OBSBasic *>(App()->GetMainWindow());
2361 2362 2363
	main->close();
}

J
jp9000 已提交
2364 2365
int main(int argc, char *argv[])
{
M
martell 已提交
2366
#ifndef _WIN32
J
jp9000 已提交
2367
	signal(SIGPIPE, SIG_IGN);
2368 2369 2370 2371 2372 2373 2374 2375

	struct sigaction sig_handler;

	sig_handler.sa_handler = ctrlc_handler;
	sigemptyset(&sig_handler.sa_mask);
	sig_handler.sa_flags = 0;

	sigaction(SIGINT, &sig_handler, NULL);
2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386

	/* Block SIGPIPE in all threads, this can happen if a thread calls write on
	a closed pipe. */
	sigset_t sigpipe_mask;
	sigemptyset(&sigpipe_mask);
	sigaddset(&sigpipe_mask, SIGPIPE);
	sigset_t saved_mask;
	if (pthread_sigmask(SIG_BLOCK, &sigpipe_mask, &saved_mask) == -1) {
		perror("pthread_sigmask");
		exit(1);
	}
J
jp9000 已提交
2387 2388
#endif

J
jp9000 已提交
2389
#ifdef _WIN32
2390
	obs_init_win32_crash_handler();
2391
	SetErrorMode(SEM_FAILCRITICALERRORS);
J
jp9000 已提交
2392
	load_debug_privilege();
J
jp9000 已提交
2393
	base_set_crash_handler(main_crash_handler, nullptr);
J
jp9000 已提交
2394 2395
#endif

J
jp9000 已提交
2396 2397
	base_get_log_handler(&def_log_handler, nullptr);

2398 2399 2400 2401
#if defined(USE_XDG) && defined(IS_UNIX)
	move_to_xdg();
#endif

2402 2403
	obs_set_cmdline_args(argc, argv);

J
jp9000 已提交
2404 2405 2406
	for (int i = 1; i < argc; i++) {
		if (arg_is(argv[i], "--portable", "-p")) {
			portable_mode = true;
2407

2408 2409 2410
		} else if (arg_is(argv[i], "--multi", "-m")) {
			multi = true;

2411 2412 2413
		} else if (arg_is(argv[i], "--verbose", nullptr)) {
			log_verbose = true;

2414 2415 2416
		} else if (arg_is(argv[i], "--always-on-top", nullptr)) {
			opt_always_on_top = true;

2417 2418 2419
		} else if (arg_is(argv[i], "--unfiltered_log", nullptr)) {
			unfiltered_log = true;

2420 2421 2422 2423 2424 2425
		} else if (arg_is(argv[i], "--startstreaming", nullptr)) {
			opt_start_streaming = true;

		} else if (arg_is(argv[i], "--startrecording", nullptr)) {
			opt_start_recording = true;

C
cg2121 已提交
2426 2427 2428
		} else if (arg_is(argv[i], "--startreplaybuffer", nullptr)) {
			opt_start_replaybuffer = true;

J
jp9000 已提交
2429 2430 2431
		} else if (arg_is(argv[i], "--startvirtualcam", nullptr)) {
			opt_start_virtualcam = true;

2432
		} else if (arg_is(argv[i], "--collection", nullptr)) {
J
jp9000 已提交
2433 2434
			if (++i < argc)
				opt_starting_collection = argv[i];
2435 2436

		} else if (arg_is(argv[i], "--profile", nullptr)) {
J
jp9000 已提交
2437 2438
			if (++i < argc)
				opt_starting_profile = argv[i];
2439

2440
		} else if (arg_is(argv[i], "--scene", nullptr)) {
J
jp9000 已提交
2441 2442
			if (++i < argc)
				opt_starting_scene = argv[i];
C
cg2121 已提交
2443 2444 2445 2446 2447 2448 2449

		} else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) {
			opt_minimize_tray = true;

		} else if (arg_is(argv[i], "--studio-mode", nullptr)) {
			opt_studio_mode = true;

2450 2451 2452
		} else if (arg_is(argv[i], "--allow-opengl", nullptr)) {
			opt_allow_opengl = true;

C
cg2121 已提交
2453
		} else if (arg_is(argv[i], "--help", "-h")) {
2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470
			std::string help =
				"--help, -h: Get list of available commands.\n\n"
				"--startstreaming: Automatically start streaming.\n"
				"--startrecording: Automatically start recording.\n"
				"--startreplaybuffer: Start replay buffer.\n"
				"--startvirtualcam: Start virtual camera (if available).\n\n"
				"--collection <string>: Use specific scene collection."
				"\n"
				"--profile <string>: Use specific profile.\n"
				"--scene <string>: Start with specific scene.\n\n"
				"--studio-mode: Enable studio mode.\n"
				"--minimize-to-tray: Minimize to system tray.\n"
				"--portable, -p: Use portable mode.\n"
				"--multi, -m: Don't warn when launching multiple instances.\n\n"
				"--verbose: Make log more verbose.\n"
				"--always-on-top: Start in 'always on top' mode.\n\n"
				"--unfiltered_log: Make log unfiltered.\n\n";
C
cg2121 已提交
2471

2472 2473 2474 2475 2476 2477 2478
#ifdef _WIN32
			MessageBoxA(NULL, help.c_str(), "Help",
				    MB_OK | MB_ICONASTERISK);
#else
			std::cout << help
				  << "--version, -V: Get current version.\n";
#endif
C
cg2121 已提交
2479 2480 2481
			exit(0);

		} else if (arg_is(argv[i], "--version", "-V")) {
J
jp9000 已提交
2482 2483
			std::cout << "OBS Studio - "
				  << App()->GetVersionString() << "\n";
C
cg2121 已提交
2484
			exit(0);
J
jp9000 已提交
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497
		}
	}

#if !OBS_UNIX_STRUCTURE
	if (!portable_mode) {
		portable_mode =
			os_file_exists(BASE_PATH "/portable_mode") ||
			os_file_exists(BASE_PATH "/obs_portable_mode") ||
			os_file_exists(BASE_PATH "/portable_mode.txt") ||
			os_file_exists(BASE_PATH "/obs_portable_mode.txt");
	}
#endif

2498
	upgrade_settings();
2499

J
jp9000 已提交
2500 2501
	fstream logFile;

2502
	curl_global_init(CURL_GLOBAL_ALL);
J
jp9000 已提交
2503 2504
	int ret = run_program(logFile, argc, argv);

J
jp9000 已提交
2505
	blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
2506
	base_set_log_handler(nullptr, nullptr);
J
jp9000 已提交
2507 2508
	return ret;
}