PlayerThread.cxx 24.4 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 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 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 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 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 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 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 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 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 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 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 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 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 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203
/*
 * Copyright (C) 2003-2013 The Music Player Daemon Project
 * http://www.musicpd.org
 *
 * 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.
 *
 * 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.
 */

#include "config.h"
#include "PlayerThread.hxx"
#include "DecoderThread.hxx"
#include "DecoderControl.hxx"
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
#include "Song.hxx"
#include "Main.hxx"
#include "system/FatalError.hxx"
#include "CrossFade.hxx"
#include "PlayerControl.hxx"
#include "OutputAll.hxx"
#include "tag/Tag.hxx"
#include "Idle.hxx"
#include "GlobalEvents.hxx"
#include "util/Domain.hxx"
#include "Log.hxx"

#include <cmath>

#include <glib.h>

#include <string.h>

static constexpr Domain player_domain("player");

enum class CrossFadeState : int8_t {
	DISABLED = -1,
	UNKNOWN = 0,
	ENABLED = 1
};

class Player {
	player_control &pc;

	decoder_control &dc;

	MusicBuffer &buffer;

	MusicPipe *pipe;

	/**
	 * are we waiting for buffered_before_play?
	 */
	bool buffering;

	/**
	 * true if the decoder is starting and did not provide data
	 * yet
	 */
	bool decoder_starting;

	/**
	 * is the player paused?
	 */
	bool paused;

	/**
	 * is there a new song in pc.next_song?
	 */
	bool queued;

	/**
	 * Was any audio output opened successfully?  It might have
	 * failed meanwhile, but was not explicitly closed by the
	 * player thread.  When this flag is unset, some output
	 * methods must not be called.
	 */
	bool output_open;

	/**
	 * the song currently being played
	 */
	Song *song;

	/**
	 * is cross fading enabled?
	 */
	CrossFadeState xfade_state;

	/**
	 * has cross-fading begun?
	 */
	bool cross_fading;

	/**
	 * The number of chunks used for crossfading.
	 */
	unsigned cross_fade_chunks;

	/**
	 * The tag of the "next" song during cross-fade.  It is
	 * postponed, and sent to the output thread when the new song
	 * really begins.
	 */
	Tag *cross_fade_tag;

	/**
	 * The current audio format for the audio outputs.
	 */
	AudioFormat play_audio_format;

	/**
	 * The time stamp of the chunk most recently sent to the
	 * output thread.  This attribute is only used if
	 * audio_output_all_get_elapsed_time() didn't return a usable
	 * value; the output thread can estimate the elapsed time more
	 * precisely.
	 */
	float elapsed_time;

public:
	Player(player_control &_pc, decoder_control &_dc,
	       MusicBuffer &_buffer)
		:pc(_pc), dc(_dc), buffer(_buffer),
		 buffering(false),
		 decoder_starting(false),
		 paused(false),
		 queued(true),
		 output_open(false),
		 song(nullptr),
		 xfade_state(CrossFadeState::UNKNOWN),
		 cross_fading(false),
		 cross_fade_chunks(0),
		 cross_fade_tag(nullptr),
		 elapsed_time(0.0) {}

private:
	void ClearAndDeletePipe() {
		pipe->Clear(buffer);
		delete pipe;
	}

	void ClearAndReplacePipe(MusicPipe *_pipe) {
		ClearAndDeletePipe();
		pipe = _pipe;
	}

	void ReplacePipe(MusicPipe *_pipe) {
		delete pipe;
		pipe = _pipe;
	}

	/**
	 * Start the decoder.
	 *
	 * Player lock is not held.
	 */
	void StartDecoder(MusicPipe &pipe);

	/**
	 * The decoder has acknowledged the "START" command (see
	 * player::WaitForDecoder()).  This function checks if the decoder
	 * initialization has completed yet.
	 *
	 * The player lock is not held.
	 */
	bool CheckDecoderStartup();

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
	 * Player lock is not held.
	 */
	void StopDecoder();

	/**
	 * Is the decoder still busy on the same song as the player?
	 *
	 * Note: this function does not check if the decoder is already
	 * finished.
	 */
	gcc_pure
	bool IsDecoderAtCurrentSong() const {
		assert(pipe != nullptr);

		return dc.pipe == pipe;
	}

	/**
	 * Returns true if the decoder is decoding the next song (or has begun
	 * decoding it, or has finished doing it), and the player hasn't
	 * switched to that song yet.
	 */
	gcc_pure
	bool IsDecoderAtNextSong() const {
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

	/**
	 * This is the handler for the #PlayerCommand::SEEK command.
	 *
	 * The player lock is not held.
	 */
	bool SeekDecoder();

	/**
	 * After the decoder has been started asynchronously, wait for
	 * the "START" command to finish.  The decoder may not be
	 * initialized yet, i.e. there is no audio_format information
	 * yet.
	 *
	 * The player lock is not held.
	 */
	bool WaitForDecoder();

	/**
	 * Wrapper for audio_output_all_open().  Upon failure, it pauses the
	 * player.
	 *
	 * @return true on success
	 */
	bool OpenOutput();

	/**
	 * Obtains the next chunk from the music pipe, optionally applies
	 * cross-fading, and sends it to all audio outputs.
	 *
	 * @return true on success, false on error (playback will be stopped)
	 */
	bool PlayNextChunk();

	/**
	 * Sends a chunk of silence to the audio outputs.  This is
	 * called when there is not enough decoded data in the pipe
	 * yet, to prevent underruns in the hardware buffers.
	 *
	 * The player lock is not held.
	 */
	bool SendSilence();

	/**
	 * Player lock must be held before calling.
	 */
	void ProcessCommand();

	/**
	 * This is called at the border between two songs: the audio output
	 * has consumed all chunks of the current song, and we should start
	 * sending chunks from the next one.
	 *
	 * The player lock is not held.
	 *
	 * @return true on success, false on error (playback will be stopped)
	 */
	bool SongBorder();

public:
	/*
	 * The main loop of the player thread, during playback.  This
	 * is basically a state machine, which multiplexes data
	 * between the decoder thread and the output threads.
	 */
	void Run();
};

static void
player_command_finished(player_control &pc)
{
	pc.Lock();
	pc.CommandFinished();
	pc.Unlock();
}

void
Player::StartDecoder(MusicPipe &_pipe)
{
	assert(queued || pc.command == PlayerCommand::SEEK);
	assert(pc.next_song != nullptr);

	unsigned start_ms = pc.next_song->start_ms;
	if (pc.command == PlayerCommand::SEEK)
		start_ms += (unsigned)(pc.seek_where * 1000);

	dc.Start(pc.next_song->DupDetached(),
		 start_ms, pc.next_song->end_ms,
		 buffer, _pipe);
}

void
Player::StopDecoder()
{
	dc.Stop();

	if (dc.pipe != nullptr) {
		/* clear and free the decoder pipe */

		dc.pipe->Clear(buffer);

		if (dc.pipe != pipe)
			delete dc.pipe;

		dc.pipe = nullptr;
	}
}

bool
Player::WaitForDecoder()
{
	assert(queued || pc.command == PlayerCommand::SEEK);
	assert(pc.next_song != nullptr);

	queued = false;

	Error error = dc.LockGetError();
	if (error.IsDefined()) {
		pc.Lock();
		pc.SetError(PlayerError::DECODER, std::move(error));

		pc.next_song->Free();
		pc.next_song = nullptr;

		pc.Unlock();

		return false;
	}

	if (song != nullptr)
		song->Free();

	song = pc.next_song;
	elapsed_time = 0.0;

	/* set the "starting" flag, which will be cleared by
	   player_check_decoder_startup() */
	decoder_starting = true;

	pc.Lock();

	/* update player_control's song information */
	pc.total_time = pc.next_song->GetDuration();
	pc.bit_rate = 0;
	pc.audio_format.Clear();

	/* clear the queued song */
	pc.next_song = nullptr;

	pc.Unlock();

	/* call syncPlaylistWithQueue() in the main thread */
	GlobalEvents::Emit(GlobalEvents::PLAYLIST);

	return true;
}

/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
static double
real_song_duration(const Song *song, double decoder_duration)
{
	assert(song != nullptr);

	if (decoder_duration <= 0.0)
		/* the decoder plugin didn't provide information; fall
		   back to Song::GetDuration() */
		return song->GetDuration();

	if (song->end_ms > 0 && song->end_ms / 1000.0 < decoder_duration)
		return (song->end_ms - song->start_ms) / 1000.0;

	return decoder_duration - song->start_ms / 1000.0;
}

bool
Player::OpenOutput()
{
	assert(play_audio_format.IsDefined());
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);

	Error error;
	if (audio_output_all_open(play_audio_format, buffer, error)) {
		output_open = true;
		paused = false;

		pc.Lock();
		pc.state = PlayerState::PLAY;
		pc.Unlock();

		idle_add(IDLE_PLAYER);

		return true;
	} else {
		LogError(error);

		output_open = false;

		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		paused = true;

		pc.Lock();
		pc.SetError(PlayerError::OUTPUT, std::move(error));
		pc.state = PlayerState::PAUSE;
		pc.Unlock();

		idle_add(IDLE_PLAYER);

		return false;
	}
}

bool
Player::CheckDecoderStartup()
{
	assert(decoder_starting);

	dc.Lock();

	Error error = dc.GetError();
	if (error.IsDefined()) {
		/* the decoder failed */
		dc.Unlock();

		pc.Lock();
		pc.SetError(PlayerError::DECODER, std::move(error));
		pc.Unlock();

		return false;
	} else if (!dc.IsStarting()) {
		/* the decoder is ready and ok */

		dc.Unlock();

		if (output_open &&
		    !audio_output_all_wait(&pc, 1))
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

		pc.Lock();
		pc.total_time = real_song_duration(dc.song, dc.total_time);
		pc.audio_format = dc.in_audio_format;
		pc.Unlock();

		idle_add(IDLE_PLAYER);

		play_audio_format = dc.out_audio_format;
		decoder_starting = false;

		if (!paused && !OpenOutput()) {
			char *uri = dc.song->GetURI();
			FormatError(player_domain,
				    "problems opening audio device "
				    "while playing \"%s\"", uri);
			g_free(uri);

			return true;
		}

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
		dc.WaitForDecoder();
		dc.Unlock();

		return true;
	}
}

bool
Player::SendSilence()
{
	assert(output_open);
	assert(play_audio_format.IsDefined());

	struct music_chunk *chunk = buffer.Allocate();
	if (chunk == nullptr) {
		LogError(player_domain, "Failed to allocate silence buffer");
		return false;
	}

#ifndef NDEBUG
	chunk->audio_format = play_audio_format;
#endif

	const size_t frame_size = play_audio_format.GetFrameSize();
	/* this formula ensures that we don't send
	   partial frames */
	unsigned num_frames = sizeof(chunk->data) / frame_size;

	chunk->times = -1.0; /* undefined time stamp */
	chunk->length = num_frames * frame_size;
	memset(chunk->data, 0, chunk->length);

	Error error;
	if (!audio_output_all_play(chunk, error)) {
		LogError(error);
		buffer.Return(chunk);
		return false;
	}

	return true;
}

inline bool
Player::SeekDecoder()
{
	assert(pc.next_song != nullptr);

	const unsigned start_ms = pc.next_song->start_ms;

	if (!dc.LockIsCurrentSong(pc.next_song)) {
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

		StopDecoder();

		/* clear music chunks which might still reside in the
		   pipe */
		pipe->Clear(buffer);

		/* re-start the decoder */
		StartDecoder(*pipe);
		if (!WaitForDecoder()) {
			/* decoder failure */
			player_command_finished(pc);
			return false;
		}
	} else {
		if (!IsDecoderAtCurrentSong()) {
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
			ClearAndReplacePipe(dc.pipe);
		}

		pc.next_song->Free();
		pc.next_song = nullptr;
		queued = false;
	}

	/* wait for the decoder to complete initialization */

	while (decoder_starting) {
		if (!CheckDecoderStartup()) {
			/* decoder failure */
			player_command_finished(pc);
			return false;
		}
	}

	/* send the SEEK command */

	double where = pc.seek_where;
	if (where > pc.total_time)
		where = pc.total_time - 0.1;
	if (where < 0.0)
		where = 0.0;

	if (!dc.Seek(where + start_ms / 1000.0)) {
		/* decoder failure */
		player_command_finished(pc);
		return false;
	}

	elapsed_time = where;

	player_command_finished(pc);

	xfade_state = CrossFadeState::UNKNOWN;

	/* re-fill the buffer after seeking */
	buffering = true;

	audio_output_all_cancel();

	return true;
}

inline void
Player::ProcessCommand()
{
	switch (pc.command) {
	case PlayerCommand::NONE:
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
		break;

	case PlayerCommand::UPDATE_AUDIO:
		pc.Unlock();
		audio_output_all_enable_disable();
		pc.Lock();
		pc.CommandFinished();
		break;

	case PlayerCommand::QUEUE:
		assert(pc.next_song != nullptr);
		assert(!queued);
		assert(!IsDecoderAtNextSong());

		queued = true;
		pc.CommandFinished();
		break;

	case PlayerCommand::PAUSE:
		pc.Unlock();

		paused = !paused;
		if (paused) {
			audio_output_all_pause();
			pc.Lock();

			pc.state = PlayerState::PAUSE;
		} else if (!play_audio_format.IsDefined()) {
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
			pc.Lock();

			pc.state = PlayerState::PLAY;
		} else {
			OpenOutput();

			pc.Lock();
		}

		pc.CommandFinished();
		break;

	case PlayerCommand::SEEK:
		pc.Unlock();
		SeekDecoder();
		pc.Lock();
		break;

	case PlayerCommand::CANCEL:
		if (pc.next_song == nullptr) {
			/* the cancel request arrived too late, we're
			   already playing the queued song...  stop
			   everything now */
			pc.command = PlayerCommand::STOP;
			return;
		}

		if (IsDecoderAtNextSong()) {
			/* the decoder is already decoding the song -
			   stop it and reset the position */
			pc.Unlock();
			StopDecoder();
			pc.Lock();
		}

		pc.next_song->Free();
		pc.next_song = nullptr;
		queued = false;
		pc.CommandFinished();
		break;

	case PlayerCommand::REFRESH:
		if (output_open && !paused) {
			pc.Unlock();
			audio_output_all_check();
			pc.Lock();
		}

		pc.elapsed_time = audio_output_all_get_elapsed_time();
		if (pc.elapsed_time < 0.0)
			pc.elapsed_time = elapsed_time;

		pc.CommandFinished();
		break;
	}
}

static void
update_song_tag(Song *song, const Tag &new_tag)
{
	if (song->IsFile())
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

	Tag *old_tag = song->tag;
	song->tag = new Tag(new_tag);

	delete old_tag;

	/* the main thread will update the playlist version when he
	   receives this event */
	GlobalEvents::Emit(GlobalEvents::TAG);

	/* notify all clients that the tag of the current song has
	   changed */
	idle_add(IDLE_PLAYER);
}

/**
 * Plays a #music_chunk object (after applying software volume).  If
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
 *
 * Player lock is not held.
 */
static bool
play_chunk(player_control &pc,
	   Song *song, struct music_chunk *chunk,
	   MusicBuffer &buffer,
	   const AudioFormat format,
	   Error &error)
{
	assert(chunk->CheckFormat(format));

	if (chunk->tag != nullptr)
		update_song_tag(song, *chunk->tag);

	if (chunk->length == 0) {
		buffer.Return(chunk);
		return true;
	}

	pc.Lock();
	pc.bit_rate = chunk->bit_rate;
	pc.Unlock();

	/* send the chunk to the audio outputs */

	if (!audio_output_all_play(chunk, error))
		return false;

	pc.total_play_time += (double)chunk->length /
		format.GetTimeToSize();
	return true;
}

inline bool
Player::PlayNextChunk()
{
	if (!audio_output_all_wait(&pc, 64))
		/* the output pipe is still large enough, don't send
		   another chunk */
		return true;

	unsigned cross_fade_position;
	struct music_chunk *chunk = nullptr;
	if (xfade_state == CrossFadeState::ENABLED && IsDecoderAtNextSong() &&
	    (cross_fade_position = pipe->GetSize()) <= cross_fade_chunks) {
		/* perform cross fade */
		music_chunk *other_chunk = dc.pipe->Shift();

		if (!cross_fading) {
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
			cross_fade_chunks = cross_fade_position;
			cross_fading = true;
		}

		if (other_chunk != nullptr) {
			chunk = pipe->Shift();
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);

			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
			cross_fade_tag =
				Tag::MergeReplace(cross_fade_tag,
						  other_chunk->tag);
			other_chunk->tag = nullptr;

			if (std::isnan(pc.mixramp_delay_seconds)) {
				chunk->mix_ratio = ((float)cross_fade_position)
					     / cross_fade_chunks;
			} else {
				chunk->mix_ratio = nan("");
			}

			if (other_chunk->IsEmpty()) {
				/* the "other" chunk was a music_chunk
				   which had only a tag, but no music
				   data - we cannot cross-fade that;
				   but since this happens only at the
				   beginning of the new song, we can
				   easily recover by throwing it away
				   now */
				buffer.Return(other_chunk);
				other_chunk = nullptr;
			}

			chunk->other = other_chunk;
		} else {
			/* there are not enough decoded chunks yet */

			dc.Lock();

			if (dc.IsIdle()) {
				/* the decoder isn't running, abort
				   cross fading */
				dc.Unlock();

				xfade_state = CrossFadeState::DISABLED;
			} else {
				/* wait for the decoder */
				dc.Signal();
				dc.WaitForDecoder();
				dc.Unlock();

				return true;
			}
		}
	}

	if (chunk == nullptr)
		chunk = pipe->Shift();

	assert(chunk != nullptr);

	/* insert the postponed tag if cross-fading is finished */

	if (xfade_state != CrossFadeState::ENABLED && cross_fade_tag != nullptr) {
		chunk->tag = Tag::MergeReplace(chunk->tag, cross_fade_tag);
		cross_fade_tag = nullptr;
	}

	/* play the current chunk */

	Error error;
	if (!play_chunk(pc, song, chunk, buffer, play_audio_format, error)) {
		LogError(error);

		buffer.Return(chunk);

		pc.Lock();

		pc.SetError(PlayerError::OUTPUT, std::move(error));

		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		pc.state = PlayerState::PAUSE;
		paused = true;

		pc.Unlock();

		idle_add(IDLE_PLAYER);

		return false;
	}

	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
	   larger block at a time */
	dc.Lock();
	if (!dc.IsIdle() &&
	    dc.pipe->GetSize() <= (pc.buffered_before_play +
				   buffer.GetSize() * 3) / 4)
		dc.Signal();
	dc.Unlock();

	return true;
}

inline bool
Player::SongBorder()
{
	xfade_state = CrossFadeState::UNKNOWN;

	char *uri = song->GetURI();
	FormatInfo(player_domain, "played \"%s\"", uri);
	g_free(uri);

	ReplacePipe(dc.pipe);

	audio_output_all_song_border();

	if (!WaitForDecoder())
		return false;

	pc.Lock();

	const bool border_pause = pc.border_pause;
	if (border_pause) {
		paused = true;
		pc.state = PlayerState::PAUSE;
	}

	pc.Unlock();

	if (border_pause)
		idle_add(IDLE_PLAYER);

	return true;
}

inline void
Player::Run()
{
	pipe = new MusicPipe();

	StartDecoder(*pipe);
	if (!WaitForDecoder()) {
		assert(song == nullptr);

		StopDecoder();
		player_command_finished(pc);
		delete pipe;
		return;
	}

	pc.Lock();
	pc.state = PlayerState::PLAY;

	if (pc.command == PlayerCommand::SEEK)
		elapsed_time = pc.seek_where;

	pc.CommandFinished();

	while (true) {
		ProcessCommand();
		if (pc.command == PlayerCommand::STOP ||
		    pc.command == PlayerCommand::EXIT ||
		    pc.command == PlayerCommand::CLOSE_AUDIO) {
			pc.Unlock();
			audio_output_all_cancel();
			break;
		}

		pc.Unlock();

		if (buffering) {
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

			if (pipe->GetSize() < pc.buffered_before_play &&
			    !dc.LockIsIdle()) {
				/* not enough decoded buffer space yet */

				if (!paused && output_open &&
				    audio_output_all_check() < 4 &&
				    !SendSilence())
					break;

				dc.Lock();
				/* XXX race condition: check decoder again */
				dc.WaitForDecoder();
				dc.Unlock();
				pc.Lock();
				continue;
			} else {
				/* buffering is complete */
				buffering = false;
			}
		}

		if (decoder_starting) {
			/* wait until the decoder is initialized completely */

			if (!CheckDecoderStartup())
				break;

			pc.Lock();
			continue;
		}

#ifndef NDEBUG
		/*
		music_pipe_check_format(&play_audio_format,
					next_song_chunk,
					&dc.out_audio_format);
		*/
#endif

		if (dc.LockIsIdle() && queued && dc.pipe == pipe) {
			/* the decoder has finished the current song;
			   make it decode the next song */

			assert(dc.pipe == nullptr || dc.pipe == pipe);

			StartDecoder(*new MusicPipe());
		}

		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
		    !pc.border_pause &&
		    IsDecoderAtNextSong() &&
		    xfade_state == CrossFadeState::UNKNOWN &&
		    !dc.LockIsStarting()) {
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
			cross_fade_chunks =
				cross_fade_calc(pc.cross_fade_seconds, dc.total_time,
						pc.mixramp_db,
						pc.mixramp_delay_seconds,
						dc.replay_gain_db,
						dc.replay_gain_prev_db,
						dc.mixramp_start,
						dc.mixramp_prev_end,
						dc.out_audio_format,
						play_audio_format,
						buffer.GetSize() -
						pc.buffered_before_play);
			if (cross_fade_chunks > 0) {
				xfade_state = CrossFadeState::ENABLED;
				cross_fading = false;
			} else
				/* cross fading is disabled or the
				   next song is too short */
				xfade_state = CrossFadeState::DISABLED;
		}

		if (paused) {
			pc.Lock();

			if (pc.command == PlayerCommand::NONE)
				pc.Wait();
			continue;
		} else if (!pipe->IsEmpty()) {
			/* at least one music chunk is ready - send it
			   to the audio output */

			PlayNextChunk();
		} else if (audio_output_all_check() > 0) {
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

			/* XXX synchronize in a better way */
			g_usleep(10000);
		} else if (IsDecoderAtNextSong()) {
			/* at the beginning of a new song */

			if (!SongBorder())
				break;
		} else if (dc.LockIsIdle()) {
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
			if (pipe->IsEmpty()) {
				/* wait for the hardware to finish
				   playback */
				audio_output_all_drain();
				break;
			}
		} else if (output_open) {
			/* the decoder is too busy and hasn't provided
			   new PCM data in time: send silence (if the
			   output pipe is empty) */
			if (!SendSilence())
				break;
		}

		pc.Lock();
	}

	StopDecoder();

	ClearAndDeletePipe();

	delete cross_fade_tag;

	if (song != nullptr)
		song->Free();

	pc.Lock();

	if (queued) {
		assert(pc.next_song != nullptr);
		pc.next_song->Free();
		pc.next_song = nullptr;
	}

	pc.state = PlayerState::STOP;

	pc.Unlock();
}

static void
do_play(player_control &pc, decoder_control &dc,
	MusicBuffer &buffer)
{
	Player player(pc, dc, buffer);
	player.Run();
}

static gpointer
player_task(gpointer arg)
{
	player_control &pc = *(player_control *)arg;

	decoder_control dc;
	decoder_thread_start(&dc);

	MusicBuffer buffer(pc.buffer_chunks);

	pc.Lock();

	while (1) {
		switch (pc.command) {
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
			assert(pc.next_song != nullptr);

			pc.Unlock();
			do_play(pc, dc, buffer);
			GlobalEvents::Emit(GlobalEvents::PLAYLIST);
			pc.Lock();
			break;

		case PlayerCommand::STOP:
			pc.Unlock();
			audio_output_all_cancel();
			pc.Lock();

			/* fall through */

		case PlayerCommand::PAUSE:
			if (pc.next_song != nullptr) {
				pc.next_song->Free();
				pc.next_song = nullptr;
			}

			pc.CommandFinished();
			break;

		case PlayerCommand::CLOSE_AUDIO:
			pc.Unlock();

			audio_output_all_release();

			pc.Lock();
			pc.CommandFinished();

			assert(buffer.IsEmptyUnsafe());

			break;

		case PlayerCommand::UPDATE_AUDIO:
			pc.Unlock();
			audio_output_all_enable_disable();
			pc.Lock();
			pc.CommandFinished();
			break;

		case PlayerCommand::EXIT:
			pc.Unlock();

			dc.Quit();

			audio_output_all_close();

			player_command_finished(pc);
			return nullptr;

		case PlayerCommand::CANCEL:
			if (pc.next_song != nullptr) {
				pc.next_song->Free();
				pc.next_song = nullptr;
			}

			pc.CommandFinished();
			break;

		case PlayerCommand::REFRESH:
			/* no-op when not playing */
			pc.CommandFinished();
			break;

		case PlayerCommand::NONE:
			pc.Wait();
			break;
		}
	}
}

void
player_create(player_control &pc)
{
	assert(pc.thread == nullptr);

#if GLIB_CHECK_VERSION(2,32,0)
	pc.thread = g_thread_new("player", player_task, &pc);
#else
	GError *e = nullptr;
	pc.thread = g_thread_create(player_task, &pc, true, &e);
	if (pc.thread == nullptr)
		FatalError("Failed to spawn player task", e);
#endif
}