Thread.cxx 28.1 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2019 The Music Player Daemon Project
3
 * http://www.musicpd.org
4 5 6 7 8 9 10 11 12 13
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
14 15 16 17
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 19
 */

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

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

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

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

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

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

66
class Player {
67
	PlayerControl &pc;
68

69
	DecoderControl &dc;
70

71 72
	MusicBuffer &buffer;

73
	std::shared_ptr<MusicPipe> pipe;
74

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

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

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

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

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

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

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

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

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

131 132 133 134 135 136
	/**
	 * Was any audio output opened successfully?  It might have
	 * failed meanwhile, but was not explicitly closed by the
	 * player thread.  When this flag is unset, some output
	 * methods must not be called.
	 */
137
	bool output_open = false;
138

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

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

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

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

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

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

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

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

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

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

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

	/**
	 * Start the decoder.
	 *
223
	 * Caller must lock the mutex.
224
	 */
225 226
	void StartDecoder(std::unique_lock<Mutex> &lock,
			  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(std::unique_lock<Mutex> &lock) 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(std::unique_lock<Mutex> &lock) 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
	/**
	 * Invoke DecoderControl::Seek() and update our state or
	 * handle errors.
	 *
	 * Caller must lock the mutex.
	 *
	 * @return false if the decoder has failed
	 */
279 280
	bool SeekDecoder(std::unique_lock<Mutex> &lock,
			 SongTime seek_time) noexcept;
281

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

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

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

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

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

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

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

342 343
	/**
	 * Player lock must be held before calling.
344 345
	 *
	 * @return false to stop playback
346
	 */
347
	bool ProcessCommand(std::unique_lock<Mutex> &lock) noexcept;
348 349 350 351 352 353

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

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

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

374 375
	/* copy ReplayGain parameters to the decoder */
	dc.replay_gain_mode = pc.replay_gain_mode;
376

377
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
378

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

384
void
385
Player::StopDecoder(std::unique_lock<Mutex> &lock) noexcept
386
{
387 388
	const PlayerControl::ScopeOccupied occupied(pc);

389
	dc.Stop(lock);
390

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

394
		dc.pipe->Clear();
395
		dc.pipe.reset();
396 397 398 399 400

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

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

	return true;
}

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

423
	queued = false;
424

425
	pc.ClearTaggedSong();
426

427
	song = std::exchange(pc.next_song, nullptr);
428

429
	elapsed_time = pc.seek_time;
430

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

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

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

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

461 462
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
463

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

467
	return SignedSongTime(SongTime(decoder_duration) - start_time);
468 469
}

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

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

483
		output_open = false;
484

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

489
		pc.SetOutputError(std::current_exception());
490

491 492
		idle_add(IDLE_PLAYER);

493 494
		return false;
	}
495 496 497 498

	output_open = true;
	paused = false;

499
	pc.state = PlayerState::PLAY;
500 501 502 503

	idle_add(IDLE_PLAYER);

	return true;
504 505
}

506 507
inline bool
Player::CheckDecoderStartup(std::unique_lock<Mutex> &lock) noexcept
508
{
509
	assert(decoder_starting);
510

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

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

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

529 530 531 532 533 534
		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);

535 536
		idle_add(IDLE_PLAYER);

537 538 539
		if (pending_seek > SongTime::zero()) {
			assert(pc.seeking);

540
			bool success = SeekDecoder(lock, pending_seek);
541 542 543 544 545
			pc.seeking = false;
			pc.ClientSignal();
			if (!success)
				return false;

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

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

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

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

		return true;
	}
}

574
bool
575
Player::SeekDecoder(std::unique_lock<Mutex> &lock, SongTime seek_time) noexcept
576 577 578 579 580 581 582 583 584 585 586 587 588
{
	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);

589
		dc.Seek(lock, song->GetStartTime() + seek_time);
590 591 592 593 594 595 596 597 598 599
	} catch (...) {
		/* decoder failure */
		pc.SetError(PlayerError::DECODER, std::current_exception());
		return false;
	}

	elapsed_time = seek_time;
	return true;
}

600
inline bool
601
Player::SeekDecoder(std::unique_lock<Mutex> &lock) noexcept
602
{
603
	assert(pc.next_song != nullptr);
604

605 606 607 608 609 610 611 612 613 614 615 616 617
	if (pc.seek_time > SongTime::zero() && // TODO: allow this only if the song duration is known
	    dc.IsUnseekableCurrentSong(*pc.next_song)) {
		/* seeking into the current song; but we already know
		   it's not seekable, so let's fail early */
		/* note the seek_time>0 check: if seeking to the
		   beginning, we can simply restart the decoder */
		pc.next_song.reset();
		pc.SetError(PlayerError::DECODER,
			    std::make_exception_ptr(std::runtime_error("Not seekable")));
		pc.CommandFinished();
		return true;
	}

618 619
	CancelPendingSeek();

620 621 622 623
	{
		const ScopeUnlock unlock(pc.mutex);
		pc.outputs.Cancel();
	}
624

625
	idle_add(IDLE_PLAYER);
626

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

631
		StopDecoder(lock);
632

633 634
		/* clear music chunks which might still reside in the
		   pipe */
635
		pipe->Clear();
636

637
		/* re-start the decoder */
638
		StartDecoder(lock, pipe);
639
		ActivateDecoder();
640

641 642 643 644 645 646
		pc.seeking = true;
		pc.CommandFinished();

		assert(xfade_state == CrossFadeState::UNKNOWN);

		return true;
647
	} else {
648
		if (!IsDecoderAtCurrentSong()) {
649 650
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
651
			ReplacePipe(dc.pipe);
652 653
		}

654
		pc.next_song.reset();
655
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
656

657 658 659 660
		if (decoder_starting) {
			/* wait for the decoder to complete
			   initialization; postpone the SEEK
			   command */
661

662 663
			pending_seek = pc.seek_time;
			pc.seeking = true;
664
			pc.CommandFinished();
665 666 667 668
			return true;
		} else {
			/* send the SEEK command */

669
			if (!SeekDecoder(lock, pc.seek_time)) {
670 671 672
				pc.CommandFinished();
				return false;
			}
673
		}
674
	}
675

676
	pc.CommandFinished();
677

678
	assert(xfade_state == CrossFadeState::UNKNOWN);
679

680
	/* re-fill the buffer after seeking */
681
	buffering = true;
682 683

	return true;
684 685
}

686
inline bool
687
Player::ProcessCommand(std::unique_lock<Mutex> &lock) noexcept
688
{
689
	switch (pc.command) {
690
	case PlayerCommand::NONE:
691 692
		break;

693 694 695
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
696
		return false;
697

698
	case PlayerCommand::UPDATE_AUDIO:
699 700 701 702 703
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

704
		pc.CommandFinished();
705 706
		break;

707
	case PlayerCommand::QUEUE:
708
		assert(pc.next_song != nullptr);
709 710
		assert(!queued);
		assert(!IsDecoderAtNextSong());
711

712
		queued = true;
713
		pc.CommandFinished();
714

715
		if (dc.IsIdle())
716
			StartDecoder(lock, std::make_shared<MusicPipe>());
717

718 719
		break;

720
	case PlayerCommand::PAUSE:
721 722
		paused = !paused;
		if (paused) {
723
			pc.state = PlayerState::PAUSE;
724 725 726

			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.Pause();
727
		} else if (!play_audio_format.IsDefined()) {
728 729
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
730
			pc.state = PlayerState::PLAY;
731
		} else {
732
			OpenOutput();
733
		}
734

735
		pc.CommandFinished();
736 737
		break;

738
	case PlayerCommand::SEEK:
739
		return SeekDecoder(lock);
740

741
	case PlayerCommand::CANCEL:
742
		if (pc.next_song == nullptr)
743
			/* the cancel request arrived too late, we're
744 745
			   already playing the queued song...  stop
			   everything now */
746
			return false;
747

748
		if (IsDecoderAtNextSong())
749 750
			/* the decoder is already decoding the song -
			   stop it and reset the position */
751
			StopDecoder(lock);
752

753
		pc.next_song.reset();
754
		queued = false;
755
		pc.CommandFinished();
756
		break;
757

758
	case PlayerCommand::REFRESH:
759
		if (output_open && !paused) {
760
			const ScopeUnlock unlock(pc.mutex);
761
			pc.outputs.CheckPipe();
762
		}
763

764 765
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
766
			: elapsed_time;
767

768
		pc.CommandFinished();
769
		break;
770
	}
771 772

	return true;
773 774
}

775 776 777
inline void
PlayerControl::LockUpdateSongTag(DetachedSong &song,
				 const Tag &new_tag) noexcept
778
{
779
	if (song.IsFile())
780 781 782 783
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

784
	song.SetTag(new_tag);
785

786
	LockSetTaggedSong(song);
787

788 789
	/* the main thread will update the playlist version when he
	   receives this event */
790
	listener.OnPlayerTagModified();
791 792 793 794 795 796

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

797 798 799
inline void
PlayerControl::PlayChunk(DetachedSong &song, MusicChunkPtr chunk,
			 const AudioFormat &format)
800
{
801
	assert(chunk->CheckFormat(format));
802

803
	if (chunk->tag != nullptr)
804
		LockUpdateSongTag(song, *chunk->tag);
805

806
	if (chunk->IsEmpty())
807
		return;
808

809
	{
810 811
		const std::lock_guard<Mutex> lock(mutex);
		bit_rate = chunk->bit_rate;
812
	}
813

814 815
	/* send the chunk to the audio outputs */

816 817
	const double chunk_length(chunk->length);

818
	outputs.Play(std::move(chunk));
819
	total_play_time += format.SizeToTime<decltype(total_play_time)>(chunk_length);
820 821
}

822
inline bool
823
Player::PlayNextChunk() noexcept
824
{
825
	if (!pc.LockWaitOutputConsumed(64))
826 827
		/* the output pipe is still large enough, don't send
		   another chunk */
828 829
		return true;

830 831 832 833 834 835 836 837 838 839 840
	/* 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;
	}

841
	MusicChunkPtr chunk;
842
	if (xfade_state == CrossFadeState::ACTIVE) {
843 844
		/* perform cross fade */

845 846 847 848
		assert(IsDecoderAtNextSong());

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

850
		auto other_chunk = dc.pipe->Shift();
851
		if (other_chunk != nullptr) {
852
			chunk = pipe->Shift();
853 854
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
855

856 857 858
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
859 860
			cross_fade_tag = Tag::Merge(std::move(cross_fade_tag),
						    std::move(other_chunk->tag));
861

862
			if (pc.cross_fade.mixramp_delay <= FloatDuration::zero()) {
863
				chunk->mix_ratio = ((float)cross_fade_position)
864
					     / cross_fade_chunks;
865
			} else {
866
				chunk->mix_ratio = -1;
867
			}
868

869
			if (other_chunk->IsEmpty()) {
870
				/* the "other" chunk was a MusicChunk
871 872 873 874 875 876
				   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 */
877
				other_chunk.reset();
878
			}
879

880
			chunk->other = std::move(other_chunk);
881
		} else {
882
			/* there are not enough decoded chunks yet */
883

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

886
			if (dc.IsIdle()) {
887
				/* the decoder isn't running, abort
888
				   cross fading */
889
				xfade_state = CrossFadeState::DISABLED;
890
			} else {
891
				/* wait for the decoder */
892
				dc.Signal();
893
				dc.WaitForDecoder(lock);
894

895 896 897 898 899
				return true;
			}
		}
	}

900
	if (chunk == nullptr)
901
		chunk = pipe->Shift();
902

903
	assert(chunk != nullptr);
904

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

907
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
908 909
		chunk->tag = Tag::Merge(std::move(chunk->tag),
					std::move(cross_fade_tag));
910
		cross_fade_tag = nullptr;
911 912
	}

913 914
	/* play the current chunk */

915
	try {
916 917
		pc.PlayChunk(*song, std::move(chunk),
			     play_audio_format);
918 919
	} catch (...) {
		LogError(std::current_exception());
920

921
		chunk.reset();
922 923 924

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

927
		pc.LockSetOutputError(std::current_exception());
928

929 930
		idle_add(IDLE_PLAYER);

931
		return false;
932
	}
933

934
	const std::lock_guard<Mutex> lock(pc.mutex);
935

936 937
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
938
	   larger block at a time */
939
	if (!dc.IsIdle() && dc.pipe->GetSize() <= decoder_wakeup_threshold) {
940 941 942 943 944 945
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
946 947 948 949

	return true;
}

950
inline void
951
Player::SongBorder() noexcept
952
{
953 954
	{
		const ScopeUnlock unlock(pc.mutex);
955

956
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
957

958
		ReplacePipe(dc.pipe);
959

960
		pc.outputs.SongBorder();
961
	}
962

963 964 965
	ActivateDecoder();

	const bool border_pause = pc.ApplyBorderPause();
966
	if (border_pause) {
967
		paused = true;
968
		pc.listener.OnBorderPause();
969
		pc.outputs.Pause();
970
		idle_add(IDLE_PLAYER);
971
	}
972 973
}

974
inline void
975
Player::Run() noexcept
976
{
977
	pipe = std::make_shared<MusicPipe>();
978

979
	std::unique_lock<Mutex> lock(pc.mutex);
980

981
	StartDecoder(lock, pipe);
982
	ActivateDecoder();
983

984
	pc.state = PlayerState::PLAY;
985

986
	pc.CommandFinished();
987

988
	while (ProcessCommand(lock)) {
989 990 991
		if (decoder_starting) {
			/* wait until the decoder is initialized completely */

992
			if (!CheckDecoderStartup(lock))
993 994 995 996 997
				break;

			continue;
		}

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

1003
			if (pipe->GetSize() < buffer_before_play &&
1004
			    !dc.IsIdle() && !buffer.IsFull()) {
1005
				/* not enough decoded buffer space yet */
1006

1007
				dc.WaitForDecoder(lock);
1008 1009 1010
				continue;
			} else {
				/* buffering is complete */
1011
				buffering = false;
1012 1013 1014
			}
		}

1015
		if (dc.IsIdle() && queued && IsDecoderAtCurrentSong()) {
1016 1017
			/* the decoder has finished the current song;
			   make it decode the next song */
1018

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

1021
			StartDecoder(lock, std::make_shared<MusicPipe>());
1022
		}
1023

1024 1025
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
1026
		    !pc.border_pause &&
1027
		    IsDecoderAtNextSong() &&
1028
		    xfade_state == CrossFadeState::UNKNOWN &&
1029
		    !dc.IsStarting()) {
1030 1031 1032
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
1033
			cross_fade_chunks =
1034
				pc.cross_fade.Calculate(dc.total_time,
1035 1036 1037 1038 1039 1040 1041
							dc.replay_gain_db,
							dc.replay_gain_prev_db,
							dc.GetMixRampStart(),
							dc.GetMixRampPreviousEnd(),
							dc.out_audio_format,
							play_audio_format,
							buffer.GetSize() -
1042
							buffer_before_play);
1043
			if (cross_fade_chunks > 0)
1044
				xfade_state = CrossFadeState::ENABLED;
1045
			else
1046 1047
				/* cross fading is disabled or the
				   next song is too short */
1048
				xfade_state = CrossFadeState::DISABLED;
1049 1050
		}

1051
		if (paused) {
1052
			if (pc.command == PlayerCommand::NONE)
1053
				pc.Wait(lock);
1054
		} else if (!pipe->IsEmpty()) {
1055 1056
			/* at least one music chunk is ready - send it
			   to the audio output */
1057

1058
			const ScopeUnlock unlock(pc.mutex);
1059
			PlayNextChunk();
1060
		} else if (UnlockCheckOutputs() > 0) {
1061 1062 1063 1064
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1065 1066 1067
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
1068
			// TODO: eliminate this kludge
1069
			dc.Signal();
1070

1071
			dc.WaitForDecoder(lock);
1072
		} else if (IsDecoderAtNextSong()) {
1073 1074
			/* at the beginning of a new song */

1075
			SongBorder();
1076
		} else if (dc.IsIdle()) {
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086
			if (queued)
				/* the decoder has just stopped,
				   between the two IsIdle() checks,
				   probably while UnlockCheckOutputs()
				   left the mutex unlocked; to restart
				   the decoder instead of stopping
				   playback completely, let's re-enter
				   this loop */
				continue;

1087 1088 1089
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1090
			if (pipe->IsEmpty()) {
1091 1092
				/* wait for the hardware to finish
				   playback */
1093
				const ScopeUnlock unlock(pc.mutex);
1094
				pc.outputs.Drain();
1095
				break;
1096
			}
1097
		} else if (output_open) {
1098
			/* the decoder is too busy and hasn't provided
1099 1100
			   new PCM data in time: wait for the
			   decoder */
1101

1102 1103 1104 1105 1106 1107
			/* 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();

1108
			dc.WaitForDecoder(lock);
1109 1110 1111
		}
	}

1112
	CancelPendingSeek();
1113
	StopDecoder(lock);
1114

1115
	pipe.reset();
1116

1117
	cross_fade_tag.reset();
1118

1119
	if (song != nullptr) {
1120
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
1121
		song.reset();
1122
	}
1123

1124 1125
	pc.ClearTaggedSong();

1126
	if (queued) {
1127
		assert(pc.next_song != nullptr);
1128
		pc.next_song.reset();
1129 1130
	}

1131
	pc.state = PlayerState::STOP;
1132 1133
}

1134
static void
1135
do_play(PlayerControl &pc, DecoderControl &dc,
1136
	MusicBuffer &buffer) noexcept
1137
{
1138
	Player player(pc, dc, buffer);
1139 1140 1141
	player.Run();
}

1142
void
1143
PlayerControl::RunThread() noexcept
1144
try {
1145 1146
	SetThreadName("player");

1147
	DecoderControl dc(mutex, cond,
1148
			  input_cache,
1149 1150
			  configured_audio_format,
			  replay_gain_config);
1151
	dc.StartThread();
1152

1153
	MusicBuffer buffer(buffer_chunks);
1154

1155
	std::unique_lock<Mutex> lock(mutex);
1156

1157
	while (1) {
1158
		switch (command) {
1159 1160
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1161
			assert(next_song != nullptr);
1162

1163 1164 1165 1166 1167 1168
			{
				const ScopeUnlock unlock(mutex);
				do_play(*this, dc, buffer);
				listener.OnPlayerSync();
			}

1169 1170
			break;

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

1177 1178
			/* fall through */

1179
		case PlayerCommand::PAUSE:
1180
			next_song.reset();
1181

1182
			CommandFinished();
1183 1184
			break;

1185
		case PlayerCommand::CLOSE_AUDIO:
1186 1187 1188 1189
			{
				const ScopeUnlock unlock(mutex);
				outputs.Release();
			}
1190

1191
			CommandFinished();
1192

1193
			assert(buffer.IsEmptyUnsafe());
1194

1195 1196
			break;

1197
		case PlayerCommand::UPDATE_AUDIO:
1198 1199 1200 1201 1202
			{
				const ScopeUnlock unlock(mutex);
				outputs.EnableDisable();
			}

1203
			CommandFinished();
1204 1205
			break;

1206
		case PlayerCommand::EXIT:
1207 1208 1209 1210 1211
			{
				const ScopeUnlock unlock(mutex);
				dc.Quit();
				outputs.Close();
			}
1212

1213
			CommandFinished();
1214
			return;
Max Kellermann's avatar
Max Kellermann committed
1215

1216
		case PlayerCommand::CANCEL:
1217
			next_song.reset();
1218

1219
			CommandFinished();
1220 1221
			break;

1222
		case PlayerCommand::REFRESH:
1223
			/* no-op when not playing */
1224
			CommandFinished();
1225 1226
			break;

1227
		case PlayerCommand::NONE:
1228
			Wait(lock);
1229 1230 1231
			break;
		}
	}
1232 1233 1234 1235 1236 1237 1238 1239
} 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? */
1240
}