Thread.cxx 28.4 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 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/Compiler.h"
50
#include "util/Domain.hxx"
51
#include "thread/Name.hxx"
52
#include "Log.hxx"
53

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

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

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

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

67
class Player {
68
	PlayerControl &pc;
69

70
	DecoderControl &dc;
71

72 73
	MusicBuffer &buffer;

74
	std::shared_ptr<MusicPipe> pipe;
75

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
245
	 * Caller must lock the mutex.
246
	 */
247
	void StopDecoder(std::unique_lock<Mutex> &lock) noexcept;
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.
	 */
255
	[[nodiscard]] gcc_pure
256
	bool IsDecoderAtCurrentSong() const noexcept {
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.
	 */
267
	[[nodiscard]] gcc_pure
268
	bool IsDecoderAtNextSong() const noexcept {
269 270 271
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

272 273 274 275 276 277 278 279
	/**
	 * Invoke DecoderControl::Seek() and update our state or
	 * handle errors.
	 *
	 * Caller must lock the mutex.
	 *
	 * @return false if the decoder has failed
	 */
280 281
	bool SeekDecoder(std::unique_lock<Mutex> &lock,
			 SongTime seek_time) noexcept;
282

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

390
	dc.Stop(lock);
391

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

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

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

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

	return true;
}

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

424
	queued = false;
425

426
	pc.ClearTaggedSong();
427

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

430
	elapsed_time = pc.seek_time;
431

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

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

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

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

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

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

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

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

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

484
		output_open = false;
485

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

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

492 493
		idle_add(IDLE_PLAYER);

494 495
		return false;
	}
496 497 498 499

	output_open = true;
	paused = false;

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

	idle_add(IDLE_PLAYER);

	return true;
505 506
}

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

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

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

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

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

536 537
		idle_add(IDLE_PLAYER);

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

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

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

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

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

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

		return true;
	}
}

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

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

	elapsed_time = seek_time;
	return true;
}

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

606 607 608 609 610 611 612 613 614 615 616 617 618
	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;
	}

619 620
	CancelPendingSeek();

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

626
	idle_add(IDLE_PLAYER);
627

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

632
		StopDecoder(lock);
633

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

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

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

		assert(xfade_state == CrossFadeState::UNKNOWN);

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

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

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

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

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

677
	pc.CommandFinished();
678

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

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

	return true;
685 686
}

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

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

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

705
		pc.CommandFinished();
706 707
		break;

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

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

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

719 720
		break;

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

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

736
		pc.CommandFinished();
737 738
		break;

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

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

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

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

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

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

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

	return true;
774 775
}

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

785
	song.SetTag(new_tag);
786

787
	LockSetTaggedSong(song);
788

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

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

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

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

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

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

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

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

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

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

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

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

846 847 848 849
		assert(IsDecoderAtNextSong());

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

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

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

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

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

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

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

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

896 897 898 899 900
				return true;
			}
		}
	}

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

904
	assert(chunk != nullptr);
905

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

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

914 915
	/* play the current chunk */

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

922
		chunk.reset();
923 924 925

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

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

930 931
		idle_add(IDLE_PLAYER);

932
		return false;
933
	}
934

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

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

	return true;
}

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

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

959
		ReplacePipe(dc.pipe);
960

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

964 965 966
	ActivateDecoder();

	const bool border_pause = pc.ApplyBorderPause();
967
	if (border_pause) {
968
		paused = true;
969
		pc.listener.OnBorderPause();
970 971 972 973 974 975

		/* drain all outputs to guarantee the current song is
		   really being played to the end; without this, the
		   Pause() call would drop all ring buffers */
		pc.outputs.Drain();

976
		pc.outputs.Pause();
977
		idle_add(IDLE_PLAYER);
978
	}
979 980
}

981
inline void
982
Player::Run() noexcept
983
{
984
	pipe = std::make_shared<MusicPipe>();
985

986
	std::unique_lock<Mutex> lock(pc.mutex);
987

988
	StartDecoder(lock, pipe);
989
	ActivateDecoder();
990

991
	pc.state = PlayerState::PLAY;
992

993
	pc.CommandFinished();
994

995
	while (ProcessCommand(lock)) {
996 997 998
		if (decoder_starting) {
			/* wait until the decoder is initialized completely */

999
			if (!CheckDecoderStartup(lock))
1000 1001 1002 1003 1004
				break;

			continue;
		}

1005
		if (buffering) {
1006 1007 1008 1009
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

1010
			if (pipe->GetSize() < buffer_before_play &&
1011
			    !dc.IsIdle() && !buffer.IsFull()) {
1012
				/* not enough decoded buffer space yet */
1013

1014
				dc.WaitForDecoder(lock);
1015 1016 1017
				continue;
			} else {
				/* buffering is complete */
1018
				buffering = false;
1019 1020 1021
			}
		}

1022
		if (dc.IsIdle() && queued && IsDecoderAtCurrentSong()) {
1023 1024
			/* the decoder has finished the current song;
			   make it decode the next song */
1025

1026
			assert(dc.pipe == nullptr || dc.pipe == pipe);
1027

1028
			StartDecoder(lock, std::make_shared<MusicPipe>());
1029
		}
1030

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

1058
		if (paused) {
1059
			if (pc.command == PlayerCommand::NONE)
1060
				pc.Wait(lock);
1061
		} else if (!pipe->IsEmpty()) {
1062 1063
			/* at least one music chunk is ready - send it
			   to the audio output */
1064

1065
			const ScopeUnlock unlock(pc.mutex);
1066
			PlayNextChunk();
1067
		} else if (UnlockCheckOutputs() > 0) {
1068 1069 1070 1071
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1072 1073 1074
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
1075
			// TODO: eliminate this kludge
1076
			dc.Signal();
1077

1078
			dc.WaitForDecoder(lock);
1079
		} else if (IsDecoderAtNextSong()) {
1080 1081
			/* at the beginning of a new song */

1082
			SongBorder();
1083
		} else if (dc.IsIdle()) {
1084 1085 1086 1087 1088 1089 1090 1091 1092 1093
			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;

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

1109 1110 1111 1112 1113 1114
			/* 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();

1115
			dc.WaitForDecoder(lock);
1116 1117 1118
		}
	}

1119
	CancelPendingSeek();
1120
	StopDecoder(lock);
1121

1122
	pipe.reset();
1123

1124
	cross_fade_tag.reset();
1125

1126
	if (song != nullptr) {
1127
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
1128
		song.reset();
1129
	}
1130

1131 1132
	pc.ClearTaggedSong();

1133
	if (queued) {
1134
		assert(pc.next_song != nullptr);
1135
		pc.next_song.reset();
1136 1137
	}

1138
	pc.state = PlayerState::STOP;
1139 1140
}

1141
static void
1142
do_play(PlayerControl &pc, DecoderControl &dc,
1143
	MusicBuffer &buffer) noexcept
1144
{
1145
	Player player(pc, dc, buffer);
1146 1147 1148
	player.Run();
}

1149
void
1150
PlayerControl::RunThread() noexcept
1151
try {
1152 1153
	SetThreadName("player");

1154
	DecoderControl dc(mutex, cond,
1155
			  input_cache,
1156 1157
			  configured_audio_format,
			  replay_gain_config);
1158
	dc.StartThread();
1159

1160
	MusicBuffer buffer(buffer_chunks);
1161

1162
	std::unique_lock<Mutex> lock(mutex);
1163

1164
	while (true) {
1165
		switch (command) {
1166 1167
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1168
			assert(next_song != nullptr);
1169

1170 1171 1172 1173 1174 1175
			{
				const ScopeUnlock unlock(mutex);
				do_play(*this, dc, buffer);
				listener.OnPlayerSync();
			}

1176 1177
			break;

1178
		case PlayerCommand::STOP:
1179 1180 1181 1182
			{
				const ScopeUnlock unlock(mutex);
				outputs.Cancel();
			}
1183

1184
			/* fall through */
1185 1186 1187
#if CLANG_OR_GCC_VERSION(7,0)
			[[fallthrough]];
#endif
1188

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

1192
			CommandFinished();
1193 1194
			break;

1195
		case PlayerCommand::CLOSE_AUDIO:
1196 1197 1198 1199
			{
				const ScopeUnlock unlock(mutex);
				outputs.Release();
			}
1200

1201
			CommandFinished();
1202

1203
			assert(buffer.IsEmptyUnsafe());
1204

1205 1206
			break;

1207
		case PlayerCommand::UPDATE_AUDIO:
1208 1209 1210 1211 1212
			{
				const ScopeUnlock unlock(mutex);
				outputs.EnableDisable();
			}

1213
			CommandFinished();
1214 1215
			break;

1216
		case PlayerCommand::EXIT:
1217 1218 1219 1220 1221
			{
				const ScopeUnlock unlock(mutex);
				dc.Quit();
				outputs.Close();
			}
1222

1223
			CommandFinished();
1224
			return;
Max Kellermann's avatar
Max Kellermann committed
1225

1226
		case PlayerCommand::CANCEL:
1227
			next_song.reset();
1228

1229
			CommandFinished();
1230 1231
			break;

1232
		case PlayerCommand::REFRESH:
1233
			/* no-op when not playing */
1234
			CommandFinished();
1235 1236
			break;

1237
		case PlayerCommand::NONE:
1238
			Wait(lock);
1239 1240 1241
			break;
		}
	}
1242 1243 1244 1245 1246 1247 1248 1249
} 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? */
1250
}