Thread.cxx 25.5 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
#include "config.h"
21
#include "Thread.hxx"
22
#include "Outputs.hxx"
23
#include "Listener.hxx"
24 25
#include "decoder/DecoderThread.hxx"
#include "decoder/DecoderControl.hxx"
26 27 28
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
29
#include "DetachedSong.hxx"
30
#include "CrossFade.hxx"
31
#include "Control.hxx"
32
#include "tag/Tag.hxx"
Max Kellermann's avatar
Max Kellermann committed
33
#include "Idle.hxx"
34
#include "util/Domain.hxx"
35
#include "thread/Name.hxx"
36
#include "Log.hxx"
37

38
#include <exception>
39

Max Kellermann's avatar
Max Kellermann committed
40 41
#include <string.h>

42
static constexpr Domain player_domain("player");
43

44
class Player {
45
	PlayerControl &pc;
46

47
	DecoderControl &dc;
48

49 50
	MusicBuffer &buffer;

51
	MusicPipe *pipe;
52

53 54 55 56 57 58 59 60 61 62 63 64
	/**
	 * 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;

65
	/**
66
	 * are we waiting for buffered_before_play?
67
	 */
68
	bool buffering = true;
69 70 71 72 73

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

76 77 78 79
	/**
	 * Did we wake up the DecoderThread recently?  This avoids
	 * duplicate wakeup calls.
	 */
80
	bool decoder_woken = false;
81

82 83 84
	/**
	 * is the player paused?
	 */
85
	bool paused = false;
86

87 88 89
	/**
	 * is there a new song in pc.next_song?
	 */
90
	bool queued = true;
91

92 93 94 95 96 97
	/**
	 * 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.
	 */
98
	bool output_open = false;
99

100
	/**
101
	 * Is cross-fading to the next song enabled?
102
	 */
103
	enum class CrossFadeState : uint8_t {
104 105 106 107
		/**
		 * The initial state: we don't know yet if we will
		 * cross-fade; it will be determined soon.
		 */
108
		UNKNOWN,
109 110 111 112 113

		/**
		 * Cross-fading is disabled for the transition to the
		 * next song.
		 */
114
		DISABLED,
115 116 117 118 119 120

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

123 124 125 126
		/**
		 * Currently cross-fading to the next song.
		 */
		ACTIVE,
127
	} xfade_state = CrossFadeState::UNKNOWN;
128 129 130 131

	/**
	 * The number of chunks used for crossfading.
	 */
132
	unsigned cross_fade_chunks = 0;
133

134 135 136
	/**
	 * The current audio format for the audio outputs.
	 */
137
	AudioFormat play_audio_format = AudioFormat::Undefined();
138 139 140 141

	/**
	 * The time stamp of the chunk most recently sent to the
	 * output thread.  This attribute is only used if
142
	 * MultipleOutputs::GetElapsedTime() didn't return a usable
143
	 * value; the output thread can estimate the elapsed time more
144
	 * precisely.
145
	 */
146
	SongTime elapsed_time = SongTime::zero();
147

148 149 150 151 152 153 154 155 156 157
	/**
	 * 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;

158
public:
159
	Player(PlayerControl &_pc, DecoderControl &_dc,
160
	       MusicBuffer &_buffer) noexcept
161
		:pc(_pc), dc(_dc), buffer(_buffer) {}
162

163
private:
164 165 166 167
	/**
	 * Reset cross-fading to the initial state.  A check to
	 * re-enable it at an appropriate time will be scheduled.
	 */
168
	void ResetCrossFade() noexcept {
169 170 171
		xfade_state = CrossFadeState::UNKNOWN;
	}

172
	void ClearAndDeletePipe() noexcept {
173 174 175 176
		pipe->Clear(buffer);
		delete pipe;
	}

177
	void ClearAndReplacePipe(MusicPipe *_pipe) noexcept {
178
		ResetCrossFade();
179 180 181 182
		ClearAndDeletePipe();
		pipe = _pipe;
	}

183
	void ReplacePipe(MusicPipe *_pipe) noexcept {
184
		ResetCrossFade();
185 186 187 188 189 190 191
		delete pipe;
		pipe = _pipe;
	}

	/**
	 * Start the decoder.
	 *
192
	 * Caller must lock the mutex.
193
	 */
194
	void StartDecoder(MusicPipe &pipe) noexcept;
195 196 197

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

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
212
	 * Caller must lock the mutex.
213
	 */
214
	void StopDecoder() noexcept;
215 216 217 218 219 220 221 222

	/**
	 * 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
223
	bool IsDecoderAtCurrentSong() const noexcept {
224 225 226 227 228 229 230 231 232 233 234
		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
235
	bool IsDecoderAtNextSong() const noexcept {
236 237 238
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

239 240 241 242 243 244 245 246 247 248
	/**
	 * 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;

249
	/**
250
	 * This is the handler for the #PlayerCommand::SEEK command.
251
	 *
252
	 * Caller must lock the mutex.
253 254
	 *
	 * @return false if the decoder has failed
255
	 */
256
	bool SeekDecoder() noexcept;
257

258 259 260 261 262
	void CancelPendingSeek() noexcept {
		pending_seek = SongTime::zero();
		pc.seeking = false;
	}

263 264 265 266 267 268
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
269
	bool ForwardDecoderError() noexcept;
270

271
	/**
272 273 274 275 276 277 278 279 280
	 * 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().
281
	 *
282
	 * Caller must lock the mutex.
283
	 */
284
	void ActivateDecoder() noexcept;
285 286

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

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

304 305
	unsigned UnlockCheckOutputs() noexcept {
		const ScopeUnlock unlock(pc.mutex);
306
		return pc.outputs.CheckPipe();
307 308
	}

309 310
	/**
	 * Player lock must be held before calling.
311 312
	 *
	 * @return false to stop playback
313
	 */
314
	bool ProcessCommand() noexcept;
315 316 317 318 319 320

	/**
	 * 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.
	 *
321
	 * Caller must lock the mutex.
322
	 */
323
	void SongBorder() noexcept;
324

325
public:
326 327 328 329 330
	/*
	 * 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.
	 */
331
	void Run() noexcept;
332 333
};

334
void
335
Player::StartDecoder(MusicPipe &_pipe) noexcept
336
{
337
	assert(queued || pc.command == PlayerCommand::SEEK);
338
	assert(pc.next_song != nullptr);
339

340 341
	/* copy ReplayGain parameters to the decoder */
	dc.replay_gain_mode = pc.replay_gain_mode;
342

343
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
344

345
	dc.Start(std::make_unique<DetachedSong>(*pc.next_song),
346
		 start_time, pc.next_song->GetEndTime(),
347
		 buffer, _pipe);
348 349
}

350
void
351
Player::StopDecoder() noexcept
352
{
353 354
	const PlayerControl::ScopeOccupied occupied(pc);

355
	dc.Stop();
356

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

360
		dc.pipe->Clear(buffer);
361

362
		if (dc.pipe != pipe)
363
			delete dc.pipe;
364

365
		dc.pipe = nullptr;
366 367 368 369 370

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

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

	return true;
}

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

393
	queued = false;
394

395
	pc.ClearTaggedSong();
396

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

399
	elapsed_time = pc.seek_time;
400

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

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

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

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

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

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

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

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

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

453
		output_open = false;
454

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

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

461 462
		idle_add(IDLE_PLAYER);

463 464
		return false;
	}
465 466 467 468

	output_open = true;
	paused = false;

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

	idle_add(IDLE_PLAYER);

	return true;
474 475
}

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

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

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

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

499 500
		idle_add(IDLE_PLAYER);

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

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

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

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

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

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

		return true;
	}
}

538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
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;
}

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

569 570
	CancelPendingSeek();

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

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

580
		StopDecoder();
581

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

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

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

		assert(xfade_state == CrossFadeState::UNKNOWN);

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

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

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

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

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

625
	pc.CommandFinished();
626

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

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

	return true;
633 634
}

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

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

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

653
		pc.CommandFinished();
654 655
		break;

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

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

664 665
		if (dc.IsIdle())
			StartDecoder(*new MusicPipe());
666

667 668
		break;

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

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

684
		pc.CommandFinished();
685 686
		break;

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

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

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

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

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

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

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

	return true;
722 723
}

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

733
	song.SetTag(new_tag);
734

735
	pc.LockSetTaggedSong(song);
736

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

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

746
/**
747
 * Plays a #MusicChunk object (after applying software volume).  If
748 749
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
750 751
 *
 * Player lock is not held.
752
 */
753
static void
754
play_chunk(PlayerControl &pc,
755
	   DetachedSong &song, MusicChunk *chunk,
756
	   MusicBuffer &buffer,
757
	   const AudioFormat format)
758
{
759
	assert(chunk->CheckFormat(format));
760

761
	if (chunk->tag != nullptr)
762
		update_song_tag(pc, song, *chunk->tag);
763

764
	if (chunk->IsEmpty()) {
765
		buffer.Return(chunk);
766
		return;
767
	}
768

769
	{
770
		const std::lock_guard<Mutex> lock(pc.mutex);
771 772
		pc.bit_rate = chunk->bit_rate;
	}
773

774 775
	/* send the chunk to the audio outputs */

776
	pc.outputs.Play(chunk);
777
	pc.total_play_time += (double)chunk->length /
778
		format.GetTimeToSize();
779 780
}

781
inline bool
782
Player::PlayNextChunk() noexcept
783
{
784
	if (!pc.LockWaitOutputConsumed(64))
785 786
		/* the output pipe is still large enough, don't send
		   another chunk */
787 788
		return true;

789 790 791 792 793 794 795 796 797 798 799
	/* 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;
	}

800
	MusicChunk *chunk = nullptr;
801
	if (xfade_state == CrossFadeState::ACTIVE) {
802 803
		/* perform cross fade */

804 805 806 807
		assert(IsDecoderAtNextSong());

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

809
		MusicChunk *other_chunk = dc.pipe->Shift();
810
		if (other_chunk != nullptr) {
811
			chunk = pipe->Shift();
812 813
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
814

815 816 817
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
818 819
			cross_fade_tag = Tag::Merge(std::move(cross_fade_tag),
						    std::move(other_chunk->tag));
820

821
			if (pc.cross_fade.mixramp_delay <= 0) {
822
				chunk->mix_ratio = ((float)cross_fade_position)
823
					     / cross_fade_chunks;
824
			} else {
825
				chunk->mix_ratio = -1;
826
			}
827

828
			if (other_chunk->IsEmpty()) {
829
				/* the "other" chunk was a MusicChunk
830 831 832 833 834 835
				   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 */
836
				buffer.Return(other_chunk);
837
				other_chunk = nullptr;
838
			}
839

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

844
			const std::lock_guard<Mutex> lock(pc.mutex);
845

846
			if (dc.IsIdle()) {
847
				/* the decoder isn't running, abort
848
				   cross fading */
849
				xfade_state = CrossFadeState::DISABLED;
850
			} else {
851
				/* wait for the decoder */
852 853
				dc.Signal();
				dc.WaitForDecoder();
854

855 856 857 858 859
				return true;
			}
		}
	}

860
	if (chunk == nullptr)
861
		chunk = pipe->Shift();
862

863
	assert(chunk != nullptr);
864

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

867
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
868 869
		chunk->tag = Tag::Merge(std::move(chunk->tag),
					std::move(cross_fade_tag));
870
		cross_fade_tag = nullptr;
871 872
	}

873 874
	/* play the current chunk */

875 876
	try {
		play_chunk(pc, *song, chunk, buffer, play_audio_format);
877 878
	} catch (...) {
		LogError(std::current_exception());
879

880
		buffer.Return(chunk);
881 882 883

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

886
		pc.LockSetOutputError(std::current_exception());
887

888 889
		idle_add(IDLE_PLAYER);

890
		return false;
891
	}
892

893
	const std::lock_guard<Mutex> lock(pc.mutex);
894

895 896
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
897
	   larger block at a time */
898 899
	if (!dc.IsIdle() &&
	    dc.pipe->GetSize() <= (pc.buffered_before_play +
900 901 902 903 904 905 906
				   buffer.GetSize() * 3) / 4) {
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
907 908 909 910

	return true;
}

911
inline void
912
Player::SongBorder() noexcept
913
{
914 915
	{
		const ScopeUnlock unlock(pc.mutex);
916

917
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
918

919
		ReplacePipe(dc.pipe);
920

921
		pc.outputs.SongBorder();
922
	}
923

924 925 926
	ActivateDecoder();

	const bool border_pause = pc.ApplyBorderPause();
927
	if (border_pause) {
928
		paused = true;
929
		idle_add(IDLE_PLAYER);
930
	}
931 932
}

933
inline void
934
Player::Run() noexcept
935
{
936
	pipe = new MusicPipe();
937

938
	const std::lock_guard<Mutex> lock(pc.mutex);
939 940

	StartDecoder(*pipe);
941
	ActivateDecoder();
942

943
	pc.state = PlayerState::PLAY;
944

945
	pc.CommandFinished();
946

947
	while (true) {
948
		if (!ProcessCommand())
949 950
			break;

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

956
			if (pipe->GetSize() < pc.buffered_before_play &&
957
			    !dc.IsIdle()) {
958
				/* not enough decoded buffer space yet */
959

960
				dc.WaitForDecoder();
961 962 963
				continue;
			} else {
				/* buffering is complete */
964
				buffering = false;
965 966 967
			}
		}

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

971
			if (!CheckDecoderStartup())
972
				break;
973

974
			continue;
975 976
		}

977
		if (dc.IsIdle() && queued && dc.pipe == pipe) {
978 979
			/* the decoder has finished the current song;
			   make it decode the next song */
980

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

983
			StartDecoder(*new MusicPipe());
984
		}
985

986 987
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
988
		    !pc.border_pause &&
989
		    IsDecoderAtNextSong() &&
990
		    xfade_state == CrossFadeState::UNKNOWN &&
991
		    !dc.IsStarting()) {
992 993 994
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
995
			cross_fade_chunks =
996
				pc.cross_fade.Calculate(dc.total_time,
997 998 999 1000 1001 1002 1003 1004
							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);
1005
			if (cross_fade_chunks > 0)
1006
				xfade_state = CrossFadeState::ENABLED;
1007
			else
1008 1009
				/* cross fading is disabled or the
				   next song is too short */
1010
				xfade_state = CrossFadeState::DISABLED;
1011 1012
		}

1013
		if (paused) {
1014
			if (pc.command == PlayerCommand::NONE)
1015
				pc.Wait();
1016
		} else if (!pipe->IsEmpty()) {
1017 1018
			/* at least one music chunk is ready - send it
			   to the audio output */
1019

1020
			const ScopeUnlock unlock(pc.mutex);
1021
			PlayNextChunk();
1022
		} else if (UnlockCheckOutputs() > 0) {
1023 1024 1025 1026
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1027 1028 1029
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
1030
			// TODO: eliminate this kludge
1031
			dc.Signal();
1032

1033
			dc.WaitForDecoder();
1034
		} else if (IsDecoderAtNextSong()) {
1035 1036
			/* at the beginning of a new song */

1037
			SongBorder();
1038
		} else if (dc.IsIdle()) {
1039 1040 1041
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1042
			if (pipe->IsEmpty()) {
1043 1044
				/* wait for the hardware to finish
				   playback */
1045
				const ScopeUnlock unlock(pc.mutex);
1046
				pc.outputs.Drain();
1047
				break;
1048
			}
1049
		} else if (output_open) {
1050
			/* the decoder is too busy and hasn't provided
1051 1052
			   new PCM data in time: wait for the
			   decoder */
1053

1054 1055 1056 1057 1058 1059
			/* 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();

1060
			dc.WaitForDecoder();
1061 1062 1063
		}
	}

1064
	CancelPendingSeek();
1065
	StopDecoder();
1066

1067
	ClearAndDeletePipe();
1068

1069
	cross_fade_tag.reset();
1070

1071
	if (song != nullptr) {
1072
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
1073
		song.reset();
1074
	}
1075

1076 1077
	pc.ClearTaggedSong();

1078
	if (queued) {
1079
		assert(pc.next_song != nullptr);
1080
		pc.next_song.reset();
1081 1082
	}

1083
	pc.state = PlayerState::STOP;
1084 1085
}

1086
static void
1087
do_play(PlayerControl &pc, DecoderControl &dc,
1088
	MusicBuffer &buffer) noexcept
1089
{
1090
	Player player(pc, dc, buffer);
1091 1092 1093
	player.Run();
}

1094
void
1095
PlayerControl::RunThread() noexcept
1096
{
1097 1098
	SetThreadName("player");

1099 1100 1101
	DecoderControl dc(mutex, cond,
			  configured_audio_format,
			  replay_gain_config);
1102
	decoder_thread_start(dc);
1103

1104
	MusicBuffer buffer(buffer_chunks);
1105

1106
	const std::lock_guard<Mutex> lock(mutex);
1107

1108
	while (1) {
1109
		switch (command) {
1110 1111
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1112
			assert(next_song != nullptr);
1113

1114 1115 1116 1117 1118 1119
			{
				const ScopeUnlock unlock(mutex);
				do_play(*this, dc, buffer);
				listener.OnPlayerSync();
			}

1120 1121
			break;

1122
		case PlayerCommand::STOP:
1123 1124 1125 1126
			{
				const ScopeUnlock unlock(mutex);
				outputs.Cancel();
			}
1127

1128 1129
			/* fall through */

1130
		case PlayerCommand::PAUSE:
1131
			next_song.reset();
1132

1133
			CommandFinished();
1134 1135
			break;

1136
		case PlayerCommand::CLOSE_AUDIO:
1137 1138 1139 1140
			{
				const ScopeUnlock unlock(mutex);
				outputs.Release();
			}
1141

1142
			CommandFinished();
1143

1144
			assert(buffer.IsEmptyUnsafe());
1145

1146 1147
			break;

1148
		case PlayerCommand::UPDATE_AUDIO:
1149 1150 1151 1152 1153
			{
				const ScopeUnlock unlock(mutex);
				outputs.EnableDisable();
			}

1154
			CommandFinished();
1155 1156
			break;

1157
		case PlayerCommand::EXIT:
1158 1159 1160 1161 1162
			{
				const ScopeUnlock unlock(mutex);
				dc.Quit();
				outputs.Close();
			}
1163

1164
			CommandFinished();
1165
			return;
Max Kellermann's avatar
Max Kellermann committed
1166

1167
		case PlayerCommand::CANCEL:
1168
			next_song.reset();
1169

1170
			CommandFinished();
1171 1172
			break;

1173
		case PlayerCommand::REFRESH:
1174
			/* no-op when not playing */
1175
			CommandFinished();
1176 1177
			break;

1178
		case PlayerCommand::NONE:
1179
			Wait();
1180 1181 1182 1183 1184
			break;
		}
	}
}

1185
void
1186
StartPlayerThread(PlayerControl &pc)
1187
{
1188 1189
	assert(!pc.thread.IsDefined());

1190
	pc.thread.Start();
1191
}