Thread.cxx 26.8 KB
Newer Older
1
/*
2
 * Copyright 2003-2018 The Music Player Daemon Project
3
 * http://www.musicpd.org
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.
18 19
 */

20 21 22 23 24 25
/* \file
 *
 * The player thread controls the playback.  It acts as a bridge
 * between the decoder thread and the output thread(s): it receives
 * #MusicChunk objects from the decoder, optionally mixes them
 * (cross-fading), applies software volume, and sends them to the
26 27
 * audio outputs via PlayerOutputs::Play()
 * (i.e. MultipleOutputs::Play()).
28 29 30 31 32 33 34 35 36 37 38
 *
 * It is controlled by the main thread (the playlist code), see
 * Control.hxx.  The playlist enqueues new songs into the player
 * thread and sends it commands.
 *
 * The player thread itself does not do any I/O.  It synchronizes with
 * other threads via #GMutex and #GCond objects, and passes
 * #MusicChunk instances around in #MusicPipe objects.
 */

#include "Control.hxx"
39
#include "Outputs.hxx"
40
#include "Listener.hxx"
41
#include "decoder/Control.hxx"
42 43 44
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
45
#include "song/DetachedSong.hxx"
46
#include "CrossFade.hxx"
47
#include "tag/Tag.hxx"
Max Kellermann's avatar
Max Kellermann committed
48
#include "Idle.hxx"
49
#include "util/Domain.hxx"
50
#include "thread/Name.hxx"
51
#include "Log.hxx"
52

53
#include <exception>
54
#include <memory>
55

Max Kellermann's avatar
Max Kellermann committed
56 57
#include <string.h>

58
static constexpr Domain player_domain("player");
59

60 61 62 63 64 65
/**
 * Start playback as soon as enough data for this duration has been
 * pushed to the decoder pipe.
 */
static constexpr auto buffer_before_play_duration = std::chrono::seconds(1);

66
class Player {
67
	PlayerControl &pc;
68

69
	DecoderControl &dc;
70

71 72
	MusicBuffer &buffer;

73
	std::shared_ptr<MusicPipe> pipe;
74

75 76 77 78 79 80 81 82 83 84 85 86
	/**
	 * the song currently being played
	 */
	std::unique_ptr<DetachedSong> song;

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

87 88
	/**
	 * Start playback as soon as this number of chunks has been
89 90
	 * pushed to the decoder pipe.  This is calculated based on
	 * #buffer_before_play_duration.
91
	 */
92
	unsigned buffer_before_play;
93

94 95 96 97 98 99 100 101 102 103
	/**
	 * If the decoder pipe gets consumed below this threshold,
	 * it's time to wake up the decoder.
	 *
	 * It is calculated in a way which should prevent a wakeup
	 * after each single consumed chunk; it is more efficient to
	 * make the decoder decode a larger block at a time.
	 */
	const unsigned decoder_wakeup_threshold;

104
	/**
105
	 * Are we waiting for #buffer_before_play?
106
	 */
107
	bool buffering = true;
108 109 110 111 112

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

115 116 117 118
	/**
	 * Did we wake up the DecoderThread recently?  This avoids
	 * duplicate wakeup calls.
	 */
119
	bool decoder_woken = false;
120

121 122 123
	/**
	 * is the player paused?
	 */
124
	bool paused = false;
125

126 127 128
	/**
	 * is there a new song in pc.next_song?
	 */
129
	bool queued = true;
130

131 132 133 134 135 136
	/**
	 * 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.
	 */
137
	bool output_open = false;
138

139
	/**
140
	 * Is cross-fading to the next song enabled?
141
	 */
142
	enum class CrossFadeState : uint8_t {
143 144 145 146
		/**
		 * The initial state: we don't know yet if we will
		 * cross-fade; it will be determined soon.
		 */
147
		UNKNOWN,
148 149 150 151 152

		/**
		 * Cross-fading is disabled for the transition to the
		 * next song.
		 */
153
		DISABLED,
154 155 156 157 158 159

		/**
		 * Cross-fading is enabled (but may not yet be in
		 * progress), will start near the end of the current
		 * song.
		 */
160
		ENABLED,
161

162 163 164 165
		/**
		 * Currently cross-fading to the next song.
		 */
		ACTIVE,
166
	} xfade_state = CrossFadeState::UNKNOWN;
167 168 169 170

	/**
	 * The number of chunks used for crossfading.
	 */
171
	unsigned cross_fade_chunks = 0;
172

173 174 175
	/**
	 * The current audio format for the audio outputs.
	 */
176
	AudioFormat play_audio_format = AudioFormat::Undefined();
177 178 179 180

	/**
	 * The time stamp of the chunk most recently sent to the
	 * output thread.  This attribute is only used if
181
	 * MultipleOutputs::GetElapsedTime() didn't return a usable
182
	 * value; the output thread can estimate the elapsed time more
183
	 * precisely.
184
	 */
185
	SongTime elapsed_time = SongTime::zero();
186

187 188 189 190 191 192 193 194 195 196
	/**
	 * If this is positive, then we need to ask the decoder to
	 * seek after it has completed startup.  This is needed if the
	 * decoder is in the middle of startup while the player
	 * receives another seek command.
	 *
	 * This is only valid while #decoder_starting is true.
	 */
	SongTime pending_seek;

197
public:
198
	Player(PlayerControl &_pc, DecoderControl &_dc,
199
	       MusicBuffer &_buffer) noexcept
200
		:pc(_pc), dc(_dc), buffer(_buffer),
201
		 decoder_wakeup_threshold(buffer.GetSize() * 3 / 4)
202 203
	{
	}
204

205
private:
206 207 208 209
	/**
	 * Reset cross-fading to the initial state.  A check to
	 * re-enable it at an appropriate time will be scheduled.
	 */
210
	void ResetCrossFade() noexcept {
211 212 213
		xfade_state = CrossFadeState::UNKNOWN;
	}

214 215
	template<typename P>
	void ReplacePipe(P &&_pipe) noexcept {
216
		ResetCrossFade();
217
		pipe = std::forward<P>(_pipe);
218 219 220 221 222
	}

	/**
	 * Start the decoder.
	 *
223
	 * Caller must lock the mutex.
224
	 */
225
	void StartDecoder(std::shared_ptr<MusicPipe> pipe) noexcept;
226 227 228

	/**
	 * The decoder has acknowledged the "START" command (see
229
	 * ActivateDecoder()).  This function checks if the decoder
230 231
	 * initialization has completed yet.  If not, it will wait
	 * some more.
232
	 *
233
	 * Caller must lock the mutex.
234 235 236
	 *
	 * @return false if the decoder has failed, true on success
	 * (though the decoder startup may or may not yet be finished)
237
	 */
238
	bool CheckDecoderStartup() noexcept;
239 240 241 242

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
243
	 * Caller must lock the mutex.
244
	 */
245
	void StopDecoder() noexcept;
246 247 248 249 250 251 252 253

	/**
	 * 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
254
	bool IsDecoderAtCurrentSong() const noexcept {
255 256 257 258 259 260 261 262 263 264 265
		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
266
	bool IsDecoderAtNextSong() const noexcept {
267 268 269
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

270 271 272 273 274 275 276 277 278 279
	/**
	 * Invoke DecoderControl::Seek() and update our state or
	 * handle errors.
	 *
	 * Caller must lock the mutex.
	 *
	 * @return false if the decoder has failed
	 */
	bool SeekDecoder(SongTime seek_time) noexcept;

280
	/**
281
	 * This is the handler for the #PlayerCommand::SEEK command.
282
	 *
283
	 * Caller must lock the mutex.
284 285
	 *
	 * @return false if the decoder has failed
286
	 */
287
	bool SeekDecoder() noexcept;
288

289 290
	void CancelPendingSeek() noexcept {
		pending_seek = SongTime::zero();
291
		pc.CancelPendingSeek();
292 293
	}

294 295 296 297 298 299
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
300
	bool ForwardDecoderError() noexcept;
301

302
	/**
303 304 305 306 307 308 309 310 311
	 * After the decoder has been started asynchronously, activate
	 * it for playback.  That is, make the currently decoded song
	 * active (assign it to #song), clear PlayerControl::next_song
	 * and #queued, initialize #elapsed_time, and set
	 * #decoder_starting.
	 *
	 * When returning, the decoder may not have completed startup
	 * yet, therefore we don't know the audio format yet.  To
	 * finish decoder startup, call CheckDecoderStartup().
312
	 *
313
	 * Caller must lock the mutex.
314
	 */
315
	void ActivateDecoder() noexcept;
316 317

	/**
318 319
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
320
	 *
321 322
	 * Caller must lock the mutex.
	 *
323 324
	 * @return true on success
	 */
325
	bool OpenOutput() noexcept;
326 327 328 329 330 331 332

	/**
	 * 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)
	 */
333
	bool PlayNextChunk() noexcept;
334

335 336
	unsigned UnlockCheckOutputs() noexcept {
		const ScopeUnlock unlock(pc.mutex);
337
		return pc.outputs.CheckPipe();
338 339
	}

340 341
	/**
	 * Player lock must be held before calling.
342 343
	 *
	 * @return false to stop playback
344
	 */
345
	bool ProcessCommand() noexcept;
346 347 348 349 350 351

	/**
	 * 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.
	 *
352
	 * Caller must lock the mutex.
353
	 */
354
	void SongBorder() noexcept;
355

356
public:
357 358 359 360 361
	/*
	 * 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.
	 */
362
	void Run() noexcept;
363 364
};

365
void
366
Player::StartDecoder(std::shared_ptr<MusicPipe> _pipe) noexcept
367
{
368
	assert(queued || pc.command == PlayerCommand::SEEK);
369
	assert(pc.next_song != nullptr);
370

371 372
	/* copy ReplayGain parameters to the decoder */
	dc.replay_gain_mode = pc.replay_gain_mode;
373

374
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
375

376
	dc.Start(std::make_unique<DetachedSong>(*pc.next_song),
377
		 start_time, pc.next_song->GetEndTime(),
378
		 buffer, std::move(_pipe));
379 380
}

381
void
382
Player::StopDecoder() noexcept
383
{
384 385
	const PlayerControl::ScopeOccupied occupied(pc);

386
	dc.Stop();
387

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

391
		dc.pipe->Clear();
392
		dc.pipe.reset();
393 394 395 396 397

		/* just in case we've been cross-fading: cancel it
		   now, because we just deleted the new song's decoder
		   pipe */
		ResetCrossFade();
398 399 400
	}
}

401
bool
402
Player::ForwardDecoderError() noexcept
403
{
404 405 406 407
	try {
		dc.CheckRethrowError();
	} catch (...) {
		pc.SetError(PlayerError::DECODER, std::current_exception());
408 409 410 411 412 413
		return false;
	}

	return true;
}

414
void
415
Player::ActivateDecoder() noexcept
416
{
417
	assert(queued || pc.command == PlayerCommand::SEEK);
418
	assert(pc.next_song != nullptr);
419

420
	queued = false;
421

422
	pc.ClearTaggedSong();
423

424
	song = std::exchange(pc.next_song, nullptr);
425

426
	elapsed_time = pc.seek_time;
427

428
	/* set the "starting" flag, which will be cleared by
429
	   CheckDecoderStartup() */
430
	decoder_starting = true;
431
	pending_seek = SongTime::zero();
432

433 434 435 436
	/* update PlayerControl's song information */
	pc.total_time = song->GetDuration();
	pc.bit_rate = 0;
	pc.audio_format.Clear();
437

438 439 440 441
	{
		/* call syncPlaylistWithQueue() in the main thread */
		const ScopeUnlock unlock(pc.mutex);
		pc.listener.OnPlayerSync();
442
	}
443 444
}

445 446 447 448
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
449
static SignedSongTime
450 451
real_song_duration(const DetachedSong &song,
		   SignedSongTime decoder_duration) noexcept
452
{
453
	if (decoder_duration.IsNegative())
454
		/* the decoder plugin didn't provide information; fall
455
		   back to Song::GetDuration() */
456
		return song.GetDuration();
457

458 459
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
460

461 462
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
463

464
	return SignedSongTime(SongTime(decoder_duration) - start_time);
465 466
}

467
bool
468
Player::OpenOutput() noexcept
469
{
470
	assert(play_audio_format.IsDefined());
471 472
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);
473

474
	try {
475
		const ScopeUnlock unlock(pc.mutex);
476
		pc.outputs.Open(play_audio_format);
477 478
	} catch (...) {
		LogError(std::current_exception());
479

480
		output_open = false;
481

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

486
		pc.SetOutputError(std::current_exception());
487

488 489
		idle_add(IDLE_PLAYER);

490 491
		return false;
	}
492 493 494 495

	output_open = true;
	paused = false;

496
	pc.state = PlayerState::PLAY;
497 498 499 500

	idle_add(IDLE_PLAYER);

	return true;
501 502
}

503
bool
504
Player::CheckDecoderStartup() noexcept
505
{
506
	assert(decoder_starting);
507

508
	if (!ForwardDecoderError()) {
509 510
		/* the decoder failed */
		return false;
511
	} else if (!dc.IsStarting()) {
512
		/* the decoder is ready and ok */
513

514
		if (output_open &&
515
		    !pc.WaitOutputConsumed(1))
516 517 518 519
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

520 521 522
		pc.total_time = real_song_duration(*dc.song,
						   dc.total_time);
		pc.audio_format = dc.in_audio_format;
523 524
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
525

526 527 528 529 530 531
		const size_t buffer_before_play_size =
			play_audio_format.TimeToSize(buffer_before_play_duration);
		buffer_before_play =
			(buffer_before_play_size + sizeof(MusicChunk::data) - 1)
			/ sizeof(MusicChunk::data);

532 533
		idle_add(IDLE_PLAYER);

534 535 536 537 538 539 540 541 542
		if (pending_seek > SongTime::zero()) {
			assert(pc.seeking);

			bool success = SeekDecoder(pending_seek);
			pc.seeking = false;
			pc.ClientSignal();
			if (!success)
				return false;

543 544 545 546 547 548
			/* re-fill the buffer after seeking */
			buffering = true;
		} else if (pc.seeking) {
			pc.seeking = false;
			pc.ClientSignal();

549 550 551 552
			/* re-fill the buffer after seeking */
			buffering = true;
		}

553
		if (!paused && !OpenOutput()) {
554 555
			FormatError(player_domain,
				    "problems opening audio device "
556 557
				    "while playing \"%s\"",
				    dc.song->GetURI());
558 559
			return true;
		}
560 561 562 563 564

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
565
		dc.WaitForDecoder();
566 567 568 569 570

		return true;
	}
}

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
bool
Player::SeekDecoder(SongTime seek_time) noexcept
{
	assert(song);
	assert(!decoder_starting);

	if (!pc.total_time.IsNegative()) {
		const SongTime total_time(pc.total_time);
		if (seek_time > total_time)
			seek_time = total_time;
	}

	try {
		const PlayerControl::ScopeOccupied occupied(pc);

		dc.Seek(song->GetStartTime() + seek_time);
	} catch (...) {
		/* decoder failure */
		pc.SetError(PlayerError::DECODER, std::current_exception());
		return false;
	}

	elapsed_time = seek_time;
	return true;
}

597
inline bool
598
Player::SeekDecoder() noexcept
599
{
600
	assert(pc.next_song != nullptr);
601

602 603
	CancelPendingSeek();

604 605 606 607
	{
		const ScopeUnlock unlock(pc.mutex);
		pc.outputs.Cancel();
	}
608

609
	idle_add(IDLE_PLAYER);
610

Max Kellermann's avatar
Max Kellermann committed
611
	if (!dc.IsSeekableCurrentSong(*pc.next_song)) {
612 613 614
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

615
		StopDecoder();
616

617 618
		/* clear music chunks which might still reside in the
		   pipe */
619
		pipe->Clear();
620

621
		/* re-start the decoder */
622
		StartDecoder(pipe);
623
		ActivateDecoder();
624

625 626 627 628 629 630
		pc.seeking = true;
		pc.CommandFinished();

		assert(xfade_state == CrossFadeState::UNKNOWN);

		return true;
631
	} else {
632
		if (!IsDecoderAtCurrentSong()) {
633 634
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
635
			ReplacePipe(dc.pipe);
636 637
		}

638
		pc.next_song.reset();
639
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
640

641 642 643 644
		if (decoder_starting) {
			/* wait for the decoder to complete
			   initialization; postpone the SEEK
			   command */
645

646 647
			pending_seek = pc.seek_time;
			pc.seeking = true;
648
			pc.CommandFinished();
649 650 651 652 653 654 655 656
			return true;
		} else {
			/* send the SEEK command */

			if (!SeekDecoder(pc.seek_time)) {
				pc.CommandFinished();
				return false;
			}
657
		}
658
	}
659

660
	pc.CommandFinished();
661

662
	assert(xfade_state == CrossFadeState::UNKNOWN);
663

664
	/* re-fill the buffer after seeking */
665
	buffering = true;
666 667

	return true;
668 669
}

670
inline bool
671
Player::ProcessCommand() noexcept
672
{
673
	switch (pc.command) {
674
	case PlayerCommand::NONE:
675 676
		break;

677 678 679
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
680
		return false;
681

682
	case PlayerCommand::UPDATE_AUDIO:
683 684 685 686 687
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

688
		pc.CommandFinished();
689 690
		break;

691
	case PlayerCommand::QUEUE:
692
		assert(pc.next_song != nullptr);
693 694
		assert(!queued);
		assert(!IsDecoderAtNextSong());
695

696
		queued = true;
697
		pc.CommandFinished();
698

699
		if (dc.IsIdle())
700
			StartDecoder(std::make_shared<MusicPipe>());
701

702 703
		break;

704
	case PlayerCommand::PAUSE:
705 706
		paused = !paused;
		if (paused) {
707
			pc.state = PlayerState::PAUSE;
708 709 710

			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.Pause();
711
		} else if (!play_audio_format.IsDefined()) {
712 713
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
714
			pc.state = PlayerState::PLAY;
715
		} else {
716
			OpenOutput();
717
		}
718

719
		pc.CommandFinished();
720 721
		break;

722
	case PlayerCommand::SEEK:
723
		return SeekDecoder();
724

725
	case PlayerCommand::CANCEL:
726
		if (pc.next_song == nullptr)
727
			/* the cancel request arrived too late, we're
728 729
			   already playing the queued song...  stop
			   everything now */
730
			return false;
731

732
		if (IsDecoderAtNextSong())
733 734
			/* the decoder is already decoding the song -
			   stop it and reset the position */
735
			StopDecoder();
736

737
		pc.next_song.reset();
738
		queued = false;
739
		pc.CommandFinished();
740
		break;
741

742
	case PlayerCommand::REFRESH:
743
		if (output_open && !paused) {
744
			const ScopeUnlock unlock(pc.mutex);
745
			pc.outputs.CheckPipe();
746
		}
747

748 749
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
750
			: elapsed_time;
751

752
		pc.CommandFinished();
753
		break;
754
	}
755 756

	return true;
757 758
}

759 760 761
inline void
PlayerControl::LockUpdateSongTag(DetachedSong &song,
				 const Tag &new_tag) noexcept
762
{
763
	if (song.IsFile())
764 765 766 767
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

768
	song.SetTag(new_tag);
769

770
	LockSetTaggedSong(song);
771

772 773
	/* the main thread will update the playlist version when he
	   receives this event */
774
	listener.OnPlayerTagModified();
775 776 777 778 779 780

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

781 782 783
inline void
PlayerControl::PlayChunk(DetachedSong &song, MusicChunkPtr chunk,
			 const AudioFormat &format)
784
{
785
	assert(chunk->CheckFormat(format));
786

787
	if (chunk->tag != nullptr)
788
		LockUpdateSongTag(song, *chunk->tag);
789

790
	if (chunk->IsEmpty())
791
		return;
792

793
	{
794 795
		const std::lock_guard<Mutex> lock(mutex);
		bit_rate = chunk->bit_rate;
796
	}
797

798 799
	/* send the chunk to the audio outputs */

800 801
	const double chunk_length(chunk->length);

802
	outputs.Play(std::move(chunk));
803
	total_play_time += format.SizeToTime<decltype(total_play_time)>(chunk_length);
804 805
}

806
inline bool
807
Player::PlayNextChunk() noexcept
808
{
809
	if (!pc.LockWaitOutputConsumed(64))
810 811
		/* the output pipe is still large enough, don't send
		   another chunk */
812 813
		return true;

814 815 816 817 818 819 820 821 822 823 824
	/* activate cross-fading? */
	if (xfade_state == CrossFadeState::ENABLED &&
	    IsDecoderAtNextSong() &&
	    pipe->GetSize() <= cross_fade_chunks) {
		/* beginning of the cross fade - adjust
		   cross_fade_chunks which might be bigger than the
		   remaining number of chunks in the old song */
		cross_fade_chunks = pipe->GetSize();
		xfade_state = CrossFadeState::ACTIVE;
	}

825
	MusicChunkPtr chunk;
826
	if (xfade_state == CrossFadeState::ACTIVE) {
827 828
		/* perform cross fade */

829 830 831 832
		assert(IsDecoderAtNextSong());

		unsigned cross_fade_position = pipe->GetSize();
		assert(cross_fade_position <= cross_fade_chunks);
833

834
		auto other_chunk = dc.pipe->Shift();
835
		if (other_chunk != nullptr) {
836
			chunk = pipe->Shift();
837 838
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
839

840 841 842
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
843 844
			cross_fade_tag = Tag::Merge(std::move(cross_fade_tag),
						    std::move(other_chunk->tag));
845

846
			if (pc.cross_fade.mixramp_delay <= FloatDuration::zero()) {
847
				chunk->mix_ratio = ((float)cross_fade_position)
848
					     / cross_fade_chunks;
849
			} else {
850
				chunk->mix_ratio = -1;
851
			}
852

853
			if (other_chunk->IsEmpty()) {
854
				/* the "other" chunk was a MusicChunk
855 856 857 858 859 860
				   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 */
861
				other_chunk.reset();
862
			}
863

864
			chunk->other = std::move(other_chunk);
865
		} else {
866
			/* there are not enough decoded chunks yet */
867

868
			const std::lock_guard<Mutex> lock(pc.mutex);
869

870
			if (dc.IsIdle()) {
871
				/* the decoder isn't running, abort
872
				   cross fading */
873
				xfade_state = CrossFadeState::DISABLED;
874
			} else {
875
				/* wait for the decoder */
876 877
				dc.Signal();
				dc.WaitForDecoder();
878

879 880 881 882 883
				return true;
			}
		}
	}

884
	if (chunk == nullptr)
885
		chunk = pipe->Shift();
886

887
	assert(chunk != nullptr);
888

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

891
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
892 893
		chunk->tag = Tag::Merge(std::move(chunk->tag),
					std::move(cross_fade_tag));
894
		cross_fade_tag = nullptr;
895 896
	}

897 898
	/* play the current chunk */

899
	try {
900 901
		pc.PlayChunk(*song, std::move(chunk),
			     play_audio_format);
902 903
	} catch (...) {
		LogError(std::current_exception());
904

905
		chunk.reset();
906 907 908

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

911
		pc.LockSetOutputError(std::current_exception());
912

913 914
		idle_add(IDLE_PLAYER);

915
		return false;
916
	}
917

918
	const std::lock_guard<Mutex> lock(pc.mutex);
919

920 921
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
922
	   larger block at a time */
923
	if (!dc.IsIdle() && dc.pipe->GetSize() <= decoder_wakeup_threshold) {
924 925 926 927 928 929
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
930 931 932 933

	return true;
}

934
inline void
935
Player::SongBorder() noexcept
936
{
937 938
	{
		const ScopeUnlock unlock(pc.mutex);
939

940
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
941

942
		ReplacePipe(dc.pipe);
943

944
		pc.outputs.SongBorder();
945
	}
946

947 948 949
	ActivateDecoder();

	const bool border_pause = pc.ApplyBorderPause();
950
	if (border_pause) {
951
		paused = true;
952
		pc.listener.OnBorderPause();
953
		pc.outputs.Pause();
954
		idle_add(IDLE_PLAYER);
955
	}
956 957
}

958
inline void
959
Player::Run() noexcept
960
{
961
	pipe = std::make_shared<MusicPipe>();
962

963
	const std::lock_guard<Mutex> lock(pc.mutex);
964

965
	StartDecoder(pipe);
966
	ActivateDecoder();
967

968
	pc.state = PlayerState::PLAY;
969

970
	pc.CommandFinished();
971

972
	while (ProcessCommand()) {
973 974 975 976 977 978 979 980 981
		if (decoder_starting) {
			/* wait until the decoder is initialized completely */

			if (!CheckDecoderStartup())
				break;

			continue;
		}

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

987
			if (pipe->GetSize() < buffer_before_play &&
988
			    !dc.IsIdle() && !buffer.IsFull()) {
989
				/* not enough decoded buffer space yet */
990

991
				dc.WaitForDecoder();
992 993 994
				continue;
			} else {
				/* buffering is complete */
995
				buffering = false;
996 997 998
			}
		}

999
		if (dc.IsIdle() && queued && dc.pipe == pipe) {
1000 1001
			/* the decoder has finished the current song;
			   make it decode the next song */
1002

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

1005
			StartDecoder(std::make_shared<MusicPipe>());
1006
		}
1007

1008 1009
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
1010
		    !pc.border_pause &&
1011
		    IsDecoderAtNextSong() &&
1012
		    xfade_state == CrossFadeState::UNKNOWN &&
1013
		    !dc.IsStarting()) {
1014 1015 1016
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
1017
			cross_fade_chunks =
1018
				pc.cross_fade.Calculate(dc.total_time,
1019 1020 1021 1022 1023 1024 1025
							dc.replay_gain_db,
							dc.replay_gain_prev_db,
							dc.GetMixRampStart(),
							dc.GetMixRampPreviousEnd(),
							dc.out_audio_format,
							play_audio_format,
							buffer.GetSize() -
1026
							buffer_before_play);
1027
			if (cross_fade_chunks > 0)
1028
				xfade_state = CrossFadeState::ENABLED;
1029
			else
1030 1031
				/* cross fading is disabled or the
				   next song is too short */
1032
				xfade_state = CrossFadeState::DISABLED;
1033 1034
		}

1035
		if (paused) {
1036
			if (pc.command == PlayerCommand::NONE)
1037
				pc.Wait();
1038
		} else if (!pipe->IsEmpty()) {
1039 1040
			/* at least one music chunk is ready - send it
			   to the audio output */
1041

1042
			const ScopeUnlock unlock(pc.mutex);
1043
			PlayNextChunk();
1044
		} else if (UnlockCheckOutputs() > 0) {
1045 1046 1047 1048
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1049 1050 1051
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
1052
			// TODO: eliminate this kludge
1053
			dc.Signal();
1054

1055
			dc.WaitForDecoder();
1056
		} else if (IsDecoderAtNextSong()) {
1057 1058
			/* at the beginning of a new song */

1059
			SongBorder();
1060
		} else if (dc.IsIdle()) {
1061 1062 1063
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1064
			if (pipe->IsEmpty()) {
1065 1066
				/* wait for the hardware to finish
				   playback */
1067
				const ScopeUnlock unlock(pc.mutex);
1068
				pc.outputs.Drain();
1069
				break;
1070
			}
1071
		} else if (output_open) {
1072
			/* the decoder is too busy and hasn't provided
1073 1074
			   new PCM data in time: wait for the
			   decoder */
1075

1076 1077 1078 1079 1080 1081
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
			// TODO: eliminate this kludge
			dc.Signal();

1082
			dc.WaitForDecoder();
1083 1084 1085
		}
	}

1086
	CancelPendingSeek();
1087
	StopDecoder();
1088

1089
	pipe.reset();
1090

1091
	cross_fade_tag.reset();
1092

1093
	if (song != nullptr) {
1094
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
1095
		song.reset();
1096
	}
1097

1098 1099
	pc.ClearTaggedSong();

1100
	if (queued) {
1101
		assert(pc.next_song != nullptr);
1102
		pc.next_song.reset();
1103 1104
	}

1105
	pc.state = PlayerState::STOP;
1106 1107
}

1108
static void
1109
do_play(PlayerControl &pc, DecoderControl &dc,
1110
	MusicBuffer &buffer) noexcept
1111
{
1112
	Player player(pc, dc, buffer);
1113 1114 1115
	player.Run();
}

1116
void
1117
PlayerControl::RunThread() noexcept
1118
try {
1119 1120
	SetThreadName("player");

1121 1122 1123
	DecoderControl dc(mutex, cond,
			  configured_audio_format,
			  replay_gain_config);
1124
	dc.StartThread();
1125

1126
	MusicBuffer buffer(buffer_chunks);
1127

1128
	const std::lock_guard<Mutex> lock(mutex);
1129

1130
	while (1) {
1131
		switch (command) {
1132 1133
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1134
			assert(next_song != nullptr);
1135

1136 1137 1138 1139 1140 1141
			{
				const ScopeUnlock unlock(mutex);
				do_play(*this, dc, buffer);
				listener.OnPlayerSync();
			}

1142 1143
			break;

1144
		case PlayerCommand::STOP:
1145 1146 1147 1148
			{
				const ScopeUnlock unlock(mutex);
				outputs.Cancel();
			}
1149

1150 1151
			/* fall through */

1152
		case PlayerCommand::PAUSE:
1153
			next_song.reset();
1154

1155
			CommandFinished();
1156 1157
			break;

1158
		case PlayerCommand::CLOSE_AUDIO:
1159 1160 1161 1162
			{
				const ScopeUnlock unlock(mutex);
				outputs.Release();
			}
1163

1164
			CommandFinished();
1165

1166
			assert(buffer.IsEmptyUnsafe());
1167

1168 1169
			break;

1170
		case PlayerCommand::UPDATE_AUDIO:
1171 1172 1173 1174 1175
			{
				const ScopeUnlock unlock(mutex);
				outputs.EnableDisable();
			}

1176
			CommandFinished();
1177 1178
			break;

1179
		case PlayerCommand::EXIT:
1180 1181 1182 1183 1184
			{
				const ScopeUnlock unlock(mutex);
				dc.Quit();
				outputs.Close();
			}
1185

1186
			CommandFinished();
1187
			return;
Max Kellermann's avatar
Max Kellermann committed
1188

1189
		case PlayerCommand::CANCEL:
1190
			next_song.reset();
1191

1192
			CommandFinished();
1193 1194
			break;

1195
		case PlayerCommand::REFRESH:
1196
			/* no-op when not playing */
1197
			CommandFinished();
1198 1199
			break;

1200
		case PlayerCommand::NONE:
1201
			Wait();
1202 1203 1204
			break;
		}
	}
1205 1206 1207 1208 1209 1210 1211 1212
} catch (...) {
	/* exceptions caught here are thrown during initialization;
	   the main loop doesn't throw */

	LogError(std::current_exception());

	/* TODO: what now? How will the main thread learn about this
	   failure? */
1213
}