obs-app.cpp 41.3 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 <sstream>
24
#include <mutex>
J
jp9000 已提交
25
#include <util/bmem.h>
26
#include <util/dstr.h>
27
#include <util/platform.h>
P
Palana 已提交
28
#include <util/profiler.hpp>
J
jp9000 已提交
29
#include <obs-config.h>
J
jp9000 已提交
30 31
#include <obs.hpp>

C
Colin Edwards 已提交
32
#include <QtGlobal>
33
#include <QGuiApplication>
34
#include <QProxyStyle>
35
#include <QScreen>
36

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

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

47 48
#include <curl/curl.h>

J
jp9000 已提交
49
#ifdef _WIN32
J
jp9000 已提交
50
#include <windows.h>
51 52
#else
#include <signal.h>
53
#endif
54

J
jp9000 已提交
55
using namespace std;
56

J
jp9000 已提交
57 58
static log_handler_t def_log_handler;

J
jp9000 已提交
59 60 61
static string currentLogFile;
static string lastLogFile;

J
jp9000 已提交
62
static bool portable_mode = false;
63 64
bool opt_start_streaming = false;
bool opt_start_recording = false;
65 66
string opt_starting_collection;
string opt_starting_profile;
67
string opt_starting_scene;
J
jp9000 已提交
68

P
Palana 已提交
69 70
QObject *CreateShortcutFilter()
{
71
	return new OBSEventFilter([](QObject *obj, QEvent *event)
P
Palana 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
	{
		auto mouse_event = [](QMouseEvent &event)
		{
			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;

#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);
#undef MAP_BUTTON
			}

			hotkey.modifiers = TranslateQtKeyboardEventModifiers(
							event.modifiers());

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

126
		auto key_event = [&](QKeyEvent *event)
P
Palana 已提交
127
		{
128 129
			QDialog *dialog = qobject_cast<QDialog*>(obj);

P
Palana 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
			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

148 149 150 151 152
			case Qt::Key_Enter:
			case Qt::Key_Escape:
			case Qt::Key_Return:
				if (dialog && pressed)
					return false;
P
Palana 已提交
153 154 155 156 157 158 159 160 161
			default:
				hotkey.key = obs_key_from_virtual_key(
					event->nativeVirtualKey());
			}

			hotkey.modifiers = TranslateQtKeyboardEventModifiers(
							event->modifiers());

			obs_hotkey_inject_event(hotkey, pressed);
162
			return true;
P
Palana 已提交
163 164 165 166 167 168 169 170 171 172 173
		};

		switch (event->type()) {
		case QEvent::MouseButtonPress:
		case QEvent::MouseButtonRelease:
			return mouse_event(*static_cast<QMouseEvent*>(event));

		/*case QEvent::MouseButtonDblClick:
		case QEvent::Wheel:*/
		case QEvent::KeyPress:
		case QEvent::KeyRelease:
174
			return key_event(static_cast<QKeyEvent*>(event));
P
Palana 已提交
175 176 177 178 179 180 181

		default:
			return false;
		}
	});
}

J
jp9000 已提交
182 183
string CurrentTimeString()
{
184 185
	using namespace std::chrono;

J
jp9000 已提交
186 187
	struct tm  tstruct;
	char       buf[80];
188 189 190

	auto tp = system_clock::now();
	auto now = system_clock::to_time_t(tp);
J
jp9000 已提交
191
	tstruct = *localtime(&now);
192 193 194 195 196 197 198 199 200 201 202 203 204

	size_t written = strftime(buf, sizeof(buf), "%X", &tstruct);
	if (ratio_less<system_clock::period, seconds::period>::value &&
			written && (sizeof(buf) - written) > 5) {
		auto tp_secs =
			time_point_cast<seconds>(tp);
		auto millis  =
			duration_cast<milliseconds>(tp - tp_secs).count();

		snprintf(buf + written, sizeof(buf) - written, ".%03u",
				static_cast<unsigned>(millis));
	}

J
jp9000 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217
	return buf;
}

string CurrentDateTimeString()
{
	time_t     now = time(0);
	struct tm  tstruct;
	char       buf[80];
	tstruct = *localtime(&now);
	strftime(buf, sizeof(buf), "%Y-%m-%d, %X", &tstruct);
	return buf;
}

218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
static inline void LogString(fstream &logFile, const char *timeString,
		char *str)
{
	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);
}

249 250 251 252 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 282 283 284 285 286 287 288 289 290 291 292 293 294 295
#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,
		const char *output_str)
{
	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);

	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) {
		logFile << CurrentTimeString() <<
			": Last log entry repeated for " <<
			to_string(rep_count - MAX_REPEATED_LINES) <<
			" more lines" << endl;
	}

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

	return false;
}

296 297 298
static void do_log(int log_level, const char *msg, va_list args, void *param)
{
	fstream &logFile = *static_cast<fstream*>(param);
J
jp9000 已提交
299 300
	char str[4096];

J
jp9000 已提交
301
#ifndef _WIN32
J
jp9000 已提交
302
	va_list args2;
J
jp9000 已提交
303
	va_copy(args2, args);
J
jp9000 已提交
304
#endif
305

J
jp9000 已提交
306 307 308 309
	vsnprintf(str, 4095, msg, args);

#ifdef _WIN32
	OutputDebugStringA(str);
310
	OutputDebugStringA("\n");
J
jp9000 已提交
311 312 313
#else
	def_log_handler(log_level, msg, args2, nullptr);
#endif
314

315 316 317
	if (too_many_repeated_entries(logFile, msg, str))
		return;

318
	if (log_level <= LOG_INFO)
319
		LogStringChunk(logFile, str);
320

321
#if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR)
322
	if (log_level <= LOG_ERROR && IsDebuggerPresent())
323
		__debugbreak();
324
#endif
J
jp9000 已提交
325
}
326

327 328
#define DEFAULT_LANG "en-US"

329
bool OBSApp::InitGlobalConfigDefaults()
330
{
331 332
	config_set_default_string(globalConfig, "General", "Language",
			DEFAULT_LANG);
J
jp9000 已提交
333
	config_set_default_uint(globalConfig, "General", "MaxLogs", 10);
334 335
	config_set_default_string(globalConfig, "General", "ProcessPriority",
			"Normal");
336

J
jp9000 已提交
337 338 339 340
#if _WIN32
	config_set_default_string(globalConfig, "Video", "Renderer",
			"Direct3D 11");
#else
341
	config_set_default_string(globalConfig, "Video", "Renderer", "OpenGL");
J
jp9000 已提交
342 343
#endif

J
jp9000 已提交
344 345
	config_set_default_bool(globalConfig, "BasicWindow", "PreviewEnabled",
			true);
346 347 348 349 350 351
	config_set_default_bool(globalConfig, "BasicWindow",
			"PreviewProgramMode", false);
	config_set_default_bool(globalConfig, "BasicWindow",
			"SceneDuplicationMode", true);
	config_set_default_bool(globalConfig, "BasicWindow",
			"SwapScenesMode", true);
352 353 354 355
	config_set_default_bool(globalConfig, "BasicWindow",
			"SnappingEnabled", true);
	config_set_default_bool(globalConfig, "BasicWindow",
			"ScreenSnapping", true);
356 357
	config_set_default_bool(globalConfig, "BasicWindow",
			"SourceSnapping", true);
358 359
	config_set_default_bool(globalConfig, "BasicWindow",
			"CenterSnapping", false);
360 361
	config_set_default_double(globalConfig, "BasicWindow",
			"SnapDistance", 10.0);
362 363 364 365
	config_set_default_bool(globalConfig, "BasicWindow",
			"RecordWhenStreaming", false);
	config_set_default_bool(globalConfig, "BasicWindow",
			"KeepRecordingWhenStreamStops", false);
C
cg2121 已提交
366 367 368 369
	config_set_default_bool(globalConfig, "BasicWindow",
			"SysTrayEnabled", true);
	config_set_default_bool(globalConfig, "BasicWindow",
			"SysTrayWhenStarted", false);
370 371 372 373 374 375
	config_set_default_bool(globalConfig, "BasicWindow",
			"ShowTransitions", true);
	config_set_default_bool(globalConfig, "BasicWindow",
			"ShowListboxToolbars", true);
	config_set_default_bool(globalConfig, "BasicWindow",
			"ShowStatusBar", true);
376 377 378 379 380 381

#ifdef __APPLE__
	config_set_default_bool(globalConfig, "Video", "DisableOSXVSync", true);
	config_set_default_bool(globalConfig, "Video", "ResetOSXVSyncOnExit",
			true);
#endif
382
	return true;
383 384 385 386
}

static bool do_mkdir(const char *path)
{
387
	if (os_mkdirs(path) == MKDIR_ERROR) {
388
		OBSErrorBox(NULL, "Failed to create directory %s", path);
389 390 391 392 393 394 395 396
		return false;
	}

	return true;
}

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

399
	if (GetConfigPath(path, sizeof(path), "obs-studio/basic") <= 0)
400
		return false;
J
jp9000 已提交
401
	if (!do_mkdir(path))
402 403
		return false;

404
	if (GetConfigPath(path, sizeof(path), "obs-studio/logs") <= 0)
405
		return false;
J
jp9000 已提交
406
	if (!do_mkdir(path))
407
		return false;
P
Palana 已提交
408 409 410 411 412 413

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

J
jp9000 已提交
414
#ifdef _WIN32
415
	if (GetConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0)
J
jp9000 已提交
416 417 418 419
		return false;
	if (!do_mkdir(path))
		return false;
#endif
420 421 422 423
	if (GetConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;
J
jp9000 已提交
424

425
	return true;
426 427
}

J
jp9000 已提交
428 429 430 431
static bool MakeUserProfileDirs()
{
	char path[512];

J
jp9000 已提交
432 433 434 435 436
	if (GetConfigPath(path, sizeof(path), "obs-studio/basic/profiles") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;

J
jp9000 已提交
437 438 439 440 441 442 443 444
	if (GetConfigPath(path, sizeof(path), "obs-studio/basic/scenes") <= 0)
		return false;
	if (!do_mkdir(path))
		return false;

	return true;
}

445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
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;

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

	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;

		const char *curName = config_get_string(config, "General",
				"Name");
		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;
}

536 537
bool OBSApp::InitGlobalConfig()
{
538 539
	char path[512];

540
	int len = GetConfigPath(path, sizeof(path),
541 542 543 544
			"obs-studio/global.ini");
	if (len <= 0) {
		return false;
	}
545

546
	int errorcode = globalConfig.Open(path, CONFIG_OPEN_ALWAYS);
547
	if (errorcode != CONFIG_SUCCESS) {
548
		OBSErrorBox(NULL, "Failed to open global.ini: %d", errorcode);
549 550 551
		return false;
	}

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575
	if (!opt_starting_collection.empty()) {
		string path = GetSceneCollectionFileFromName(
				opt_starting_collection.c_str());
		if (!path.empty()) {
			config_set_string(globalConfig,
					"Basic", "SceneCollection",
					opt_starting_collection.c_str());
			config_set_string(globalConfig,
					"Basic", "SceneCollectionFile",
					path.c_str());
		}
	}

	if (!opt_starting_profile.empty()) {
		string path = GetProfileDirFromName(
				opt_starting_profile.c_str());
		if (!path.empty()) {
			config_set_string(globalConfig, "Basic", "Profile",
					opt_starting_profile.c_str());
			config_set_string(globalConfig, "Basic", "ProfileDir",
					path.c_str());
		}
	}

576
	return InitGlobalConfigDefaults();
577
}
578

579 580
bool OBSApp::InitLocale()
{
P
Palana 已提交
581
	ProfileScope("OBSApp::InitLocale");
582 583 584
	const char *lang = config_get_string(globalConfig, "General",
			"Language");

585 586
	locale = lang;

587
	string englishPath;
588 589
	if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) {
		OBSErrorBox(NULL, "Failed to find locale/" DEFAULT_LANG ".ini");
590 591 592 593 594 595 596 597 598 599
		return false;
	}

	textLookup = text_lookup_create(englishPath.c_str());
	if (!textLookup) {
		OBSErrorBox(NULL, "Failed to create locale from file '%s'",
				englishPath.c_str());
		return false;
	}

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
	bool userLocale = config_has_user_value(globalConfig, "General",
			"Language");
	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'",
					locale_.c_str());
			locale = locale_;
			return true;
		}

628
		return true;
629 630 631 632
	}

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

634
	string path;
635 636
	if (GetDataFilePath(file.str().c_str(), path)) {
		if (!text_lookup_add(textLookup, path.c_str()))
J
jp9000 已提交
637
			blog(LOG_ERROR, "Failed to add locale file '%s'",
638 639
					path.c_str());
	} else {
J
jp9000 已提交
640
		blog(LOG_ERROR, "Could not find locale file '%s'",
641
				file.str().c_str());
642 643 644 645 646
	}

	return true;
}

S
Socapex 已提交
647 648 649 650 651 652 653 654 655
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;
656
		int ret = GetConfigPath(userDir, sizeof(userDir),
S
Socapex 已提交
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
				temp.c_str());

		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();
	setStyleSheet(mpath);
	return true;
}

bool OBSApp::InitTheme()
{
	const char *themeName = config_get_string(globalConfig, "General",
			"Theme");

	if (!themeName)
		themeName = "Default";

	stringstream t;
	t << themeName;
	return SetTheme(t.str());
}

P
Palana 已提交
685 686 687
OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store)
	: QApplication(argc, argv),
	  profilerNameStore(store)
688 689 690 691 692 693
{
	sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio");
}

OBSApp::~OBSApp()
{
694 695 696 697 698 699 700 701 702
#ifdef __APPLE__
	bool vsyncDiabled = config_get_bool(globalConfig, "Video",
			"DisableOSXVSync");
	bool resetVSync = config_get_bool(globalConfig, "Video",
			"ResetOSXVSyncOnExit");
	if (vsyncDiabled && resetVSync)
		EnableOSXVSync(true);
#endif

703 704 705
	os_inhibit_sleep_set_active(sleepInhibitor, false);
	os_inhibit_sleep_destroy(sleepInhibitor);
}
706

J
jp9000 已提交
707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761
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 已提交
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
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);
}

788
void OBSApp::AppInit()
789
{
P
Palana 已提交
790 791
	ProfileScope("OBSApp::AppInit");

792
	if (!InitApplicationBundle())
J
jp9000 已提交
793
		throw "Failed to initialize application bundle";
794
	if (!MakeUserDirs())
J
jp9000 已提交
795
		throw "Failed to create required user directories";
796
	if (!InitGlobalConfig())
J
jp9000 已提交
797
		throw "Failed to initialize global config";
798
	if (!InitLocale())
J
jp9000 已提交
799
		throw "Failed to load locale";
S
Socapex 已提交
800 801
	if (!InitTheme())
		throw "Failed to load theme";
J
jp9000 已提交
802 803 804 805 806

	config_set_default_string(globalConfig, "Basic", "Profile",
			Str("Untitled"));
	config_set_default_string(globalConfig, "Basic", "ProfileDir",
			Str("Untitled"));
J
jp9000 已提交
807 808 809 810 811
	config_set_default_string(globalConfig, "Basic", "SceneCollection",
			Str("Untitled"));
	config_set_default_string(globalConfig, "Basic", "SceneCollectionFile",
			Str("Untitled"));

812 813 814 815 816
#ifdef __APPLE__
	if (config_get_bool(globalConfig, "Video", "DisableOSXVSync"))
		EnableOSXVSync(false);
#endif

J
jp9000 已提交
817
	move_basic_to_profiles();
J
jp9000 已提交
818 819 820 821
	move_basic_to_scene_collections();

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

J
jp9000 已提交
824
const char *OBSApp::GetRenderModule() const
825
{
J
jp9000 已提交
826 827 828
	const char *renderer = config_get_string(globalConfig, "Video",
			"Renderer");

J
jp9000 已提交
829
	return (astrcmpi(renderer, "Direct3D 11") == 0) ?
830
		DL_D3D11 : DL_OPENGL;
J
jp9000 已提交
831
}
J
jp9000 已提交
832

833 834 835 836 837 838 839 840 841 842
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);
}

J
jp9000 已提交
843
bool OBSApp::OBSInit()
844
{
P
Palana 已提交
845 846
	ProfileScope("OBSApp::OBSInit");

J
jp9000 已提交
847 848 849 850 851 852 853 854 855 856 857
	bool licenseAccepted = config_get_bool(globalConfig, "General",
			"LicenseAccepted");
	OBSLicenseAgreement agreement(nullptr);

	if (licenseAccepted || agreement.exec() == QDialog::Accepted) {
		if (!licenseAccepted) {
			config_set_bool(globalConfig, "General",
					"LicenseAccepted", true);
			config_save(globalConfig);
		}

858 859 860
		if (!StartupOBS(locale.c_str(), GetProfilerNameStore()))
			return false;

861 862 863 864 865
		mainWindow = new OBSBasic();

		mainWindow->setAttribute(Qt::WA_DeleteOnClose, true);
		connect(mainWindow, SIGNAL(destroyed()), this, SLOT(quit()));

J
jp9000 已提交
866 867
		mainWindow->OBSInit();

P
Palana 已提交
868 869 870 871 872 873 874 875
		connect(this, &QGuiApplication::applicationStateChanged,
				[](Qt::ApplicationState state)
				{
					obs_hotkey_enable_background_press(
						state != Qt::ApplicationActive);
				});
		obs_hotkey_enable_background_press(
				applicationState() != Qt::ApplicationActive);
J
jp9000 已提交
876 877 878 879
		return true;
	} else {
		return false;
	}
880 881
}

J
jp9000 已提交
882 883 884
string OBSApp::GetVersionString() const
{
	stringstream ver;
J
jp9000 已提交
885

J
jp9000 已提交
886
#ifdef HAVE_OBSCONFIG_H
887 888 889 890 891
	ver << OBS_VERSION;
#else
	ver <<  LIBOBS_API_MAJOR_VER << "." <<
		LIBOBS_API_MINOR_VER << "." <<
		LIBOBS_API_PATCH_VER;
892

J
jp9000 已提交
893
#endif
894
	ver << " (";
J
jp9000 已提交
895 896

#ifdef _WIN32
J
jp9000 已提交
897
	if (sizeof(void*) == 8)
J
jp9000 已提交
898
		ver << "64bit, ";
J
jp9000 已提交
899

J
jp9000 已提交
900 901 902
	ver << "windows)";
#elif __APPLE__
	ver << "mac)";
903 904
#elif __FreeBSD__
	ver << "freebsd)";
J
jp9000 已提交
905 906 907
#else /* assume linux for the time being */
	ver << "linux)";
#endif
J
jp9000 已提交
908

J
jp9000 已提交
909 910 911
	return ver.str();
}

J
jp9000 已提交
912
#ifdef __APPLE__
J
jp9000 已提交
913 914
#define INPUT_AUDIO_SOURCE  "coreaudio_input_capture"
#define OUTPUT_AUDIO_SOURCE "coreaudio_output_capture"
J
jp9000 已提交
915 916 917 918
#elif _WIN32
#define INPUT_AUDIO_SOURCE  "wasapi_input_capture"
#define OUTPUT_AUDIO_SOURCE "wasapi_output_capture"
#else
919 920
#define INPUT_AUDIO_SOURCE  "pulse_input_capture"
#define OUTPUT_AUDIO_SOURCE "pulse_output_capture"
J
jp9000 已提交
921 922 923 924 925 926 927 928 929 930 931 932
#endif

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

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

J
jp9000 已提交
933 934 935 936 937 938 939 940 941 942
const char *OBSApp::GetLastLog() const
{
	return lastLogFile.c_str();
}

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

J
jp9000 已提交
943 944 945 946 947 948 949 950 951 952
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 已提交
953 954 955 956
QString OBSTranslator::translate(const char *context, const char *sourceText,
		const char *disambiguation, int n) const
{
	const char *out = nullptr;
J
jp9000 已提交
957 958
	if (!App()->TranslateString(sourceText, &out))
		return QString(sourceText);
J
jp9000 已提交
959 960 961 962 963 964 965

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

J
jp9000 已提交
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011
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;
}

static uint64_t convert_log_name(const char *name)
{
	BaseLexer  lex;
	string     year, month, day, hour, minute, second;

	lexer_start(lex, name);

	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;

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

J
jp9000 已提交
1012
static void delete_oldest_file(const char *location)
J
jp9000 已提交
1013
{
1014
	BPtr<char>       logDir(GetConfigPathPtr(location));
J
jp9000 已提交
1015
	string           oldestLog;
J
jp9000 已提交
1016
	uint64_t         oldest_ts = (uint64_t)-1;
J
jp9000 已提交
1017
	struct os_dirent *entry;
1018

J
jp9000 已提交
1019 1020
	unsigned int maxLogs = (unsigned int)config_get_uint(
			App()->GlobalConfig(), "General", "MaxLogs");
1021

1022
	os_dir_t *dir = os_opendir(logDir);
J
jp9000 已提交
1023 1024
	if (dir) {
		unsigned int count = 0;
1025

J
jp9000 已提交
1026
		while ((entry = os_readdir(dir)) != NULL) {
J
jp9000 已提交
1027
			if (entry->directory || *entry->d_name == '.')
J
jp9000 已提交
1028 1029
				continue;

J
jp9000 已提交
1030
			uint64_t ts = convert_log_name(entry->d_name);
J
jp9000 已提交
1031

J
jp9000 已提交
1032 1033 1034 1035 1036
			if (ts) {
				if (ts < oldest_ts) {
					oldestLog = entry->d_name;
					oldest_ts = ts;
				}
J
jp9000 已提交
1037

J
jp9000 已提交
1038 1039
				count++;
			}
J
jp9000 已提交
1040 1041 1042 1043
		}

		os_closedir(dir);

J
jp9000 已提交
1044
		if (count > maxLogs) {
J
jp9000 已提交
1045 1046
			stringstream delPath;

J
jp9000 已提交
1047
			delPath << logDir << "/" << oldestLog;
J
jp9000 已提交
1048 1049 1050 1051 1052
			os_unlink(delPath.str().c_str());
		}
	}
}

J
jp9000 已提交
1053 1054
static void get_last_log(void)
{
1055
	BPtr<char>       logDir(GetConfigPathPtr("obs-studio/logs"));
J
jp9000 已提交
1056
	struct os_dirent *entry;
1057
	os_dir_t         *dir        = os_opendir(logDir);
J
jp9000 已提交
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
	uint64_t         highest_ts = 0;

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

			uint64_t ts = convert_log_name(entry->d_name);

			if (ts > highest_ts) {
				lastLogFile = entry->d_name;
				highest_ts  = ts;
			}
		}

		os_closedir(dir);
	}
}

1077
string GenerateTimeDateFilename(const char *extension, bool noSpace)
J
jp9000 已提交
1078
{
1079 1080 1081
	time_t    now = time(0);
	char      file[256] = {};
	struct tm *cur_time;
J
jp9000 已提交
1082

J
jp9000 已提交
1083
	cur_time = localtime(&now);
1084
	snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s",
1085 1086 1087
			cur_time->tm_year+1900,
			cur_time->tm_mon+1,
			cur_time->tm_mday,
1088
			noSpace ? '_' : ' ',
1089 1090 1091 1092 1093 1094 1095
			cur_time->tm_hour,
			cur_time->tm_min,
			cur_time->tm_sec,
			extension);

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

B
bl 已提交
1097 1098 1099 1100 1101 1102 1103 1104 1105
string GenerateSpecifiedFilename(const char *extension, bool noSpace,
		const char *format)
{
	time_t now = time(0);
	struct tm *cur_time;
	cur_time = localtime(&now);

	const size_t spec_count = 23;
	const char *spec[][2] = {
B
bl 已提交
1106 1107 1108 1109
		{"%CCYY", "%Y"},
		{"%YY",   "%y"},
		{"%MM",   "%m"},
		{"%DD",   "%d"},
B
bl 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 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
		{"%hh",   "%H"},
		{"%mm",   "%M"},
		{"%ss",   "%S"},
		{"%%",    "%%"},

		{"%a",    ""},
		{"%A",    ""},
		{"%b",    ""},
		{"%B",    ""},
		{"%d",    ""},
		{"%H",    ""},
		{"%I",    ""},
		{"%m",    ""},
		{"%M",    ""},
		{"%p",    ""},
		{"%S",    ""},
		{"%y",    ""},
		{"%Y",    ""},
		{"%z",    ""},
		{"%Z",    ""},
	};

	char convert[128] = {};
	string sf = format;
	string c;
	size_t pos = 0, len;

	while (pos < sf.length()) {
		len = 0;
		for (size_t i = 0; i < spec_count && len == 0; i++) {

			if (sf.find(spec[i][0], pos) == pos) {
				if (strlen(spec[i][1]))
					strftime(convert, sizeof(convert),
							spec[i][1], cur_time);
				else
					strftime(convert, sizeof(convert),
							spec[i][0], cur_time);

				len = strlen(spec[i][0]);

				c = convert;
				if (c.length() && c.find_first_not_of(' ') !=
						std::string::npos)
					sf.replace(pos, len, convert);
			}
		}

		if (len)
			pos += strlen(convert);
		else if (!len && sf.at(pos) == '%')
			sf.erase(pos,1);
		else
			pos++;
	}

	if (noSpace)
		replace(sf.begin(), sf.end(), ' ', '_');

	sf += '.';
	sf += extension;

	return (sf.length() < 256) ? sf : sf.substr(0, 255);
}

1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197
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;
}

1198 1199 1200
static void create_log_file(fstream &logFile)
{
	stringstream dst;
J
jp9000 已提交
1201

1202
	get_last_log();
J
jp9000 已提交
1203

1204 1205
	currentLogFile = GenerateTimeDateFilename("txt");
	dst << "obs-studio/logs/" << currentLogFile.c_str();
J
jp9000 已提交
1206

1207
	BPtr<char> path(GetConfigPathPtr(dst.str().c_str()));
1208 1209
	logFile.open(path,
			ios_base::in | ios_base::out | ios_base::trunc);
J
jp9000 已提交
1210 1211

	if (logFile.is_open()) {
J
jp9000 已提交
1212
		delete_oldest_file("obs-studio/logs");
1213
		base_set_log_handler(do_log, &logFile);
J
jp9000 已提交
1214 1215 1216 1217 1218
	} else {
		blog(LOG_ERROR, "Failed to open log file");
	}
}

P
Palana 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238
static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store)
{
	profiler_name_store_free(store);
};

using ProfilerNameStore =
	std::unique_ptr<profiler_name_store_t,
			decltype(ProfilerNameStoreRelease)>;

ProfilerNameStore CreateNameStore()
{
	return ProfilerNameStore{profiler_name_store_create(),
					ProfilerNameStoreRelease};
}

static auto SnapshotRelease = [](profiler_snapshot_t *snap)
{
	profile_snapshot_free(snap);
};

J
jp9000 已提交
1239
using ProfilerSnapshot =
P
Palana 已提交
1240 1241 1242 1243 1244 1245 1246
	std::unique_ptr<profiler_snapshot_t, decltype(SnapshotRelease)>;

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

P
Palana 已提交
1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
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'",
				static_cast<const char*>(path));
}

P
Palana 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277
static auto ProfilerFree = [](void *)
{
	profiler_stop();

	auto snap = GetSnapshot();

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

P
Palana 已提交
1278 1279
	SaveProfilerData(snap);

P
Palana 已提交
1280 1281 1282
	profiler_free();
};

P
Palana 已提交
1283
static const char *run_program_init = "run_program_init";
J
jp9000 已提交
1284 1285 1286
static int run_program(fstream &logFile, int argc, char *argv[])
{
	int ret = -1;
P
Palana 已提交
1287 1288 1289 1290 1291 1292 1293 1294

	auto profilerNameStore = CreateNameStore();

	std::unique_ptr<void, decltype(ProfilerFree)>
		prof_release(static_cast<void*>(&ProfilerFree),
				ProfilerFree);

	profiler_start();
P
Palana 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311
	profile_register_root(run_program_init, 0);

	auto PrintInitProfile = [&]()
	{
		auto snap = GetSnapshot();

		profiler_snapshot_filter_roots(snap.get(), [](void *data,
					const char *name, bool *remove)
		{
			*remove = (*static_cast<const char**>(data)) != name;
			return true;
		}, static_cast<void*>(&run_program_init));

		profiler_print(snap.get());
	};

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

J
jp9000 已提交
1313
	QCoreApplication::addLibraryPath(".");
J
jp9000 已提交
1314

C
Colin Edwards 已提交
1315
#if (QT_VERSION >= QT_VERSION_CHECK(5, 6, 0))
C
Colin Edwards 已提交
1316
	QApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
C
Colin Edwards 已提交
1317
#endif
C
Colin Edwards 已提交
1318

P
Palana 已提交
1319
	OBSApp program(argc, argv, profilerNameStore.get());
J
jp9000 已提交
1320
	try {
1321 1322
		program.AppInit();

J
jp9000 已提交
1323 1324 1325
		OBSTranslator translator;

		create_log_file(logFile);
P
Palana 已提交
1326
		delete_oldest_file("obs-studio/profiler_data");
J
jp9000 已提交
1327 1328 1329

		program.installTranslator(&translator);

P
Palana 已提交
1330 1331 1332
		if (!program.OBSInit())
			return 0;

P
Palana 已提交
1333 1334
		prof.Stop();

P
Palana 已提交
1335
		return program.exec();
J
jp9000 已提交
1336 1337 1338

	} catch (const char *error) {
		blog(LOG_ERROR, "%s", error);
1339
		OBSErrorBox(nullptr, "%s", error);
J
jp9000 已提交
1340 1341
	}

J
jp9000 已提交
1342 1343 1344
	return ret;
}

J
jp9000 已提交
1345 1346
#define MAX_CRASH_REPORT_SIZE (50 * 1024)

J
jp9000 已提交
1347 1348 1349 1350 1351 1352 1353
#ifdef _WIN32

#define CRASH_MESSAGE \
	"Woops, OBS has crashed!\n\nWould you like to copy the crash log " \
	"to the clipboard?  (Crash logs will still be saved to the " \
	"%appdata%\\obs-studio\\crashes directory)"

J
jp9000 已提交
1354 1355
static void main_crash_handler(const char *format, va_list args, void *param)
{
J
jp9000 已提交
1356 1357 1358
	char *text = new char[MAX_CRASH_REPORT_SIZE];

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

J
jp9000 已提交
1361 1362 1363 1364 1365
	delete_oldest_file("obs-studio/crashes");

	string name = "obs-studio/crashes/Crash ";
	name += GenerateTimeDateFilename("txt");

1366
	BPtr<char> path(GetConfigPathPtr(name.c_str()));
J
jp9000 已提交
1367 1368

	fstream file;
1369 1370
	file.open(path, ios_base::in | ios_base::out | ios_base::trunc |
			ios_base::binary);
J
jp9000 已提交
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388
	file << text;
	file.close();

	int ret = MessageBoxA(NULL, CRASH_MESSAGE, "OBS has crashed!",
			MB_YESNO | MB_ICONERROR | MB_TASKMODAL);

	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 已提交
1389 1390 1391 1392 1393 1394

	exit(-1);

	UNUSED_PARAMETER(param);
}

J
jp9000 已提交
1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410
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 已提交
1411
		AdjustTokenPrivileges(token, false, &tp,
J
jp9000 已提交
1412 1413 1414 1415 1416 1417 1418
				sizeof(tp), NULL, NULL);
	}

	CloseHandle(token);
}
#endif

J
jp9000 已提交
1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
#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);
	}
}

1459 1460 1461 1462 1463 1464 1465 1466 1467 1468
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);
}

1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527
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);
	os_utf8_to_wcs(name, base_len, &wfile[0], len);

	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);
	os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len);
	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;
}

1528
bool WindowPositionValid(QRect rect)
1529
{
1530 1531
	for (QScreen* screen: QGuiApplication::screens()) {
		if (screen->availableGeometry().intersects(rect))
1532 1533 1534 1535 1536
			return true;
	}
	return false;
}

J
jp9000 已提交
1537 1538 1539 1540 1541 1542 1543
static inline bool arg_is(const char *arg,
		const char *long_form, const char *short_form)
{
	return (long_form  && strcmp(arg, long_form)  == 0) ||
	       (short_form && strcmp(arg, short_form) == 0);
}

1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560
#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;
1561 1562 1563 1564 1565 1566 1567

	/* 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;

1568 1569 1570 1571 1572 1573 1574 1575 1576
	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 已提交
1577
static bool update_ffmpeg_output(ConfigFile &config)
1578 1579
{
	if (config_has_user_value(config, "AdvOut", "FFOutputToFile"))
J
jp9000 已提交
1580
		return false;
1581 1582 1583

	const char *url = config_get_string(config, "AdvOut", "FFURL");
	if (!url)
J
jp9000 已提交
1584
		return false;
1585 1586 1587

	bool isActualURL = strstr(url, "://") != nullptr;
	if (isActualURL)
J
jp9000 已提交
1588
		return false;
1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606

	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 已提交
1607
		return false;
1608 1609 1610 1611 1612

	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 已提交
1613
	return true;
1614 1615
}

1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
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;

	const char *section = (strcmp(mode, "Advanced") == 0) ?
		"AdvOut" : "SimpleOutput";

	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;
}

1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679
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");
1680 1681
	bool modified = false;
	bool cbr = true;
1682

1683 1684 1685
	if (cbr_item) {
		cbr = obs_data_item_get_bool(cbr_item);
		obs_data_item_unset_user_value(cbr_item);
1686

1687 1688 1689 1690
		obs_data_set_string(data, "rate_control", cbr ? "CBR" : "VBR");

		modified = true;
	}
1691

1692 1693
	if (!rc_item && astrcmpi(encoder, "obs_x264") == 0) {
		if (!cbr_item)
1694
			obs_data_set_string(data, "rate_control", "CBR");
1695
		else if (!cbr)
1696 1697
			convert_x264_settings(data);

1698
		modified = true;
1699 1700
	}

1701 1702 1703
	if (modified)
		obs_data_save_json_safe(data, file, "tmp", "bak");

1704 1705 1706 1707 1708
	obs_data_item_release(&rc_item);
	obs_data_item_release(&cbr_item);
	obs_data_release(data);
}

1709
static void upgrade_settings(void)
1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725
{
	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) {
1726 1727
		if (ent->directory && strcmp(ent->d_name, ".") != 0 &&
				strcmp(ent->d_name, "..") != 0) {
1728 1729 1730 1731
			strcat(path, "/");
			strcat(path, ent->d_name);
			strcat(path, "/basic.ini");

J
jp9000 已提交
1732 1733 1734 1735 1736
			ConfigFile config;
			int ret;

			ret = config.Open(path, CONFIG_OPEN_EXISTING);
			if (ret == CONFIG_SUCCESS) {
1737 1738
				if (update_ffmpeg_output(config) ||
				    update_reconnect(config)) {
J
jp9000 已提交
1739 1740 1741 1742
					config_save_safe(config, "tmp",
							nullptr);
				}
			}
1743

1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765

			if (config) {
				const char *sEnc = config_get_string(config,
						"AdvOut", "Encoder");
				const char *rEnc = config_get_string(config,
						"AdvOut", "RecEncoder");

				/* 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);
			}

1766 1767 1768 1769 1770 1771 1772 1773 1774
			path[pathlen] = 0;
		}

		ent = os_readdir(dir);
	}

	os_closedir(dir);
}

J
jp9000 已提交
1775 1776
int main(int argc, char *argv[])
{
M
martell 已提交
1777
#ifndef _WIN32
J
jp9000 已提交
1778 1779 1780
	signal(SIGPIPE, SIG_IGN);
#endif

J
jp9000 已提交
1781 1782
#ifdef _WIN32
	load_debug_privilege();
J
jp9000 已提交
1783
	base_set_crash_handler(main_crash_handler, nullptr);
J
jp9000 已提交
1784 1785
#endif

J
jp9000 已提交
1786 1787
	base_get_log_handler(&def_log_handler, nullptr);

1788 1789 1790 1791
#if defined(USE_XDG) && defined(IS_UNIX)
	move_to_xdg();
#endif

J
jp9000 已提交
1792 1793 1794
	for (int i = 1; i < argc; i++) {
		if (arg_is(argv[i], "--portable", "-p")) {
			portable_mode = true;
1795

1796 1797 1798 1799 1800 1801
		} else if (arg_is(argv[i], "--startstreaming", nullptr)) {
			opt_start_streaming = true;

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

1802 1803 1804 1805 1806 1807
		} else if (arg_is(argv[i], "--collection", nullptr)) {
			if (++i < argc) opt_starting_collection = argv[i];

		} else if (arg_is(argv[i], "--profile", nullptr)) {
			if (++i < argc) opt_starting_profile = argv[i];

1808 1809
		} else if (arg_is(argv[i], "--scene", nullptr)) {
			if (++i < argc) opt_starting_scene = argv[i];
J
jp9000 已提交
1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822
		}
	}

#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

1823
	upgrade_settings();
1824

J
jp9000 已提交
1825 1826
	fstream logFile;

1827
	curl_global_init(CURL_GLOBAL_ALL);
J
jp9000 已提交
1828 1829
	int ret = run_program(logFile, argc, argv);

J
jp9000 已提交
1830
	blog(LOG_INFO, "Number of memory leaks: %ld", bnum_allocs());
1831
	base_set_log_handler(nullptr, nullptr);
J
jp9000 已提交
1832 1833
	return ret;
}