Main.cxx 16.9 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3
 * http://www.musicpd.org
Warren Dukes's avatar
Warren Dukes committed
4 5 6 7 8 9 10 11 12 13
 *
 * 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
 * the Free Software Foundation; either version 2 of the License, or
 * (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.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Warren Dukes's avatar
Warren Dukes committed
18 19
 */

20
#include "config.h"
Max Kellermann's avatar
Max Kellermann committed
21
#include "Main.hxx"
22
#include "Instance.hxx"
Max Kellermann's avatar
Max Kellermann committed
23
#include "CommandLine.hxx"
Max Kellermann's avatar
Max Kellermann committed
24
#include "PlaylistFile.hxx"
25
#include "MusicChunk.hxx"
26
#include "StateFile.hxx"
27
#include "player/Thread.hxx"
Max Kellermann's avatar
Max Kellermann committed
28
#include "Mapper.hxx"
29
#include "Permission.hxx"
Max Kellermann's avatar
Max Kellermann committed
30
#include "Listen.hxx"
31 32
#include "client/Client.hxx"
#include "client/ClientList.hxx"
33
#include "command/AllCommands.hxx"
34
#include "Partition.hxx"
35
#include "tag/Config.hxx"
36
#include "ReplayGainGlobal.hxx"
Max Kellermann's avatar
Max Kellermann committed
37
#include "Idle.hxx"
38
#include "Log.hxx"
39
#include "LogInit.hxx"
Max Kellermann's avatar
Max Kellermann committed
40
#include "input/Init.hxx"
41
#include "event/Loop.hxx"
42
#include "fs/AllocatedPath.hxx"
43
#include "fs/Config.hxx"
44
#include "playlist/PlaylistRegistry.hxx"
45
#include "zeroconf/ZeroconfGlue.hxx"
46
#include "decoder/DecoderList.hxx"
47
#include "AudioParser.hxx"
48
#include "pcm/PcmConvert.hxx"
49
#include "unix/SignalHandlers.hxx"
50
#include "system/FatalError.hxx"
51
#include "thread/Slack.hxx"
52
#include "lib/icu/Init.hxx"
53
#include "config/ConfigGlobal.hxx"
54
#include "config/Param.hxx"
55 56
#include "config/ConfigDefaults.hxx"
#include "config/ConfigOption.hxx"
57
#include "config/ConfigError.hxx"
58
#include "util/RuntimeError.hxx"
Max Kellermann's avatar
Max Kellermann committed
59

60 61 62 63
#ifdef ENABLE_DAEMON
#include "unix/Daemon.hxx"
#endif

64 65
#ifdef ENABLE_DATABASE
#include "db/update/Service.hxx"
66
#include "db/Configured.hxx"
67
#include "db/DatabasePlugin.hxx"
68
#include "db/plugins/simple/SimpleDatabasePlugin.hxx"
69
#include "storage/Configured.hxx"
70
#include "storage/CompositeStorage.hxx"
71 72 73
#ifdef ENABLE_INOTIFY
#include "db/update/InotifyUpdate.hxx"
#endif
74 75
#endif

76 77 78 79
#ifdef ENABLE_NEIGHBOR_PLUGINS
#include "neighbor/Glue.hxx"
#endif

80
#ifdef ENABLE_SQLITE
81
#include "sticker/StickerDatabase.hxx"
82 83
#endif

84
#ifdef ENABLE_ARCHIVE
85
#include "archive/ArchiveList.hxx"
86
#endif
Max Kellermann's avatar
Max Kellermann committed
87

Max Kellermann's avatar
Max Kellermann committed
88
#ifdef ANDROID
89 90
#include "java/Global.hxx"
#include "java/File.hxx"
91
#include "android/Environment.hxx"
92
#include "android/Context.hxx"
93
#include "fs/StandardDirectory.hxx"
94
#include "fs/FileSystem.hxx"
Max Kellermann's avatar
Max Kellermann committed
95 96 97
#include "org_musicpd_Bridge.h"
#endif

98 99 100 101
#ifdef ENABLE_SYSTEMD_DAEMON
#include <systemd/sd-daemon.h>
#endif

Max Kellermann's avatar
Max Kellermann committed
102
#include <stdlib.h>
103

104
#ifdef HAVE_LOCALE_H
105 106 107
#include <locale.h>
#endif

108
#ifdef _WIN32
109 110 111 112
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

113
#ifdef __BLOCKS__
114 115 116
#include <dispatch/dispatch.h>
#endif

117 118
#include <limits.h>

119 120 121 122
static constexpr size_t KILOBYTE = 1024;
static constexpr size_t MEGABYTE = 1024 * KILOBYTE;

static constexpr size_t DEFAULT_BUFFER_SIZE = 4 * MEGABYTE;
123 124 125 126 127 128 129 130 131 132

static
#if GCC_OLDER_THAN(5,0)
/* gcc 4.x has no "constexpr" for std::max() */
const
#else
constexpr
#endif
size_t MIN_BUFFER_SIZE = std::max(CHUNK_SIZE * 32,
				  64 * KILOBYTE);
133

134
static constexpr unsigned DEFAULT_BUFFER_BEFORE_PLAY = 10;
Max Kellermann's avatar
Max Kellermann committed
135

136 137 138 139
#ifdef ANDROID
Context *context;
#endif

140
Instance *instance;
141

142
struct Config {
143
	ReplayGainConfig replay_gain;
144 145 146 147 148
};

static Config
LoadConfig()
{
149
	return {LoadReplayGainConfig()};
150 151
}

152
#ifdef ENABLE_DAEMON
153

154 155
static void
glue_daemonize_init(const struct options *options)
156
{
157 158
	daemonize_init(config_get_string(ConfigOption::USER, nullptr),
		       config_get_string(ConfigOption::GROUP, nullptr),
159
		       config_get_path(ConfigOption::PID_FILE));
160 161 162 163 164

	if (options->kill)
		daemonize_kill();
}

165 166
#endif

167 168
static void
glue_mapper_init()
169
{
170
	mapper_init(config_get_path(ConfigOption::PLAYLIST_DIR));
171
}
172

173 174
#ifdef ENABLE_DATABASE

175
static void
176
InitStorage(EventLoop &event_loop)
177
{
178
	auto storage = CreateConfiguredStorage(event_loop);
179
	if (storage == nullptr)
180
		return;
181 182 183

	CompositeStorage *composite = new CompositeStorage();
	instance->storage = composite;
184
	composite->Mount("", std::move(storage));
185 186
}

187 188 189 190 191 192
/**
 * Returns the database.  If this function returns false, this has not
 * succeeded, and the caller should create the database after the
 * process has been daemonized.
 */
static bool
193
glue_db_init_and_load(void)
194
{
195
	instance->database =
196 197 198
		CreateConfiguredDatabase(instance->event_loop,
					 instance->io_thread.GetEventLoop(),
					 *instance);
199 200
	if (instance->database == nullptr)
		return true;
201

202
	if (instance->database->GetPlugin().flags & DatabasePlugin::FLAG_REQUIRE_STORAGE) {
203
		InitStorage(instance->io_thread.GetEventLoop());
204

205 206 207 208 209 210 211 212 213 214 215 216 217
		if (instance->storage == nullptr) {
			delete instance->database;
			instance->database = nullptr;
			LogDefault(config_domain,
				   "Found database setting without "
				   "music_directory - disabling database");
			return true;
		}
	} else {
		if (IsStorageConfigured())
			LogDefault(config_domain,
				   "Ignoring the storage configuration "
				   "because the database does not need it");
218 219
	}

220 221 222 223 224
	try {
		instance->database->Open();
	} catch (...) {
		std::throw_with_nested(std::runtime_error("Failed to open database plugin"));
	}
225

226
	if (!instance->database->IsPlugin(simple_db_plugin))
227 228
		return true;

229
	SimpleDatabase &db = *(SimpleDatabase *)instance->database;
230
	instance->update = new UpdateService(instance->event_loop, db,
Max Kellermann's avatar
Max Kellermann committed
231
					     static_cast<CompositeStorage &>(*instance->storage),
232
					     *instance);
233

234
	/* run database update after daemonization? */
235
	return db.FileExists();
Warren Dukes's avatar
Warren Dukes committed
236
}
Warren Dukes's avatar
Warren Dukes committed
237

238 239 240 241 242 243 244
static bool
InitDatabaseAndStorage()
{
	const bool create_db = !glue_db_init_and_load();
	return create_db;
}

245 246
#endif

247 248 249 250
/**
 * Configure and initialize the sticker subsystem.
 */
static void
251
glue_sticker_init()
252 253
{
#ifdef ENABLE_SQLITE
254 255
	auto sticker_file = config_get_path(ConfigOption::STICKER_FILE);
	if (sticker_file.IsNull())
256
		return;
257

258
	sticker_global_init(std::move(sticker_file));
259 260 261
#endif
}

262 263
static void
glue_state_file_init()
264
{
265
	auto path_fs = config_get_path(ConfigOption::STATE_FILE);
266 267 268 269
	if (path_fs.IsNull()) {
#ifdef ANDROID
		const auto cache_dir = GetUserCacheDir();
		if (cache_dir.IsNull())
270
			return;
271 272 273

		path_fs = AllocatedPath::Build(cache_dir, "state");
#else
274
		return;
275 276
#endif
	}
277

278
	const auto interval =
279 280
		config_get_unsigned(ConfigOption::STATE_FILE_INTERVAL,
				    StateFile::DEFAULT_INTERVAL);
281

282
	instance->state_file = new StateFile(std::move(path_fs), interval,
283
					     instance->partitions.front(),
284 285
					     instance->event_loop);
	instance->state_file->Read();
286 287
}

288 289 290 291 292
/**
 * Windows-only initialization of the Winsock2 library.
 */
static void winsock_init(void)
{
293
#ifdef _WIN32
294 295
	WSADATA sockinfo;

296
	int retval = WSAStartup(MAKEWORD(2, 2), &sockinfo);
297
	if(retval != 0)
298 299
		FormatFatalError("Attempt to open Winsock2 failed; error code %d",
				 retval);
300 301

	if (LOBYTE(sockinfo.wVersion) != 2)
302 303
		FatalError("We use Winsock2 but your version is either too new "
			   "or old; please install Winsock 2.x");
304
#endif
305
}
306

Max Kellermann's avatar
Max Kellermann committed
307 308 309 310
/**
 * Initialize the decoder and player core, including the music pipe.
 */
static void
311
initialize_decoder_and_player(const ReplayGainConfig &replay_gain_config)
Max Kellermann's avatar
Max Kellermann committed
312
{
313
	const ConfigParam *param;
Max Kellermann's avatar
Max Kellermann committed
314

315
	size_t buffer_size;
316
	param = config_get_param(ConfigOption::AUDIO_BUFFER_SIZE);
317
	if (param != nullptr) {
318
		char *test;
319
		long tmp = strtol(param->value.c_str(), &test, 10);
320
		if (*test != '\0' || tmp <= 0 || tmp == LONG_MAX)
321 322
			FormatFatalError("buffer size \"%s\" is not a "
					 "positive integer, line %i",
323
					 param->value.c_str(), param->line);
324
		buffer_size = tmp * KILOBYTE;
325 326 327 328 329 330 331

		if (buffer_size < MIN_BUFFER_SIZE) {
			FormatWarning(config_domain, "buffer size %lu is too small, using %lu bytes instead",
				      (unsigned long)buffer_size,
				      (unsigned long)MIN_BUFFER_SIZE);
			buffer_size = MIN_BUFFER_SIZE;
		}
Max Kellermann's avatar
Max Kellermann committed
332 333 334
	} else
		buffer_size = DEFAULT_BUFFER_SIZE;

335
	const unsigned buffered_chunks = buffer_size / CHUNK_SIZE;
Max Kellermann's avatar
Max Kellermann committed
336 337

	if (buffered_chunks >= 1 << 15)
338 339
		FormatFatalError("buffer size \"%lu\" is too big",
				 (unsigned long)buffer_size);
Max Kellermann's avatar
Max Kellermann committed
340

341
	float perc;
342
	param = config_get_param(ConfigOption::BUFFER_BEFORE_PLAY);
343
	if (param != nullptr) {
344
		char *test;
345
		perc = strtod(param->value.c_str(), &test);
Max Kellermann's avatar
Max Kellermann committed
346
		if (*test != '%' || perc < 0 || perc > 100) {
347 348 349
			FormatFatalError("buffered before play \"%s\" is not "
					 "a positive percentage and less "
					 "than 100 percent, line %i",
350
					 param->value.c_str(), param->line);
Max Kellermann's avatar
Max Kellermann committed
351
		}
352 353 354 355 356 357 358 359 360 361 362 363 364

		if (perc > 80) {
			/* this upper limit should avoid deadlocks
			   which can occur because the DecoderThread
			   cannot ever fill the music buffer to
			   exactly 100%; a few chunks always need to
			   be available to generate silence in
			   Player::SendSilence() */
			FormatError(config_domain,
				    "buffer_before_play is too large (%f%%), capping at 80%%; please fix your configuration",
				    perc);
			perc = 80;
		}
Max Kellermann's avatar
Max Kellermann committed
365 366 367
	} else
		perc = DEFAULT_BUFFER_BEFORE_PLAY;

368
	unsigned buffered_before_play = (perc / 100) * buffered_chunks;
Max Kellermann's avatar
Max Kellermann committed
369 370 371
	if (buffered_before_play > buffered_chunks)
		buffered_before_play = buffered_chunks;

372
	const unsigned max_length =
373
		config_get_positive(ConfigOption::MAX_PLAYLIST_LENGTH,
374 375
				    DEFAULT_PLAYLIST_MAX_LENGTH);

376 377 378 379 380 381
	AudioFormat configured_audio_format = AudioFormat::Undefined();
	param = config_get_param(ConfigOption::AUDIO_OUTPUT_FORMAT);
	if (param != nullptr) {
		try {
			configured_audio_format = ParseAudioFormat(param->value.c_str(),
								   true);
382
		} catch (...) {
383 384 385 386 387
			std::throw_with_nested(FormatRuntimeError("error parsing line %i",
								  param->line));
		}
	}

388 389 390 391 392 393 394 395
	instance->partitions.emplace_back(*instance,
					  "default",
					  max_length,
					  buffered_chunks,
					  buffered_before_play,
					  configured_audio_format,
					  replay_gain_config);
	auto &partition = instance->partitions.back();
396 397 398 399

	try {
		param = config_get_param(ConfigOption::REPLAYGAIN);
		if (param != nullptr)
400
			partition.replay_gain_mode =
401 402 403 404 405
				FromString(param->value.c_str());
	} catch (...) {
		std::throw_with_nested(FormatRuntimeError("Failed to parse line %i",
							  param->line));
	}
Max Kellermann's avatar
Max Kellermann committed
406 407
}

408 409
void
Instance::OnIdle(unsigned flags)
410
{
Max Kellermann's avatar
Max Kellermann committed
411
	/* send "idle" notifications to all subscribed
412
	   clients */
413
	client_list->IdleAdd(flags);
414

415
	if (flags & (IDLE_PLAYLIST|IDLE_PLAYER|IDLE_MIXER|IDLE_OUTPUT) &&
416 417
	    state_file != nullptr)
		state_file->CheckModified();
418 419
}

Max Kellermann's avatar
Max Kellermann committed
420 421
#ifndef ANDROID

422
int main(int argc, char *argv[])
423
{
424
#ifdef _WIN32
425 426 427 428 429 430
	return win32_main(argc, argv);
#else
	return mpd_main(argc, argv);
#endif
}

Max Kellermann's avatar
Max Kellermann committed
431 432
#endif

433
static int
434
mpd_main_after_fork(const Config &config);
435

436 437 438
#ifdef ANDROID
static inline
#endif
439
int mpd_main(int argc, char *argv[])
440
try {
Max Kellermann's avatar
Max Kellermann committed
441
	struct options options;
Warren Dukes's avatar
Warren Dukes committed
442

443
#ifdef ENABLE_DAEMON
444
	daemonize_close_stdin();
445
#endif
446

447
#ifndef ANDROID
448
#ifdef HAVE_LOCALE_H
449 450
	/* initialize locale */
	setlocale(LC_CTYPE,"");
451
	setlocale(LC_COLLATE, "");
452
#endif
453
#endif
Max Kellermann's avatar
Max Kellermann committed
454

455
	IcuInit();
456

457
	winsock_init();
458
	config_global_init();
Warren Dukes's avatar
Warren Dukes committed
459

460
#ifdef ANDROID
461 462 463 464 465 466 467 468 469 470
	(void)argc;
	(void)argv;

	const auto sdcard = Environment::getExternalStorageDirectory();
	if (!sdcard.IsNull()) {
		const auto config_path =
			AllocatedPath::Build(sdcard, "mpd.conf");
		if (FileExists(config_path))
			ReadConfigFile(config_path);
	}
471
#else
472
	ParseCommandLine(argc, argv, options);
473
#endif
Warren Dukes's avatar
Warren Dukes committed
474

475 476
	const auto config = LoadConfig();

477
#ifdef ENABLE_DAEMON
478
	glue_daemonize_init(&options);
479
#endif
480

481
	TagLoadConfig();
482

483
	log_init(options.verbose, options.log_stderr);
484

485 486
	instance = new Instance();

487 488
#ifdef ENABLE_NEIGHBOR_PLUGINS
	instance->neighbors = new NeighborGlue();
489 490
	instance->neighbors->Init(instance->io_thread.GetEventLoop(),
				  *instance);
491 492 493 494 495 496 497

	if (instance->neighbors->IsEmpty()) {
		delete instance->neighbors;
		instance->neighbors = nullptr;
	}
#endif

498 499
	const unsigned max_clients =
		config_get_positive(ConfigOption::MAX_CONN, 10);
500
	instance->client_list = new ClientList(max_clients);
501

502
	initialize_decoder_and_player(config.replay_gain);
503

504
	listen_global_init(instance->event_loop, instance->partitions.front());
505

506
#ifdef ENABLE_DAEMON
507
	daemonize_set_user();
508
	daemonize_begin(options.daemon);
509
#endif
Warren Dukes's avatar
Warren Dukes committed
510

511
#ifdef __BLOCKS__
512 513 514 515 516 517 518
	/* Runs the OS X native event loop in the main thread, and runs
	   the rest of mpd_main on a new thread. This lets CoreAudio receive
	   route change notifications (e.g. plugging or unplugging headphones).
	   All hardware output on OS X ultimately uses CoreAudio internally.
	   This must be run after forking; if dispatch is called before forking,
	   the child process will have a broken internal dispatch state. */
	dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
519
		exit(mpd_main_after_fork(config));
520 521 522 523
	});
	dispatch_main();
	return EXIT_FAILURE; // unreachable, because dispatch_main never returns
#else
524
	return mpd_main_after_fork(config);
525
#endif
526 527 528
} catch (const std::exception &e) {
	LogError(e);
	return EXIT_FAILURE;
529 530
}

531
static int
532
mpd_main_after_fork(const Config &config)
533
try {
534
	ConfigureFS();
535

536
	glue_mapper_init();
537

538
	initPermissions();
539
	spl_global_init();
540
#ifdef ENABLE_ARCHIVE
541
	archive_plugin_init_all();
542
#endif
543

544
	pcm_convert_global_init();
545

546
	decoder_plugin_init_all();
547

548
#ifdef ENABLE_DATABASE
549
	const bool create_db = InitDatabaseAndStorage();
550
#endif
551

552
	glue_sticker_init();
553

Max Kellermann's avatar
Max Kellermann committed
554
	command_init();
555

556 557 558 559 560 561
	for (auto &partition : instance->partitions) {
		partition.outputs.Configure(instance->io_thread.GetEventLoop(),
					    config.replay_gain,
					    partition.pc);
		partition.UpdateEffectiveReplayGainMode();
	}
562

563
	client_manager_init();
564
	input_stream_global_init(instance->io_thread.GetEventLoop());
565
	playlist_list_global_init();
566

567
#ifdef ENABLE_DAEMON
568
	daemonize_commit();
569
#endif
570

571
#ifndef ANDROID
572
	setup_log_output();
Warren Dukes's avatar
Warren Dukes committed
573

574
	SignalHandlersInit(instance->event_loop);
575
#endif
576

577
	instance->io_thread.Start();
578

579
#ifdef ENABLE_NEIGHBOR_PLUGINS
580 581
	if (instance->neighbors != nullptr)
		instance->neighbors->Open();
582 583
#endif

584
	ZeroconfInit(instance->event_loop);
585

586 587
	for (auto &partition : instance->partitions)
		StartPlayerThread(partition.pc);
588

589
#ifdef ENABLE_DATABASE
590
	if (create_db) {
591 592
		/* the database failed to load: recreate the
		   database */
593
		unsigned job = instance->update->Enqueue("", true);
594
		if (job == 0)
595
			FatalError("directory update failed");
596
	}
597
#endif
598

599
	glue_state_file_init();
600

601
#ifdef ENABLE_DATABASE
602
	if (config_get_bool(ConfigOption::AUTO_UPDATE, false)) {
603
#ifdef ENABLE_INOTIFY
604
		if (instance->storage != nullptr &&
605
		    instance->update != nullptr)
606
			mpd_inotify_init(instance->event_loop,
607 608
					 *instance->storage,
					 *instance->update,
609
					 config_get_unsigned(ConfigOption::AUTO_UPDATE_DEPTH,
610
							     INT_MAX));
611
#else
612
		FormatWarning(config_domain,
613
			      "inotify: auto_update was disabled. enable during compilation phase");
614
#endif
615
	}
616
#endif
617

618 619
	config_global_check();

620 621
	/* enable all audio outputs (if not already done by
	   playlist_state_restore() */
622 623
	for (auto &partition : instance->partitions)
		partition.pc.LockUpdateAudio();
624

625
#ifdef _WIN32
626 627
	win32_app_started();
#endif
628

629 630 631 632
	/* the MPD frontend does not care about timer slack; set it to
	   a huge value to allow the kernel to reduce CPU wakeups */
	SetThreadTimerSlackMS(100);

633 634 635 636
#ifdef ENABLE_SYSTEMD_DAEMON
	sd_notify(0, "READY=1");
#endif

637
	/* run the main loop */
638
	instance->event_loop.Run();
639

640
#ifdef _WIN32
641 642 643
	win32_app_stopping();
#endif

644 645
	/* cleanup */

646
#if defined(ENABLE_DATABASE) && defined(ENABLE_INOTIFY)
647
	mpd_inotify_finish();
648 649 650

	if (instance->update != nullptr)
		instance->update->CancelAllAsync();
651
#endif
652

653 654 655
	if (instance->state_file != nullptr) {
		instance->state_file->Write();
		delete instance->state_file;
656 657
	}

658 659 660
	for (auto &partition : instance->partitions)
		partition.pc.Kill();

661
	ZeroconfDeinit();
Max Kellermann's avatar
Max Kellermann committed
662
	listen_global_finish();
663
	delete instance->client_list;
664

665 666 667 668 669 670 671
#ifdef ENABLE_NEIGHBOR_PLUGINS
	if (instance->neighbors != nullptr) {
		instance->neighbors->Close();
		delete instance->neighbors;
	}
#endif

672
#ifdef ENABLE_DATABASE
673
	delete instance->update;
674 675 676 677 678

	if (instance->database != nullptr) {
		instance->database->Close();
		delete instance->database;
	}
679 680

	delete instance->storage;
681
#endif
682

683 684 685 686
#ifdef ENABLE_SQLITE
	sticker_global_finish();
#endif

687
	playlist_list_global_finish();
688
	input_stream_global_finish();
689 690

#ifdef ENABLE_DATABASE
691
	mapper_finish();
692 693
#endif

694 695
	DeinitFS();

696
	instance->partitions.clear();
Max Kellermann's avatar
Max Kellermann committed
697
	command_finish();
698
	decoder_plugin_deinit_all();
699
#ifdef ENABLE_ARCHIVE
700
	archive_plugin_deinit_all();
701
#endif
702
	config_global_finish();
703
	instance->io_thread.Stop();
704
#ifndef ANDROID
705
	SignalHandlersFinish();
706
#endif
707
	delete instance;
708
	instance = nullptr;
709 710

#ifdef ENABLE_DAEMON
711
	daemonize_finish();
712
#endif
713

714
#ifdef _WIN32
715 716
	WSACleanup();
#endif
717

718
	IcuFinish();
719

720
	log_deinit();
721
	return EXIT_SUCCESS;
722 723 724
} catch (const std::exception &e) {
	LogError(e);
	return EXIT_FAILURE;
Warren Dukes's avatar
Warren Dukes committed
725
}
Max Kellermann's avatar
Max Kellermann committed
726 727 728 729 730

#ifdef ANDROID

gcc_visibility_default
JNIEXPORT void JNICALL
731
Java_org_musicpd_Bridge_run(JNIEnv *env, jclass, jobject _context)
Max Kellermann's avatar
Max Kellermann committed
732
{
733 734
	Java::Init(env);
	Java::File::Initialise(env);
735
	Environment::Initialise(env);
736

737 738
	context = new Context(env, _context);

Max Kellermann's avatar
Max Kellermann committed
739
	mpd_main(0, nullptr);
740

741
	delete context;
742
	Environment::Deinitialise(env);
Max Kellermann's avatar
Max Kellermann committed
743 744
}

745 746 747 748 749
gcc_visibility_default
JNIEXPORT void JNICALL
Java_org_musicpd_Bridge_shutdown(JNIEnv *, jclass)
{
	if (instance != nullptr)
750
		instance->Shutdown();
751 752
}

Max Kellermann's avatar
Max Kellermann committed
753
#endif