Thread.cxx 28.8 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2021 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
	void StartDecoder(std::unique_lock<Mutex> &lock,
Max Kellermann's avatar
Max Kellermann committed
227
			  std::shared_ptr<MusicPipe> pipe,
228
			  bool initial_seek_essential) noexcept;
229 230 231

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

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
246
	 * Caller must lock the mutex.
247
	 */
248
	void StopDecoder(std::unique_lock<Mutex> &lock) noexcept;
249 250 251 252 253 254 255

	/**
	 * Is the decoder still busy on the same song as the player?
	 *
	 * Note: this function does not check if the decoder is already
	 * finished.
	 */
256
	[[nodiscard]] gcc_pure
257
	bool IsDecoderAtCurrentSong() const noexcept {
258 259 260 261 262 263 264 265 266 267
		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.
	 */
268
	[[nodiscard]] gcc_pure
269
	bool IsDecoderAtNextSong() const noexcept {
270 271 272
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

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

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

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

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

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

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

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

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

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

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

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

369
void
370
Player::StartDecoder(std::unique_lock<Mutex> &lock,
Max Kellermann's avatar
Max Kellermann committed
371
		     std::shared_ptr<MusicPipe> _pipe,
372
		     bool initial_seek_essential) noexcept
373
{
374
	assert(queued || pc.command == PlayerCommand::SEEK);
375
	assert(pc.next_song != nullptr);
376

377 378
	/* copy ReplayGain parameters to the decoder */
	dc.replay_gain_mode = pc.replay_gain_mode;
379

380
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
381

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

388
void
389
Player::StopDecoder(std::unique_lock<Mutex> &lock) noexcept
390
{
391 392
	const PlayerControl::ScopeOccupied occupied(pc);

393
	dc.Stop(lock);
394

395
	if (dc.pipe != nullptr) {
396 397
		/* clear and free the decoder pipe */

398
		dc.pipe->Clear();
399
		dc.pipe.reset();
400 401 402 403 404

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

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

	return true;
}

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

427
	queued = false;
428

429
	pc.ClearTaggedSong();
430

431
	song = std::exchange(pc.next_song, nullptr);
432

433
	elapsed_time = pc.seek_time;
434

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

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

445
	{
446
		/* call playlist::SyncWithPlayer() in the main thread */
447 448
		const ScopeUnlock unlock(pc.mutex);
		pc.listener.OnPlayerSync();
449
	}
450 451
}

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

465 466
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
467

468 469
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
470

471
	return SignedSongTime(SongTime(decoder_duration) - start_time);
472 473
}

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

481
	try {
482
		const ScopeUnlock unlock(pc.mutex);
483
		pc.outputs.Open(play_audio_format);
484 485
	} catch (...) {
		LogError(std::current_exception());
486

487
		output_open = false;
488

489 490
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
491
		paused = true;
492

493
		pc.SetOutputError(std::current_exception());
494

495 496
		idle_add(IDLE_PLAYER);

497 498
		return false;
	}
499 500 501 502

	output_open = true;
	paused = false;

503
	pc.state = PlayerState::PLAY;
504 505 506 507

	idle_add(IDLE_PLAYER);

	return true;
508 509
}

510 511
inline bool
Player::CheckDecoderStartup(std::unique_lock<Mutex> &lock) noexcept
512
{
513
	assert(decoder_starting);
514

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

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

527 528 529
		pc.total_time = real_song_duration(*dc.song,
						   dc.total_time);
		pc.audio_format = dc.in_audio_format;
530 531
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
532

533 534 535 536 537 538
		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);

539 540
		idle_add(IDLE_PLAYER);

541 542 543
		if (pending_seek > SongTime::zero()) {
			assert(pc.seeking);

544
			bool success = SeekDecoder(lock, pending_seek);
545 546 547 548 549
			pc.seeking = false;
			pc.ClientSignal();
			if (!success)
				return false;

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

556 557 558 559
			/* re-fill the buffer after seeking */
			buffering = true;
		}

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

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

		return true;
	}
}

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

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

	elapsed_time = seek_time;
	return true;
}

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

609 610 611 612 613 614 615 616 617 618 619 620 621
	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;
	}

622 623
	CancelPendingSeek();

624 625 626 627
	{
		const ScopeUnlock unlock(pc.mutex);
		pc.outputs.Cancel();
	}
628

629
	idle_add(IDLE_PLAYER);
630

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

635
		StopDecoder(lock);
636

637 638
		/* clear music chunks which might still reside in the
		   pipe */
639
		pipe->Clear();
640

641
		/* re-start the decoder */
Max Kellermann's avatar
Max Kellermann committed
642
		StartDecoder(lock, pipe, true);
643
		ActivateDecoder();
644

645 646 647 648 649 650
		pc.seeking = true;
		pc.CommandFinished();

		assert(xfade_state == CrossFadeState::UNKNOWN);

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

658
		pc.next_song.reset();
659
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
660

661 662 663 664
		if (decoder_starting) {
			/* wait for the decoder to complete
			   initialization; postpone the SEEK
			   command */
665

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

673
			if (!SeekDecoder(lock, pc.seek_time)) {
674 675 676
				pc.CommandFinished();
				return false;
			}
677
		}
678
	}
679

680
	pc.CommandFinished();
681

682
	assert(xfade_state == CrossFadeState::UNKNOWN);
683

684
	/* re-fill the buffer after seeking */
685
	buffering = true;
686

687 688 689 690 691 692
	{
		/* call syncPlaylistWithQueue() in the main thread */
		const ScopeUnlock unlock(pc.mutex);
		pc.listener.OnPlayerSync();
	}

693
	return true;
694 695
}

696
inline bool
697
Player::ProcessCommand(std::unique_lock<Mutex> &lock) noexcept
698
{
699
	switch (pc.command) {
700
	case PlayerCommand::NONE:
701 702
		break;

703 704 705
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
706
		return false;
707

708
	case PlayerCommand::UPDATE_AUDIO:
709 710 711 712 713
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

714
		pc.CommandFinished();
715 716
		break;

717
	case PlayerCommand::QUEUE:
718
		assert(pc.next_song != nullptr);
719 720
		assert(!queued);
		assert(!IsDecoderAtNextSong());
721

722
		queued = true;
723
		pc.CommandFinished();
724

725
		if (dc.IsIdle())
Max Kellermann's avatar
Max Kellermann committed
726 727
			StartDecoder(lock, std::make_shared<MusicPipe>(),
				     false);
728

729 730
		break;

731
	case PlayerCommand::PAUSE:
732 733
		paused = !paused;
		if (paused) {
734
			pc.state = PlayerState::PAUSE;
735 736 737

			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.Pause();
738
		} else if (!play_audio_format.IsDefined()) {
739 740
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
741
			pc.state = PlayerState::PLAY;
742
		} else {
743
			OpenOutput();
744
		}
745

746
		pc.CommandFinished();
747 748
		break;

749
	case PlayerCommand::SEEK:
750
		return SeekDecoder(lock);
751

752
	case PlayerCommand::CANCEL:
753
		if (pc.next_song == nullptr)
754
			/* the cancel request arrived too late, we're
755 756
			   already playing the queued song...  stop
			   everything now */
757
			return false;
758

759
		if (IsDecoderAtNextSong())
760 761
			/* the decoder is already decoding the song -
			   stop it and reset the position */
762
			StopDecoder(lock);
763

764
		pc.next_song.reset();
765
		queued = false;
766
		pc.CommandFinished();
767
		break;
768

769
	case PlayerCommand::REFRESH:
770
		if (output_open && !paused) {
771
			const ScopeUnlock unlock(pc.mutex);
772
			pc.outputs.CheckPipe();
773
		}
774

775 776
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
777
			: elapsed_time;
778

779
		pc.CommandFinished();
780
		break;
781
	}
782 783

	return true;
784 785
}

786 787 788
inline void
PlayerControl::LockUpdateSongTag(DetachedSong &song,
				 const Tag &new_tag) noexcept
789
{
790
	if (song.IsFile())
791 792 793 794
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

795
	song.SetTag(new_tag);
796

797
	LockSetTaggedSong(song);
798

799 800
	/* the main thread will update the playlist version when he
	   receives this event */
801
	listener.OnPlayerTagModified();
802 803 804 805 806 807

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

808 809 810
inline void
PlayerControl::PlayChunk(DetachedSong &song, MusicChunkPtr chunk,
			 const AudioFormat &format)
811
{
812
	assert(chunk->CheckFormat(format));
813

814
	if (chunk->tag != nullptr)
815
		LockUpdateSongTag(song, *chunk->tag);
816

817
	if (chunk->IsEmpty())
818
		return;
819

820
	{
821 822
		const std::lock_guard<Mutex> lock(mutex);
		bit_rate = chunk->bit_rate;
823
	}
824

825 826
	/* send the chunk to the audio outputs */

827 828
	const double chunk_length(chunk->length);

829
	outputs.Play(std::move(chunk));
830
	total_play_time += format.SizeToTime<decltype(total_play_time)>(chunk_length);
831 832
}

833
inline bool
834
Player::PlayNextChunk() noexcept
835
{
836
	if (!pc.LockWaitOutputConsumed(64))
837 838
		/* the output pipe is still large enough, don't send
		   another chunk */
839 840
		return true;

841 842 843 844 845 846 847 848 849 850 851
	/* 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;
	}

852
	MusicChunkPtr chunk;
853
	if (xfade_state == CrossFadeState::ACTIVE) {
854 855
		/* perform cross fade */

856 857 858 859
		assert(IsDecoderAtNextSong());

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

861
		auto other_chunk = dc.pipe->Shift();
862
		if (other_chunk != nullptr) {
863
			chunk = pipe->Shift();
864 865
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
866

867 868 869
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
870 871
			cross_fade_tag = Tag::Merge(std::move(cross_fade_tag),
						    std::move(other_chunk->tag));
872

873
			if (pc.cross_fade.mixramp_delay <= FloatDuration::zero()) {
874
				chunk->mix_ratio = ((float)cross_fade_position)
875
					     / cross_fade_chunks;
876
			} else {
877
				chunk->mix_ratio = -1;
878
			}
879

880
			if (other_chunk->IsEmpty()) {
881
				/* the "other" chunk was a MusicChunk
882 883 884 885 886 887
				   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 */
888
				other_chunk.reset();
889
			}
890

891
			chunk->other = std::move(other_chunk);
892
		} else {
893
			/* there are not enough decoded chunks yet */
894

895
			std::unique_lock<Mutex> lock(pc.mutex);
896

897
			if (dc.IsIdle()) {
898
				/* the decoder isn't running, abort
899
				   cross fading */
900
				xfade_state = CrossFadeState::DISABLED;
901
			} else {
902
				/* wait for the decoder */
903
				dc.Signal();
904
				dc.WaitForDecoder(lock);
905

906 907 908 909 910
				return true;
			}
		}
	}

911
	if (chunk == nullptr)
912
		chunk = pipe->Shift();
913

914
	assert(chunk != nullptr);
915

916 917
	/* insert the postponed tag if cross-fading is finished */

918
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
919 920
		chunk->tag = Tag::Merge(std::move(chunk->tag),
					std::move(cross_fade_tag));
921
		cross_fade_tag = nullptr;
922 923
	}

924 925
	/* play the current chunk */

926
	try {
927 928
		pc.PlayChunk(*song, std::move(chunk),
			     play_audio_format);
929 930
	} catch (...) {
		LogError(std::current_exception());
931

932
		chunk.reset();
933 934 935

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

938
		pc.LockSetOutputError(std::current_exception());
939

940 941
		idle_add(IDLE_PLAYER);

942
		return false;
943
	}
944

945
	const std::lock_guard<Mutex> lock(pc.mutex);
946

947 948
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
949
	   larger block at a time */
950
	if (!dc.IsIdle() && dc.pipe->GetSize() <= decoder_wakeup_threshold) {
951 952 953 954 955 956
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
957 958 959 960

	return true;
}

961
inline void
962
Player::SongBorder() noexcept
963
{
964 965
	{
		const ScopeUnlock unlock(pc.mutex);
966

967
		FormatNotice(player_domain, "played \"%s\"", song->GetURI());
968

969
		ReplacePipe(dc.pipe);
970

971
		pc.outputs.SongBorder();
972
	}
973

974 975 976
	ActivateDecoder();

	const bool border_pause = pc.ApplyBorderPause();
977
	if (border_pause) {
978
		paused = true;
979
		pc.listener.OnBorderPause();
980 981 982 983 984 985

		/* 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();

986
		pc.outputs.Pause();
987
		idle_add(IDLE_PLAYER);
988
	}
989 990
}

991
inline void
992
Player::Run() noexcept
993
{
994
	pipe = std::make_shared<MusicPipe>();
995

996
	std::unique_lock<Mutex> lock(pc.mutex);
997

Max Kellermann's avatar
Max Kellermann committed
998
	StartDecoder(lock, pipe, true);
999
	ActivateDecoder();
1000

1001
	pc.state = PlayerState::PLAY;
1002

1003
	pc.CommandFinished();
1004

1005
	while (ProcessCommand(lock)) {
1006 1007 1008
		if (decoder_starting) {
			/* wait until the decoder is initialized completely */

1009
			if (!CheckDecoderStartup(lock))
1010 1011 1012 1013 1014
				break;

			continue;
		}

1015
		if (buffering) {
1016 1017 1018 1019
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

1020
			if (pipe->GetSize() < buffer_before_play &&
1021
			    !dc.IsIdle() && !buffer.IsFull()) {
1022
				/* not enough decoded buffer space yet */
1023

1024
				dc.WaitForDecoder(lock);
1025 1026 1027
				continue;
			} else {
				/* buffering is complete */
1028
				buffering = false;
1029 1030 1031
			}
		}

1032
		if (dc.IsIdle() && queued && IsDecoderAtCurrentSong()) {
1033 1034
			/* the decoder has finished the current song;
			   make it decode the next song */
1035

1036
			assert(dc.pipe == nullptr || dc.pipe == pipe);
1037

Max Kellermann's avatar
Max Kellermann committed
1038 1039
			StartDecoder(lock, std::make_shared<MusicPipe>(),
				     false);
1040
		}
1041

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

1069
		if (paused) {
1070
			if (pc.command == PlayerCommand::NONE)
1071
				pc.Wait(lock);
1072
		} else if (!pipe->IsEmpty()) {
1073 1074
			/* at least one music chunk is ready - send it
			   to the audio output */
1075

1076
			const ScopeUnlock unlock(pc.mutex);
1077
			PlayNextChunk();
1078
		} else if (UnlockCheckOutputs() > 0) {
1079 1080 1081 1082
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1083 1084 1085
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
1086
			// TODO: eliminate this kludge
1087
			dc.Signal();
1088

1089
			dc.WaitForDecoder(lock);
1090
		} else if (IsDecoderAtNextSong()) {
1091 1092
			/* at the beginning of a new song */

1093
			SongBorder();
1094
		} else if (dc.IsIdle()) {
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
			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;

1105 1106 1107
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1108
			if (pipe->IsEmpty()) {
1109 1110
				/* wait for the hardware to finish
				   playback */
1111
				const ScopeUnlock unlock(pc.mutex);
1112
				pc.outputs.Drain();
1113
				break;
1114
			}
1115
		} else if (output_open) {
1116
			/* the decoder is too busy and hasn't provided
1117 1118
			   new PCM data in time: wait for the
			   decoder */
1119

1120 1121 1122 1123 1124 1125
			/* 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();

1126
			dc.WaitForDecoder(lock);
1127 1128 1129
		}
	}

1130
	CancelPendingSeek();
1131
	StopDecoder(lock);
1132

1133
	pipe.reset();
1134

1135
	cross_fade_tag.reset();
1136

1137
	if (song != nullptr) {
1138
		FormatNotice(player_domain, "played \"%s\"", song->GetURI());
1139
		song.reset();
1140
	}
1141

1142 1143
	pc.ClearTaggedSong();

1144
	if (queued) {
1145
		assert(pc.next_song != nullptr);
1146
		pc.next_song.reset();
1147 1148
	}

1149
	pc.state = PlayerState::STOP;
1150 1151
}

1152
static void
1153
do_play(PlayerControl &pc, DecoderControl &dc,
1154
	MusicBuffer &buffer) noexcept
1155
{
1156
	Player player(pc, dc, buffer);
1157 1158 1159
	player.Run();
}

1160
void
1161
PlayerControl::RunThread() noexcept
1162
try {
1163 1164
	SetThreadName("player");

1165
	DecoderControl dc(mutex, cond,
1166
			  input_cache,
1167 1168
			  configured_audio_format,
			  replay_gain_config);
1169
	dc.StartThread();
1170

1171
	MusicBuffer buffer(buffer_chunks);
1172

1173
	std::unique_lock<Mutex> lock(mutex);
1174

1175
	while (true) {
1176
		switch (command) {
1177 1178
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1179
			assert(next_song != nullptr);
1180

1181 1182 1183
			{
				const ScopeUnlock unlock(mutex);
				do_play(*this, dc, buffer);
1184 1185 1186 1187 1188

				/* give the main thread a chance to
				   queue another song, just in case
				   we've stopped playback
				   spuriously */
1189 1190 1191
				listener.OnPlayerSync();
			}

1192 1193
			break;

1194
		case PlayerCommand::STOP:
1195 1196 1197 1198
			{
				const ScopeUnlock unlock(mutex);
				outputs.Cancel();
			}
1199

1200
			/* fall through */
1201 1202 1203
#if CLANG_OR_GCC_VERSION(7,0)
			[[fallthrough]];
#endif
1204

1205
		case PlayerCommand::PAUSE:
1206
			next_song.reset();
1207

1208
			CommandFinished();
1209 1210
			break;

1211
		case PlayerCommand::CLOSE_AUDIO:
1212 1213 1214 1215
			{
				const ScopeUnlock unlock(mutex);
				outputs.Release();
			}
1216

1217
			CommandFinished();
1218

1219
			assert(buffer.IsEmptyUnsafe());
1220

1221 1222
			break;

1223
		case PlayerCommand::UPDATE_AUDIO:
1224 1225 1226 1227 1228
			{
				const ScopeUnlock unlock(mutex);
				outputs.EnableDisable();
			}

1229
			CommandFinished();
1230 1231
			break;

1232
		case PlayerCommand::EXIT:
1233 1234 1235 1236 1237
			{
				const ScopeUnlock unlock(mutex);
				dc.Quit();
				outputs.Close();
			}
1238

1239
			CommandFinished();
1240
			return;
Max Kellermann's avatar
Max Kellermann committed
1241

1242
		case PlayerCommand::CANCEL:
1243
			next_song.reset();
1244

1245
			CommandFinished();
1246 1247
			break;

1248
		case PlayerCommand::REFRESH:
1249
			/* no-op when not playing */
1250
			CommandFinished();
1251 1252
			break;

1253
		case PlayerCommand::NONE:
1254
			Wait(lock);
1255 1256 1257
			break;
		}
	}
1258 1259 1260 1261 1262 1263 1264 1265
} 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? */
1266
}