Thread.cxx 25.8 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2017 The Music Player Daemon Project
3
 * http://www.musicpd.org
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 26 27 28 29 30 31 32 33 34 35 36
/* \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
 * audio outputs via audio_output_all_play().
 *
 * 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.
 */

37
#include "config.h"
38
#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
class Player {
61
	PlayerControl &pc;
62

63
	DecoderControl &dc;
64

65 66
	MusicBuffer &buffer;

67
	std::shared_ptr<MusicPipe> pipe;
68

69 70 71 72 73 74 75 76 77 78 79 80
	/**
	 * 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;

81
	/**
82
	 * are we waiting for buffered_before_play?
83
	 */
84
	bool buffering = true;
85 86 87 88 89

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

92 93 94 95
	/**
	 * Did we wake up the DecoderThread recently?  This avoids
	 * duplicate wakeup calls.
	 */
96
	bool decoder_woken = false;
97

98 99 100
	/**
	 * is the player paused?
	 */
101
	bool paused = false;
102

103 104 105
	/**
	 * is there a new song in pc.next_song?
	 */
106
	bool queued = true;
107

108 109 110 111 112 113
	/**
	 * 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.
	 */
114
	bool output_open = false;
115

116
	/**
117
	 * Is cross-fading to the next song enabled?
118
	 */
119
	enum class CrossFadeState : uint8_t {
120 121 122 123
		/**
		 * The initial state: we don't know yet if we will
		 * cross-fade; it will be determined soon.
		 */
124
		UNKNOWN,
125 126 127 128 129

		/**
		 * Cross-fading is disabled for the transition to the
		 * next song.
		 */
130
		DISABLED,
131 132 133 134 135 136

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

139 140 141 142
		/**
		 * Currently cross-fading to the next song.
		 */
		ACTIVE,
143
	} xfade_state = CrossFadeState::UNKNOWN;
144 145 146 147

	/**
	 * The number of chunks used for crossfading.
	 */
148
	unsigned cross_fade_chunks = 0;
149

150 151 152
	/**
	 * The current audio format for the audio outputs.
	 */
153
	AudioFormat play_audio_format = AudioFormat::Undefined();
154 155 156 157

	/**
	 * The time stamp of the chunk most recently sent to the
	 * output thread.  This attribute is only used if
158
	 * MultipleOutputs::GetElapsedTime() didn't return a usable
159
	 * value; the output thread can estimate the elapsed time more
160
	 * precisely.
161
	 */
162
	SongTime elapsed_time = SongTime::zero();
163

164 165 166 167 168 169 170 171 172 173
	/**
	 * 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;

174
public:
175
	Player(PlayerControl &_pc, DecoderControl &_dc,
176
	       MusicBuffer &_buffer) noexcept
177
		:pc(_pc), dc(_dc), buffer(_buffer) {}
178

179
private:
180 181 182 183
	/**
	 * Reset cross-fading to the initial state.  A check to
	 * re-enable it at an appropriate time will be scheduled.
	 */
184
	void ResetCrossFade() noexcept {
185 186 187
		xfade_state = CrossFadeState::UNKNOWN;
	}

188 189
	template<typename P>
	void ReplacePipe(P &&_pipe) noexcept {
190
		ResetCrossFade();
191
		pipe = std::forward<P>(_pipe);
192 193 194 195 196
	}

	/**
	 * Start the decoder.
	 *
197
	 * Caller must lock the mutex.
198
	 */
199
	void StartDecoder(std::shared_ptr<MusicPipe> pipe) noexcept;
200 201 202

	/**
	 * The decoder has acknowledged the "START" command (see
203
	 * ActivateDecoder()).  This function checks if the decoder
204 205
	 * initialization has completed yet.  If not, it will wait
	 * some more.
206
	 *
207
	 * Caller must lock the mutex.
208 209 210
	 *
	 * @return false if the decoder has failed, true on success
	 * (though the decoder startup may or may not yet be finished)
211
	 */
212
	bool CheckDecoderStartup() noexcept;
213 214 215 216

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
217
	 * Caller must lock the mutex.
218
	 */
219
	void StopDecoder() noexcept;
220 221 222 223 224 225 226 227

	/**
	 * 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
228
	bool IsDecoderAtCurrentSong() const noexcept {
229 230 231 232 233 234 235 236 237 238 239
		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
240
	bool IsDecoderAtNextSong() const noexcept {
241 242 243
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

244 245 246 247 248 249 250 251 252 253
	/**
	 * 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;

254
	/**
255
	 * This is the handler for the #PlayerCommand::SEEK command.
256
	 *
257
	 * Caller must lock the mutex.
258 259
	 *
	 * @return false if the decoder has failed
260
	 */
261
	bool SeekDecoder() noexcept;
262

263 264
	void CancelPendingSeek() noexcept {
		pending_seek = SongTime::zero();
265
		pc.CancelPendingSeek();
266 267
	}

268 269 270 271 272 273
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
274
	bool ForwardDecoderError() noexcept;
275

276
	/**
277 278 279 280 281 282 283 284 285
	 * 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().
286
	 *
287
	 * Caller must lock the mutex.
288
	 */
289
	void ActivateDecoder() noexcept;
290 291

	/**
292 293
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
294
	 *
295 296
	 * Caller must lock the mutex.
	 *
297 298
	 * @return true on success
	 */
299
	bool OpenOutput() noexcept;
300 301 302 303 304 305 306

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

309 310
	unsigned UnlockCheckOutputs() noexcept {
		const ScopeUnlock unlock(pc.mutex);
311
		return pc.outputs.CheckPipe();
312 313
	}

314 315
	/**
	 * Player lock must be held before calling.
316 317
	 *
	 * @return false to stop playback
318
	 */
319
	bool ProcessCommand() noexcept;
320 321 322 323 324 325

	/**
	 * 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.
	 *
326
	 * Caller must lock the mutex.
327
	 */
328
	void SongBorder() noexcept;
329

330
public:
331 332 333 334 335
	/*
	 * 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.
	 */
336
	void Run() noexcept;
337 338
};

339
void
340
Player::StartDecoder(std::shared_ptr<MusicPipe> _pipe) noexcept
341
{
342
	assert(queued || pc.command == PlayerCommand::SEEK);
343
	assert(pc.next_song != nullptr);
344

345 346
	/* copy ReplayGain parameters to the decoder */
	dc.replay_gain_mode = pc.replay_gain_mode;
347

348
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
349

350
	dc.Start(std::make_unique<DetachedSong>(*pc.next_song),
351
		 start_time, pc.next_song->GetEndTime(),
352
		 buffer, std::move(_pipe));
353 354
}

355
void
356
Player::StopDecoder() noexcept
357
{
358 359
	const PlayerControl::ScopeOccupied occupied(pc);

360
	dc.Stop();
361

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

365
		dc.pipe->Clear();
366
		dc.pipe.reset();
367 368 369 370 371

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

375
bool
376
Player::ForwardDecoderError() noexcept
377
{
378 379 380 381
	try {
		dc.CheckRethrowError();
	} catch (...) {
		pc.SetError(PlayerError::DECODER, std::current_exception());
382 383 384 385 386 387
		return false;
	}

	return true;
}

388
void
389
Player::ActivateDecoder() noexcept
390
{
391
	assert(queued || pc.command == PlayerCommand::SEEK);
392
	assert(pc.next_song != nullptr);
393

394
	queued = false;
395

396
	pc.ClearTaggedSong();
397

398
	song = std::exchange(pc.next_song, nullptr);
399

400
	elapsed_time = pc.seek_time;
401

402
	/* set the "starting" flag, which will be cleared by
403
	   CheckDecoderStartup() */
404
	decoder_starting = true;
405
	pending_seek = SongTime::zero();
406

407 408 409 410
	/* update PlayerControl's song information */
	pc.total_time = song->GetDuration();
	pc.bit_rate = 0;
	pc.audio_format.Clear();
411

412 413 414 415
	{
		/* call syncPlaylistWithQueue() in the main thread */
		const ScopeUnlock unlock(pc.mutex);
		pc.listener.OnPlayerSync();
416
	}
417 418
}

419 420 421 422
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
423
static SignedSongTime
424 425
real_song_duration(const DetachedSong &song,
		   SignedSongTime decoder_duration) noexcept
426
{
427
	if (decoder_duration.IsNegative())
428
		/* the decoder plugin didn't provide information; fall
429
		   back to Song::GetDuration() */
430
		return song.GetDuration();
431

432 433
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
434

435 436
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
437

438
	return SignedSongTime(SongTime(decoder_duration) - start_time);
439 440
}

441
bool
442
Player::OpenOutput() noexcept
443
{
444
	assert(play_audio_format.IsDefined());
445 446
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);
447

448
	try {
449
		const ScopeUnlock unlock(pc.mutex);
450
		pc.outputs.Open(play_audio_format);
451 452
	} catch (...) {
		LogError(std::current_exception());
453

454
		output_open = false;
455

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

460
		pc.SetOutputError(std::current_exception());
461

462 463
		idle_add(IDLE_PLAYER);

464 465
		return false;
	}
466 467 468 469

	output_open = true;
	paused = false;

470
	pc.state = PlayerState::PLAY;
471 472 473 474

	idle_add(IDLE_PLAYER);

	return true;
475 476
}

477
bool
478
Player::CheckDecoderStartup() noexcept
479
{
480
	assert(decoder_starting);
481

482
	if (!ForwardDecoderError()) {
483 484
		/* the decoder failed */
		return false;
485
	} else if (!dc.IsStarting()) {
486
		/* the decoder is ready and ok */
487

488
		if (output_open &&
489
		    !pc.WaitOutputConsumed(1))
490 491 492 493
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

494 495 496
		pc.total_time = real_song_duration(*dc.song,
						   dc.total_time);
		pc.audio_format = dc.in_audio_format;
497 498
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
499

500 501
		idle_add(IDLE_PLAYER);

502 503 504 505 506 507 508 509 510
		if (pending_seek > SongTime::zero()) {
			assert(pc.seeking);

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

511 512 513 514 515 516
			/* re-fill the buffer after seeking */
			buffering = true;
		} else if (pc.seeking) {
			pc.seeking = false;
			pc.ClientSignal();

517 518 519 520
			/* re-fill the buffer after seeking */
			buffering = true;
		}

521
		if (!paused && !OpenOutput()) {
522 523
			FormatError(player_domain,
				    "problems opening audio device "
524 525
				    "while playing \"%s\"",
				    dc.song->GetURI());
526 527
			return true;
		}
528 529 530 531 532

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
533
		dc.WaitForDecoder();
534 535 536 537 538

		return true;
	}
}

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

565
inline bool
566
Player::SeekDecoder() noexcept
567
{
568
	assert(pc.next_song != nullptr);
569

570 571
	CancelPendingSeek();

572 573 574 575
	{
		const ScopeUnlock unlock(pc.mutex);
		pc.outputs.Cancel();
	}
576

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

581
		StopDecoder();
582

583 584
		/* clear music chunks which might still reside in the
		   pipe */
585
		pipe->Clear();
586

587
		/* re-start the decoder */
588
		StartDecoder(pipe);
589
		ActivateDecoder();
590

591 592 593 594 595 596
		pc.seeking = true;
		pc.CommandFinished();

		assert(xfade_state == CrossFadeState::UNKNOWN);

		return true;
597
	} else {
598
		if (!IsDecoderAtCurrentSong()) {
599 600
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
601
			ReplacePipe(dc.pipe);
602 603
		}

604
		pc.next_song.reset();
605
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
606

607 608 609 610
		if (decoder_starting) {
			/* wait for the decoder to complete
			   initialization; postpone the SEEK
			   command */
611

612 613
			pending_seek = pc.seek_time;
			pc.seeking = true;
614
			pc.CommandFinished();
615 616 617 618 619 620 621 622
			return true;
		} else {
			/* send the SEEK command */

			if (!SeekDecoder(pc.seek_time)) {
				pc.CommandFinished();
				return false;
			}
623
		}
624
	}
625

626
	pc.CommandFinished();
627

628
	assert(xfade_state == CrossFadeState::UNKNOWN);
629

630
	/* re-fill the buffer after seeking */
631
	buffering = true;
632 633

	return true;
634 635
}

636
inline bool
637
Player::ProcessCommand() noexcept
638
{
639
	switch (pc.command) {
640
	case PlayerCommand::NONE:
641 642
		break;

643 644 645
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
646
		return false;
647

648
	case PlayerCommand::UPDATE_AUDIO:
649 650 651 652 653
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

654
		pc.CommandFinished();
655 656
		break;

657
	case PlayerCommand::QUEUE:
658
		assert(pc.next_song != nullptr);
659 660
		assert(!queued);
		assert(!IsDecoderAtNextSong());
661

662
		queued = true;
663
		pc.CommandFinished();
664

665
		if (dc.IsIdle())
666
			StartDecoder(std::make_shared<MusicPipe>());
667

668 669
		break;

670
	case PlayerCommand::PAUSE:
671 672
		paused = !paused;
		if (paused) {
673
			pc.state = PlayerState::PAUSE;
674 675 676

			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.Pause();
677
		} else if (!play_audio_format.IsDefined()) {
678 679
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
680
			pc.state = PlayerState::PLAY;
681
		} else {
682
			OpenOutput();
683
		}
684

685
		pc.CommandFinished();
686 687
		break;

688
	case PlayerCommand::SEEK:
689
		return SeekDecoder();
690

691
	case PlayerCommand::CANCEL:
692
		if (pc.next_song == nullptr)
693
			/* the cancel request arrived too late, we're
694 695
			   already playing the queued song...  stop
			   everything now */
696
			return false;
697

698
		if (IsDecoderAtNextSong())
699 700
			/* the decoder is already decoding the song -
			   stop it and reset the position */
701
			StopDecoder();
702

703
		pc.next_song.reset();
704
		queued = false;
705
		pc.CommandFinished();
706
		break;
707

708
	case PlayerCommand::REFRESH:
709
		if (output_open && !paused) {
710
			const ScopeUnlock unlock(pc.mutex);
711
			pc.outputs.CheckPipe();
712
		}
713

714 715
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
716
			: elapsed_time;
717

718
		pc.CommandFinished();
719
		break;
720
	}
721 722

	return true;
723 724
}

725 726 727
inline void
PlayerControl::LockUpdateSongTag(DetachedSong &song,
				 const Tag &new_tag) noexcept
728
{
729
	if (song.IsFile())
730 731 732 733
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

734
	song.SetTag(new_tag);
735

736
	LockSetTaggedSong(song);
737

738 739
	/* the main thread will update the playlist version when he
	   receives this event */
740
	listener.OnPlayerTagModified();
741 742 743 744 745 746

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

747 748 749
inline void
PlayerControl::PlayChunk(DetachedSong &song, MusicChunkPtr chunk,
			 const AudioFormat &format)
750
{
751
	assert(chunk->CheckFormat(format));
752

753
	if (chunk->tag != nullptr)
754
		LockUpdateSongTag(song, *chunk->tag);
755

756
	if (chunk->IsEmpty())
757
		return;
758

759
	{
760 761
		const std::lock_guard<Mutex> lock(mutex);
		bit_rate = chunk->bit_rate;
762
	}
763

764 765
	/* send the chunk to the audio outputs */

766 767
	const double chunk_length(chunk->length);

768 769
	outputs.Play(std::move(chunk));
	total_play_time += chunk_length / format.GetTimeToSize();
770 771
}

772
inline bool
773
Player::PlayNextChunk() noexcept
774
{
775
	if (!pc.LockWaitOutputConsumed(64))
776 777
		/* the output pipe is still large enough, don't send
		   another chunk */
778 779
		return true;

780 781 782 783 784 785 786 787 788 789 790
	/* 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;
	}

791
	MusicChunkPtr chunk;
792
	if (xfade_state == CrossFadeState::ACTIVE) {
793 794
		/* perform cross fade */

795 796 797 798
		assert(IsDecoderAtNextSong());

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

800
		auto other_chunk = dc.pipe->Shift();
801
		if (other_chunk != nullptr) {
802
			chunk = pipe->Shift();
803 804
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
805

806 807 808
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
809 810
			cross_fade_tag = Tag::Merge(std::move(cross_fade_tag),
						    std::move(other_chunk->tag));
811

812
			if (pc.cross_fade.mixramp_delay <= 0) {
813
				chunk->mix_ratio = ((float)cross_fade_position)
814
					     / cross_fade_chunks;
815
			} else {
816
				chunk->mix_ratio = -1;
817
			}
818

819
			if (other_chunk->IsEmpty()) {
820
				/* the "other" chunk was a MusicChunk
821 822 823 824 825 826
				   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 */
827
				other_chunk.reset();
828
			}
829

830
			chunk->other = std::move(other_chunk);
831
		} else {
832
			/* there are not enough decoded chunks yet */
833

834
			const std::lock_guard<Mutex> lock(pc.mutex);
835

836
			if (dc.IsIdle()) {
837
				/* the decoder isn't running, abort
838
				   cross fading */
839
				xfade_state = CrossFadeState::DISABLED;
840
			} else {
841
				/* wait for the decoder */
842 843
				dc.Signal();
				dc.WaitForDecoder();
844

845 846 847 848 849
				return true;
			}
		}
	}

850
	if (chunk == nullptr)
851
		chunk = pipe->Shift();
852

853
	assert(chunk != nullptr);
854

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

857
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
858 859
		chunk->tag = Tag::Merge(std::move(chunk->tag),
					std::move(cross_fade_tag));
860
		cross_fade_tag = nullptr;
861 862
	}

863 864
	/* play the current chunk */

865
	try {
866 867
		pc.PlayChunk(*song, std::move(chunk),
			     play_audio_format);
868 869
	} catch (...) {
		LogError(std::current_exception());
870

871
		chunk.reset();
872 873 874

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

877
		pc.LockSetOutputError(std::current_exception());
878

879 880
		idle_add(IDLE_PLAYER);

881
		return false;
882
	}
883

884
	const std::lock_guard<Mutex> lock(pc.mutex);
885

886 887
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
888
	   larger block at a time */
889 890
	if (!dc.IsIdle() &&
	    dc.pipe->GetSize() <= (pc.buffered_before_play +
891 892 893 894 895 896 897
				   buffer.GetSize() * 3) / 4) {
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
898 899 900 901

	return true;
}

902
inline void
903
Player::SongBorder() noexcept
904
{
905 906
	{
		const ScopeUnlock unlock(pc.mutex);
907

908
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
909

910
		ReplacePipe(dc.pipe);
911

912
		pc.outputs.SongBorder();
913
	}
914

915 916 917
	ActivateDecoder();

	const bool border_pause = pc.ApplyBorderPause();
918
	if (border_pause) {
919
		paused = true;
920
		pc.listener.OnBorderPause();
921
		pc.outputs.Pause();
922
		idle_add(IDLE_PLAYER);
923
	}
924 925
}

926
inline void
927
Player::Run() noexcept
928
{
929
	pipe = std::make_shared<MusicPipe>();
930

931
	const std::lock_guard<Mutex> lock(pc.mutex);
932

933
	StartDecoder(pipe);
934
	ActivateDecoder();
935

936
	pc.state = PlayerState::PLAY;
937

938
	pc.CommandFinished();
939

940
	while (ProcessCommand()) {
941
		if (buffering) {
942 943 944 945
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

946
			if (pipe->GetSize() < pc.buffered_before_play &&
947
			    !dc.IsIdle()) {
948
				/* not enough decoded buffer space yet */
949

950
				dc.WaitForDecoder();
951 952 953
				continue;
			} else {
				/* buffering is complete */
954
				buffering = false;
955 956 957
			}
		}

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

961
			if (!CheckDecoderStartup())
962
				break;
963

964
			continue;
965 966
		}

967
		if (dc.IsIdle() && queued && dc.pipe == pipe) {
968 969
			/* the decoder has finished the current song;
			   make it decode the next song */
970

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

973
			StartDecoder(std::make_shared<MusicPipe>());
974
		}
975

976 977
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
978
		    !pc.border_pause &&
979
		    IsDecoderAtNextSong() &&
980
		    xfade_state == CrossFadeState::UNKNOWN &&
981
		    !dc.IsStarting()) {
982 983 984
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
985
			cross_fade_chunks =
986
				pc.cross_fade.Calculate(dc.total_time,
987 988 989 990 991 992 993 994
							dc.replay_gain_db,
							dc.replay_gain_prev_db,
							dc.GetMixRampStart(),
							dc.GetMixRampPreviousEnd(),
							dc.out_audio_format,
							play_audio_format,
							buffer.GetSize() -
							pc.buffered_before_play);
995
			if (cross_fade_chunks > 0)
996
				xfade_state = CrossFadeState::ENABLED;
997
			else
998 999
				/* cross fading is disabled or the
				   next song is too short */
1000
				xfade_state = CrossFadeState::DISABLED;
1001 1002
		}

1003
		if (paused) {
1004
			if (pc.command == PlayerCommand::NONE)
1005
				pc.Wait();
1006
		} else if (!pipe->IsEmpty()) {
1007 1008
			/* at least one music chunk is ready - send it
			   to the audio output */
1009

1010
			const ScopeUnlock unlock(pc.mutex);
1011
			PlayNextChunk();
1012
		} else if (UnlockCheckOutputs() > 0) {
1013 1014 1015 1016
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1017 1018 1019
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
1020
			// TODO: eliminate this kludge
1021
			dc.Signal();
1022

1023
			dc.WaitForDecoder();
1024
		} else if (IsDecoderAtNextSong()) {
1025 1026
			/* at the beginning of a new song */

1027
			SongBorder();
1028
		} else if (dc.IsIdle()) {
1029 1030 1031
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1032
			if (pipe->IsEmpty()) {
1033 1034
				/* wait for the hardware to finish
				   playback */
1035
				const ScopeUnlock unlock(pc.mutex);
1036
				pc.outputs.Drain();
1037
				break;
1038
			}
1039
		} else if (output_open) {
1040
			/* the decoder is too busy and hasn't provided
1041 1042
			   new PCM data in time: wait for the
			   decoder */
1043

1044 1045 1046 1047 1048 1049
			/* 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();

1050
			dc.WaitForDecoder();
1051 1052 1053
		}
	}

1054
	CancelPendingSeek();
1055
	StopDecoder();
1056

1057
	pipe.reset();
1058

1059
	cross_fade_tag.reset();
1060

1061
	if (song != nullptr) {
1062
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
1063
		song.reset();
1064
	}
1065

1066 1067
	pc.ClearTaggedSong();

1068
	if (queued) {
1069
		assert(pc.next_song != nullptr);
1070
		pc.next_song.reset();
1071 1072
	}

1073
	pc.state = PlayerState::STOP;
1074 1075
}

1076
static void
1077
do_play(PlayerControl &pc, DecoderControl &dc,
1078
	MusicBuffer &buffer) noexcept
1079
{
1080
	Player player(pc, dc, buffer);
1081 1082 1083
	player.Run();
}

1084
void
1085
PlayerControl::RunThread() noexcept
1086
try {
1087 1088
	SetThreadName("player");

1089 1090 1091
	DecoderControl dc(mutex, cond,
			  configured_audio_format,
			  replay_gain_config);
1092
	dc.StartThread();
1093

1094
	MusicBuffer buffer(buffer_chunks);
1095

1096
	const std::lock_guard<Mutex> lock(mutex);
1097

1098
	while (1) {
1099
		switch (command) {
1100 1101
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1102
			assert(next_song != nullptr);
1103

1104 1105 1106 1107 1108 1109
			{
				const ScopeUnlock unlock(mutex);
				do_play(*this, dc, buffer);
				listener.OnPlayerSync();
			}

1110 1111
			break;

1112
		case PlayerCommand::STOP:
1113 1114 1115 1116
			{
				const ScopeUnlock unlock(mutex);
				outputs.Cancel();
			}
1117

1118 1119
			/* fall through */

1120
		case PlayerCommand::PAUSE:
1121
			next_song.reset();
1122

1123
			CommandFinished();
1124 1125
			break;

1126
		case PlayerCommand::CLOSE_AUDIO:
1127 1128 1129 1130
			{
				const ScopeUnlock unlock(mutex);
				outputs.Release();
			}
1131

1132
			CommandFinished();
1133

1134
			assert(buffer.IsEmptyUnsafe());
1135

1136 1137
			break;

1138
		case PlayerCommand::UPDATE_AUDIO:
1139 1140 1141 1142 1143
			{
				const ScopeUnlock unlock(mutex);
				outputs.EnableDisable();
			}

1144
			CommandFinished();
1145 1146
			break;

1147
		case PlayerCommand::EXIT:
1148 1149 1150 1151 1152
			{
				const ScopeUnlock unlock(mutex);
				dc.Quit();
				outputs.Close();
			}
1153

1154
			CommandFinished();
1155
			return;
Max Kellermann's avatar
Max Kellermann committed
1156

1157
		case PlayerCommand::CANCEL:
1158
			next_song.reset();
1159

1160
			CommandFinished();
1161 1162
			break;

1163
		case PlayerCommand::REFRESH:
1164
			/* no-op when not playing */
1165
			CommandFinished();
1166 1167
			break;

1168
		case PlayerCommand::NONE:
1169
			Wait();
1170 1171 1172
			break;
		}
	}
1173 1174 1175 1176 1177 1178 1179 1180
} 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? */
1181
}