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

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

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

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

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

61 62 63 64 65 66
/**
 * 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);

67
class Player {
68
	PlayerControl &pc;
69

70
	DecoderControl &dc;
71

72 73
	MusicBuffer &buffer;

74
	std::shared_ptr<MusicPipe> pipe;
75

76 77 78 79 80 81 82 83 84 85 86 87
	/**
	 * 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;

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

95 96 97 98 99 100 101 102 103 104
	/**
	 * 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;

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

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

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

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

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

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

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

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

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

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

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

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

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

188 189 190 191 192 193 194 195 196 197
	/**
	 * 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;

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

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

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

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

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

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

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

271 272 273 274 275 276 277 278 279 280
	/**
	 * 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;

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

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

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

303
	/**
304 305 306 307 308 309 310 311 312
	 * 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().
313
	 *
314
	 * Caller must lock the mutex.
315
	 */
316
	void ActivateDecoder() noexcept;
317 318

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

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

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

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

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

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

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

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

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

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

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

387
	dc.Stop();
388

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

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

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

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

	return true;
}

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

421
	queued = false;
422

423
	pc.ClearTaggedSong();
424

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

427
	elapsed_time = pc.seek_time;
428

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

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

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

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

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

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

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

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

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

481
		output_open = false;
482

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

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

489 490
		idle_add(IDLE_PLAYER);

491 492
		return false;
	}
493 494 495 496

	output_open = true;
	paused = false;

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

	idle_add(IDLE_PLAYER);

	return true;
502 503
}

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

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

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

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

527 528 529 530 531 532
		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);

533 534
		idle_add(IDLE_PLAYER);

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

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

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

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

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

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

		return true;
	}
}

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

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

603 604
	CancelPendingSeek();

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

610
	idle_add(IDLE_PLAYER);
611

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

616
		StopDecoder();
617

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

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

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

		assert(xfade_state == CrossFadeState::UNKNOWN);

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

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

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

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

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

661
	pc.CommandFinished();
662

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

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

	return true;
669 670
}

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

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

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

689
		pc.CommandFinished();
690 691
		break;

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

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

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

703 704
		break;

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

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

720
		pc.CommandFinished();
721 722
		break;

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

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

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

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

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

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

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

	return true;
758 759
}

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

769
	song.SetTag(new_tag);
770

771
	LockSetTaggedSong(song);
772

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

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

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

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

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

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

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

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

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

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

815 816 817 818 819 820 821 822 823 824 825
	/* 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;
	}

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

830 831 832 833
		assert(IsDecoderAtNextSong());

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

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

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

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

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

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

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

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

880 881 882 883 884
				return true;
			}
		}
	}

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

888
	assert(chunk != nullptr);
889

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

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

898 899
	/* play the current chunk */

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

906
		chunk.reset();
907 908 909

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

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

914 915
		idle_add(IDLE_PLAYER);

916
		return false;
917
	}
918

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

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

	return true;
}

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

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

943
		ReplacePipe(dc.pipe);
944

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

948 949 950
	ActivateDecoder();

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

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

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

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

969
	pc.state = PlayerState::PLAY;
970

971
	pc.CommandFinished();
972

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

			if (!CheckDecoderStartup())
				break;

			continue;
		}

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

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

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

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

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

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

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

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

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

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

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

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

1077 1078 1079 1080 1081 1082
			/* 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();

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

1087
	CancelPendingSeek();
1088
	StopDecoder();
1089

1090
	pipe.reset();
1091

1092
	cross_fade_tag.reset();
1093

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

1099 1100
	pc.ClearTaggedSong();

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

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

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

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

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

1127
	MusicBuffer buffer(buffer_chunks);
1128

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

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

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

1143 1144
			break;

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

1151 1152
			/* fall through */

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

1156
			CommandFinished();
1157 1158
			break;

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

1165
			CommandFinished();
1166

1167
			assert(buffer.IsEmptyUnsafe());
1168

1169 1170
			break;

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

1177
			CommandFinished();
1178 1179
			break;

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

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

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

1193
			CommandFinished();
1194 1195
			break;

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

1201
		case PlayerCommand::NONE:
1202
			Wait();
1203 1204 1205
			break;
		}
	}
1206 1207 1208 1209 1210 1211 1212 1213
} 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? */
1214
}