Main.cxx 13.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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 "PlaylistGlobal.hxx"
26
#include "MusicChunk.hxx"
27
#include "StateFile.hxx"
28
#include "PlayerThread.hxx"
Max Kellermann's avatar
Max Kellermann committed
29
#include "Mapper.hxx"
30
#include "Permission.hxx"
Max Kellermann's avatar
Max Kellermann committed
31
#include "Listen.hxx"
32 33
#include "client/Client.hxx"
#include "client/ClientList.hxx"
34
#include "command/AllCommands.hxx"
35
#include "Partition.hxx"
Max Kellermann's avatar
Max Kellermann committed
36
#include "mixer/Volume.hxx"
37
#include "tag/TagConfig.hxx"
38
#include "ReplayGainConfig.hxx"
Max Kellermann's avatar
Max Kellermann committed
39
#include "Idle.hxx"
40
#include "Log.hxx"
41
#include "LogInit.hxx"
42
#include "GlobalEvents.hxx"
Max Kellermann's avatar
Max Kellermann committed
43
#include "input/Init.hxx"
44
#include "event/Loop.hxx"
45
#include "IOThread.hxx"
46
#include "fs/AllocatedPath.hxx"
47
#include "fs/Config.hxx"
48
#include "playlist/PlaylistRegistry.hxx"
49
#include "zeroconf/ZeroconfGlue.hxx"
50
#include "decoder/DecoderList.hxx"
51
#include "AudioConfig.hxx"
52
#include "pcm/PcmConvert.hxx"
53 54
#include "unix/SignalHandlers.hxx"
#include "unix/Daemon.hxx"
55
#include "system/FatalError.hxx"
56
#include "util/UriUtil.hxx"
57
#include "util/Error.hxx"
58
#include "util/Domain.hxx"
59
#include "thread/Id.hxx"
60
#include "thread/Slack.hxx"
61 62 63 64
#include "config/ConfigGlobal.hxx"
#include "config/ConfigData.hxx"
#include "config/ConfigDefaults.hxx"
#include "config/ConfigOption.hxx"
65
#include "config/ConfigError.hxx"
66
#include "Stats.hxx"
Max Kellermann's avatar
Max Kellermann committed
67

68 69
#ifdef ENABLE_DATABASE
#include "db/update/Service.hxx"
70
#include "db/Configured.hxx"
71
#include "db/plugins/SimpleDatabasePlugin.hxx"
72
#include "storage/Configured.hxx"
73
#include "storage/CompositeStorage.hxx"
74 75
#endif

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

80
#ifdef ENABLE_INOTIFY
Max Kellermann's avatar
Max Kellermann committed
81
#include "db/update/InotifyUpdate.hxx"
82
#endif
Warren Dukes's avatar
Warren Dukes committed
83

84
#ifdef ENABLE_SQLITE
85
#include "sticker/StickerDatabase.hxx"
86 87
#endif

88
#ifdef ENABLE_ARCHIVE
89
#include "archive/ArchiveList.hxx"
90
#endif
Max Kellermann's avatar
Max Kellermann committed
91

92
#ifdef HAVE_GLIB
93
#include <glib.h>
94
#endif
95

Max Kellermann's avatar
Max Kellermann committed
96
#include <stdlib.h>
97

98
#ifdef HAVE_LOCALE_H
99 100 101
#include <locale.h>
#endif

102 103 104 105 106
#ifdef WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
#endif

107 108
#include <limits.h>

109
static constexpr unsigned DEFAULT_BUFFER_SIZE = 4096;
110
static constexpr unsigned DEFAULT_BUFFER_BEFORE_PLAY = 10;
Max Kellermann's avatar
Max Kellermann committed
111

112 113
static constexpr Domain main_domain("main");

114
Instance *instance;
115

116 117
static StateFile *state_file;

118
static bool
119
glue_daemonize_init(const struct options *options, Error &error)
120
{
121
	auto pid_file = config_get_path(CONF_PID_FILE, error);
122
	if (pid_file.IsNull() && error.IsDefined())
123 124
		return false;

125 126
	daemonize_init(config_get_string(CONF_USER, nullptr),
		       config_get_string(CONF_GROUP, nullptr),
127
		       std::move(pid_file));
128 129 130

	if (options->kill)
		daemonize_kill();
131 132

	return true;
133 134
}

135
static bool
136
glue_mapper_init(Error &error)
137
{
138
	auto playlist_dir = config_get_path(CONF_PLAYLIST_DIR, error);
139
	if (playlist_dir.IsNull() && error.IsDefined())
140
		return false;
141

142 143 144
	mapper_init(std::move(playlist_dir));
	return true;
}
145

146 147
#ifdef ENABLE_DATABASE

148 149 150
static bool
InitStorage(Error &error)
{
151 152 153 154 155 156 157 158 159 160
	Storage *storage = CreateConfiguredStorage(error);
	if (storage == nullptr)
		return !error.IsDefined();

	assert(!error.IsDefined());

	CompositeStorage *composite = new CompositeStorage();
	instance->storage = composite;
	composite->Mount("", storage);
	return true;
161 162
}

163 164 165 166 167 168
/**
 * 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
169
glue_db_init_and_load(void)
170
{
171
	bool is_simple;
172
	Error error;
173 174 175 176 177 178 179 180 181
	instance->database =
		CreateConfiguredDatabase(*instance->event_loop, *instance,
					 is_simple, error);
	if (instance->database == nullptr) {
		if (error.IsDefined())
			FatalError(error);
		else
			return true;
	}
182

183 184 185 186 187 188 189 190 191 192 193 194
	if (!InitStorage(error))
		FatalError(error);

	if (instance->storage == nullptr) {
		delete instance->database;
		instance->database = nullptr;
		LogDefault(config_domain,
			   "Found database setting without "
			   "music_directory - disabling database");
		return true;
	}

195
	if (!instance->database->Open(error))
196
		FatalError(error);
197

198
	if (!is_simple)
199 200
		return true;

201
	SimpleDatabase &db = *(SimpleDatabase *)instance->database;
202
	instance->update = new UpdateService(*instance->event_loop, db,
203
					     *instance->storage,
204
					     *instance);
205

206
	/* run database update after daemonization? */
207
	return db.FileExists();
Warren Dukes's avatar
Warren Dukes committed
208
}
Warren Dukes's avatar
Warren Dukes committed
209

210 211 212 213 214 215 216
static bool
InitDatabaseAndStorage()
{
	const bool create_db = !glue_db_init_and_load();
	return create_db;
}

217 218
#endif

219 220 221 222 223 224 225
/**
 * Configure and initialize the sticker subsystem.
 */
static void
glue_sticker_init(void)
{
#ifdef ENABLE_SQLITE
226
	Error error;
227 228 229 230 231 232
	auto sticker_file = config_get_path(CONF_STICKER_FILE, error);
	if (sticker_file.IsNull()) {
		if (error.IsDefined())
			FatalError(error);
		return;
	}
233

234
	if (!sticker_global_init(std::move(sticker_file), error))
235
		FatalError(error);
236 237 238
#endif
}

239
static bool
240
glue_state_file_init(Error &error)
241
{
242
	auto path_fs = config_get_path(CONF_STATE_FILE, error);
243 244
	if (path_fs.IsNull())
		return !error.IsDefined();
245

246
	state_file = new StateFile(std::move(path_fs),
247 248
				   *instance->partition,
				   *instance->event_loop);
249
	state_file->Read();
250
	return true;
251 252
}

253 254 255 256 257
/**
 * Windows-only initialization of the Winsock2 library.
 */
static void winsock_init(void)
{
258
#ifdef WIN32
259 260
	WSADATA sockinfo;

261
	int retval = WSAStartup(MAKEWORD(2, 2), &sockinfo);
262
	if(retval != 0)
263 264
		FormatFatalError("Attempt to open Winsock2 failed; error code %d",
				 retval);
265 266

	if (LOBYTE(sockinfo.wVersion) != 2)
267 268
		FatalError("We use Winsock2 but your version is either too new "
			   "or old; please install Winsock 2.x");
269
#endif
270
}
271

Max Kellermann's avatar
Max Kellermann committed
272 273 274 275 276 277
/**
 * Initialize the decoder and player core, including the music pipe.
 */
static void
initialize_decoder_and_player(void)
{
278
	const struct config_param *param;
Max Kellermann's avatar
Max Kellermann committed
279

280
	size_t buffer_size;
Max Kellermann's avatar
Max Kellermann committed
281
	param = config_get_param(CONF_AUDIO_BUFFER_SIZE);
282
	if (param != nullptr) {
283
		char *test;
284
		long tmp = strtol(param->value.c_str(), &test, 10);
285
		if (*test != '\0' || tmp <= 0 || tmp == LONG_MAX)
286 287
			FormatFatalError("buffer size \"%s\" is not a "
					 "positive integer, line %i",
288
					 param->value.c_str(), param->line);
289
		buffer_size = tmp;
Max Kellermann's avatar
Max Kellermann committed
290 291 292 293 294
	} else
		buffer_size = DEFAULT_BUFFER_SIZE;

	buffer_size *= 1024;

295
	const unsigned buffered_chunks = buffer_size / CHUNK_SIZE;
Max Kellermann's avatar
Max Kellermann committed
296 297

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

301
	float perc;
Max Kellermann's avatar
Max Kellermann committed
302
	param = config_get_param(CONF_BUFFER_BEFORE_PLAY);
303
	if (param != nullptr) {
304
		char *test;
305
		perc = strtod(param->value.c_str(), &test);
Max Kellermann's avatar
Max Kellermann committed
306
		if (*test != '%' || perc < 0 || perc > 100) {
307 308 309
			FormatFatalError("buffered before play \"%s\" is not "
					 "a positive percentage and less "
					 "than 100 percent, line %i",
310
					 param->value.c_str(), param->line);
Max Kellermann's avatar
Max Kellermann committed
311 312 313 314
		}
	} else
		perc = DEFAULT_BUFFER_BEFORE_PLAY;

315
	unsigned buffered_before_play = (perc / 100) * buffered_chunks;
Max Kellermann's avatar
Max Kellermann committed
316 317 318
	if (buffered_before_play > buffered_chunks)
		buffered_before_play = buffered_chunks;

319 320 321 322
	const unsigned max_length =
		config_get_positive(CONF_MAX_PLAYLIST_LENGTH,
				    DEFAULT_PLAYLIST_MAX_LENGTH);

323 324 325 326
	instance->partition = new Partition(*instance,
					    max_length,
					    buffered_chunks,
					    buffered_before_play);
Max Kellermann's avatar
Max Kellermann committed
327 328
}

329
/**
330
 * Handler for GlobalEvents::IDLE.
331 332 333
 */
static void
idle_event_emitted(void)
334
{
Max Kellermann's avatar
Max Kellermann committed
335
	/* send "idle" notifications to all subscribed
336
	   clients */
337
	unsigned flags = idle_get();
338
	if (flags != 0)
339
		instance->client_list->IdleAdd(flags);
340

341 342
	if (flags & (IDLE_PLAYLIST|IDLE_PLAYER|IDLE_MIXER|IDLE_OUTPUT) &&
	    state_file != nullptr)
343
		state_file->CheckModified();
344 345
}

346 347
#ifdef WIN32

348
/**
349
 * Handler for GlobalEvents::SHUTDOWN.
350 351 352 353
 */
static void
shutdown_event_emitted(void)
{
354
	instance->event_loop->Break();
355 356
}

357 358
#endif

359
int main(int argc, char *argv[])
360 361 362 363 364 365 366 367 368
{
#ifdef WIN32
	return win32_main(argc, argv);
#else
	return mpd_main(argc, argv);
#endif
}

int mpd_main(int argc, char *argv[])
369
{
Max Kellermann's avatar
Max Kellermann committed
370
	struct options options;
371
	Error error;
Warren Dukes's avatar
Warren Dukes committed
372

373 374
	daemonize_close_stdin();

375
#ifdef HAVE_LOCALE_H
376 377 378 379
	/* initialize locale */
	setlocale(LC_CTYPE,"");
#endif

380
#ifdef HAVE_GLIB
381 382
	g_set_application_name("Music Player Daemon");

383
#if !GLIB_CHECK_VERSION(2,32,0)
Max Kellermann's avatar
Max Kellermann committed
384
	/* enable GLib's thread safety code */
385
	g_thread_init(nullptr);
386
#endif
387
#endif
Max Kellermann's avatar
Max Kellermann committed
388

389
	winsock_init();
390
	io_thread_init();
391
	config_global_init();
Warren Dukes's avatar
Warren Dukes committed
392

393
	if (!parse_cmdline(argc, argv, &options, error)) {
394
		LogError(error);
395 396
		return EXIT_FAILURE;
	}
Warren Dukes's avatar
Warren Dukes committed
397

398
	if (!glue_daemonize_init(&options, error)) {
399
		LogError(error);
400 401
		return EXIT_FAILURE;
	}
402

Max Kellermann's avatar
Max Kellermann committed
403
	stats_global_init();
404
	TagLoadConfig();
405

406
	if (!log_init(options.verbose, options.log_stderr, error)) {
407
		LogError(error);
408 409
		return EXIT_FAILURE;
	}
410

411
	instance = new Instance();
412
	instance->event_loop = new EventLoop();
413

414 415 416 417 418 419 420 421 422 423 424 425 426
#ifdef ENABLE_NEIGHBOR_PLUGINS
	instance->neighbors = new NeighborGlue();
	if (!instance->neighbors->Init(io_thread_get(), *instance, error)) {
		LogError(error);
		return EXIT_FAILURE;
	}

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

427
	const unsigned max_clients = config_get_positive(CONF_MAX_CONN, 10);
428
	instance->client_list = new ClientList(max_clients);
429

430
	if (!listen_global_init(*instance->event_loop, error)) {
431
		LogError(error);
432 433
		return EXIT_FAILURE;
	}
434

435
	daemonize_set_user();
436
	daemonize_begin(options.daemon);
Warren Dukes's avatar
Warren Dukes committed
437

438
	GlobalEvents::Initialize(*instance->event_loop);
439
	GlobalEvents::Register(GlobalEvents::IDLE, idle_event_emitted);
440
#ifdef WIN32
441
	GlobalEvents::Register(GlobalEvents::SHUTDOWN, shutdown_event_emitted);
442
#endif
443

444
	ConfigureFS();
445

446
	if (!glue_mapper_init(error)) {
447
		LogError(error);
448 449 450
		return EXIT_FAILURE;
	}

451
	initPermissions();
452
	playlist_global_init();
453
	spl_global_init();
454
#ifdef ENABLE_ARCHIVE
455
	archive_plugin_init_all();
456
#endif
457

458
	if (!pcm_convert_global_init(error)) {
459
		LogError(error);
460 461 462
		return EXIT_FAILURE;
	}

463
	decoder_plugin_init_all();
464

465
#ifdef ENABLE_DATABASE
466
	const bool create_db = InitDatabaseAndStorage();
467
#endif
468

469
	glue_sticker_init();
470

Max Kellermann's avatar
Max Kellermann committed
471
	command_init();
Max Kellermann's avatar
Max Kellermann committed
472
	initialize_decoder_and_player();
473
	volume_init();
474
	initAudioConfig();
475
	instance->partition->outputs.Configure(*instance->event_loop,
476
					       instance->partition->pc);
477
	client_manager_init();
478
	replay_gain_global_init();
479

480
	if (!input_stream_global_init(error)) {
481
		LogError(error);
482 483 484
		return EXIT_FAILURE;
	}

485
	playlist_list_global_init();
486

487
	daemonize_commit();
488

489
	setup_log_output(options.log_stderr);
Warren Dukes's avatar
Warren Dukes committed
490

491
	SignalHandlersInit(*instance->event_loop);
492

493
	io_thread_start();
494

495 496 497 498 499 500
#ifdef ENABLE_NEIGHBOR_PLUGINS
	if (instance->neighbors != nullptr &&
	    !instance->neighbors->Open(error))
		FatalError(error);
#endif

501
	ZeroconfInit(*instance->event_loop);
502

503
	player_create(instance->partition->pc);
504

505
#ifdef ENABLE_DATABASE
506
	if (create_db) {
507 508
		/* the database failed to load: recreate the
		   database */
509
		unsigned job = instance->update->Enqueue("", true);
510
		if (job == 0)
511
			FatalError("directory update failed");
512
	}
513
#endif
514

515
	if (!glue_state_file_init(error)) {
516
		LogError(error);
517 518
		return EXIT_FAILURE;
	}
519

520
	instance->partition->outputs.SetReplayGainMode(replay_gain_get_real_mode(instance->partition->playlist.queue.random));
521

522
	if (config_get_bool(CONF_AUTO_UPDATE, false)) {
523
#ifdef ENABLE_INOTIFY
524
		if (instance->storage != nullptr &&
525
		    instance->update != nullptr)
526 527 528
			mpd_inotify_init(*instance->event_loop,
					 *instance->storage,
					 *instance->update,
529
					 config_get_unsigned(CONF_AUTO_UPDATE_DEPTH,
530
							     G_MAXUINT));
531
#else
532 533
		FormatWarning(main_domain,
			      "inotify: auto_update was disabled. enable during compilation phase");
534
#endif
535
	}
536

537 538
	config_global_check();

539 540
	/* enable all audio outputs (if not already done by
	   playlist_state_restore() */
541
	instance->partition->pc.UpdateAudio();
542

543 544 545
#ifdef WIN32
	win32_app_started();
#endif
546

547 548 549 550
	/* 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);

551
	/* run the main loop */
552
	instance->event_loop->Run();
553

554 555 556 557
#ifdef WIN32
	win32_app_stopping();
#endif

558 559
	/* cleanup */

560
#ifdef ENABLE_INOTIFY
561
	mpd_inotify_finish();
562
#endif
563

564 565 566 567 568
	if (state_file != nullptr) {
		state_file->Write();
		delete state_file;
	}

569
	instance->partition->pc.Kill();
570
	ZeroconfDeinit();
Max Kellermann's avatar
Max Kellermann committed
571
	listen_global_finish();
572
	delete instance->client_list;
573

574 575 576 577 578 579 580
#ifdef ENABLE_NEIGHBOR_PLUGINS
	if (instance->neighbors != nullptr) {
		instance->neighbors->Close();
		delete instance->neighbors;
	}
#endif

581
#ifdef ENABLE_DATABASE
582
	delete instance->update;
583 584 585 586 587

	if (instance->database != nullptr) {
		instance->database->Close();
		delete instance->database;
	}
588
#endif
589

590 591 592 593
#ifdef ENABLE_SQLITE
	sticker_global_finish();
#endif

594
	GlobalEvents::Deinitialize();
595

596
	playlist_list_global_finish();
597
	input_stream_global_finish();
598 599

#ifdef ENABLE_DATABASE
600
	mapper_finish();
601 602
#endif

603
	delete instance->partition;
Max Kellermann's avatar
Max Kellermann committed
604
	command_finish();
605
	decoder_plugin_deinit_all();
606
#ifdef ENABLE_ARCHIVE
607
	archive_plugin_deinit_all();
608
#endif
609
	config_global_finish();
610
	io_thread_deinit();
611
	SignalHandlersFinish();
612
	delete instance->event_loop;
613
	delete instance;
614
	daemonize_finish();
615 616 617
#ifdef WIN32
	WSACleanup();
#endif
618

619
	log_deinit();
620
	return EXIT_SUCCESS;
Warren Dukes's avatar
Warren Dukes committed
621
}