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

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

38
#include <exception>
39
#include <memory>
40

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

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

45
class Player {
46
	PlayerControl &pc;
47

48
	DecoderControl &dc;
49

50 51
	MusicBuffer &buffer;

52
	std::shared_ptr<MusicPipe> pipe;
53

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

173 174
	template<typename P>
	void ReplacePipe(P &&_pipe) noexcept {
175
		ResetCrossFade();
176
		pipe = std::forward<P>(_pipe);
177 178 179 180 181
	}

	/**
	 * Start the decoder.
	 *
182
	 * Caller must lock the mutex.
183
	 */
184
	void StartDecoder(std::shared_ptr<MusicPipe> pipe) noexcept;
185 186 187

	/**
	 * The decoder has acknowledged the "START" command (see
188
	 * ActivateDecoder()).  This function checks if the decoder
189 190
	 * initialization has completed yet.  If not, it will wait
	 * some more.
191
	 *
192
	 * Caller must lock the mutex.
193 194 195
	 *
	 * @return false if the decoder has failed, true on success
	 * (though the decoder startup may or may not yet be finished)
196
	 */
197
	bool CheckDecoderStartup() noexcept;
198 199 200 201

	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
202
	 * Caller must lock the mutex.
203
	 */
204
	void StopDecoder() noexcept;
205 206 207 208 209 210 211 212

	/**
	 * 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
213
	bool IsDecoderAtCurrentSong() const noexcept {
214 215 216 217 218 219 220 221 222 223 224
		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
225
	bool IsDecoderAtNextSong() const noexcept {
226 227 228
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

229 230 231 232 233 234 235 236 237 238
	/**
	 * Invoke DecoderControl::Seek() and update our state or
	 * handle errors.
	 *
	 * Caller must lock the mutex.
	 *
	 * @return false if the decoder has failed
	 */
	bool SeekDecoder(SongTime seek_time) noexcept;

239
	/**
240
	 * This is the handler for the #PlayerCommand::SEEK command.
241
	 *
242
	 * Caller must lock the mutex.
243 244
	 *
	 * @return false if the decoder has failed
245
	 */
246
	bool SeekDecoder() noexcept;
247

248
	void CancelPendingSeek() noexcept {
249 250 251
		if (!pc.seeking)
			return;

252 253
		pending_seek = SongTime::zero();
		pc.seeking = false;
254
		pc.ClientSignal();
255 256
	}

257 258 259 260 261 262
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
263
	bool ForwardDecoderError() noexcept;
264

265
	/**
266 267 268 269 270 271 272 273 274
	 * 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().
275
	 *
276
	 * Caller must lock the mutex.
277
	 */
278
	void ActivateDecoder() noexcept;
279 280

	/**
281 282
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
283
	 *
284 285
	 * Caller must lock the mutex.
	 *
286 287
	 * @return true on success
	 */
288
	bool OpenOutput() noexcept;
289 290 291 292 293 294 295

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

298 299
	unsigned UnlockCheckOutputs() noexcept {
		const ScopeUnlock unlock(pc.mutex);
300
		return pc.outputs.CheckPipe();
301 302
	}

303 304
	/**
	 * Player lock must be held before calling.
305 306
	 *
	 * @return false to stop playback
307
	 */
308
	bool ProcessCommand() noexcept;
309 310 311 312 313 314

	/**
	 * 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.
	 *
315
	 * Caller must lock the mutex.
316
	 */
317
	void SongBorder() noexcept;
318

319
public:
320 321 322 323 324
	/*
	 * 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.
	 */
325
	void Run() noexcept;
326 327
};

328
void
329
Player::StartDecoder(std::shared_ptr<MusicPipe> _pipe) noexcept
330
{
331
	assert(queued || pc.command == PlayerCommand::SEEK);
332
	assert(pc.next_song != nullptr);
333

334 335
	/* copy ReplayGain parameters to the decoder */
	dc.replay_gain_mode = pc.replay_gain_mode;
336

337
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
338

339
	dc.Start(std::make_unique<DetachedSong>(*pc.next_song),
340
		 start_time, pc.next_song->GetEndTime(),
341
		 buffer, std::move(_pipe));
342 343
}

344
void
345
Player::StopDecoder() noexcept
346
{
347 348
	const PlayerControl::ScopeOccupied occupied(pc);

349
	dc.Stop();
350

351
	if (dc.pipe != nullptr) {
352 353
		/* clear and free the decoder pipe */

354
		dc.pipe->Clear();
355
		dc.pipe.reset();
356 357 358 359 360

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

364
bool
365
Player::ForwardDecoderError() noexcept
366
{
367 368 369 370
	try {
		dc.CheckRethrowError();
	} catch (...) {
		pc.SetError(PlayerError::DECODER, std::current_exception());
371 372 373 374 375 376
		return false;
	}

	return true;
}

377
void
378
Player::ActivateDecoder() noexcept
379
{
380
	assert(queued || pc.command == PlayerCommand::SEEK);
381
	assert(pc.next_song != nullptr);
382

383
	queued = false;
384

385
	pc.ClearTaggedSong();
386

387
	song = std::exchange(pc.next_song, nullptr);
388

389
	elapsed_time = pc.seek_time;
390

391
	/* set the "starting" flag, which will be cleared by
392
	   CheckDecoderStartup() */
393
	decoder_starting = true;
394
	pending_seek = SongTime::zero();
395

396 397 398 399
	/* update PlayerControl's song information */
	pc.total_time = song->GetDuration();
	pc.bit_rate = 0;
	pc.audio_format.Clear();
400

401 402 403 404
	{
		/* call syncPlaylistWithQueue() in the main thread */
		const ScopeUnlock unlock(pc.mutex);
		pc.listener.OnPlayerSync();
405
	}
406 407
}

408 409 410 411
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
412
static SignedSongTime
413 414
real_song_duration(const DetachedSong &song,
		   SignedSongTime decoder_duration) noexcept
415
{
416
	if (decoder_duration.IsNegative())
417
		/* the decoder plugin didn't provide information; fall
418
		   back to Song::GetDuration() */
419
		return song.GetDuration();
420

421 422
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
423

424 425
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
426

427
	return SignedSongTime(SongTime(decoder_duration) - start_time);
428 429
}

430
bool
431
Player::OpenOutput() noexcept
432
{
433
	assert(play_audio_format.IsDefined());
434 435
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);
436

437
	try {
438
		const ScopeUnlock unlock(pc.mutex);
439
		pc.outputs.Open(play_audio_format);
440 441
	} catch (...) {
		LogError(std::current_exception());
442

443
		output_open = false;
444

445 446
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
447
		paused = true;
448

449
		pc.SetOutputError(std::current_exception());
450

451 452
		idle_add(IDLE_PLAYER);

453 454
		return false;
	}
455 456 457 458

	output_open = true;
	paused = false;

459
	pc.state = PlayerState::PLAY;
460 461 462 463

	idle_add(IDLE_PLAYER);

	return true;
464 465
}

466
bool
467
Player::CheckDecoderStartup() noexcept
468
{
469
	assert(decoder_starting);
470

471
	if (!ForwardDecoderError()) {
472 473
		/* the decoder failed */
		return false;
474
	} else if (!dc.IsStarting()) {
475
		/* the decoder is ready and ok */
476

477
		if (output_open &&
478
		    !pc.WaitOutputConsumed(1))
479 480 481 482
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

483 484 485
		pc.total_time = real_song_duration(*dc.song,
						   dc.total_time);
		pc.audio_format = dc.in_audio_format;
486 487
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
488

489 490
		idle_add(IDLE_PLAYER);

491 492 493 494 495 496 497 498 499
		if (pending_seek > SongTime::zero()) {
			assert(pc.seeking);

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

500 501 502 503 504 505
			/* re-fill the buffer after seeking */
			buffering = true;
		} else if (pc.seeking) {
			pc.seeking = false;
			pc.ClientSignal();

506 507 508 509
			/* re-fill the buffer after seeking */
			buffering = true;
		}

510
		if (!paused && !OpenOutput()) {
511 512
			FormatError(player_domain,
				    "problems opening audio device "
513 514
				    "while playing \"%s\"",
				    dc.song->GetURI());
515 516
			return true;
		}
517 518 519 520 521

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
522
		dc.WaitForDecoder();
523 524 525 526 527

		return true;
	}
}

528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553
bool
Player::SeekDecoder(SongTime seek_time) noexcept
{
	assert(song);
	assert(!decoder_starting);

	if (!pc.total_time.IsNegative()) {
		const SongTime total_time(pc.total_time);
		if (seek_time > total_time)
			seek_time = total_time;
	}

	try {
		const PlayerControl::ScopeOccupied occupied(pc);

		dc.Seek(song->GetStartTime() + seek_time);
	} catch (...) {
		/* decoder failure */
		pc.SetError(PlayerError::DECODER, std::current_exception());
		return false;
	}

	elapsed_time = seek_time;
	return true;
}

554
inline bool
555
Player::SeekDecoder() noexcept
556
{
557
	assert(pc.next_song != nullptr);
558

559 560
	CancelPendingSeek();

561 562 563 564
	{
		const ScopeUnlock unlock(pc.mutex);
		pc.outputs.Cancel();
	}
565

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

570
		StopDecoder();
571

572 573
		/* clear music chunks which might still reside in the
		   pipe */
574
		pipe->Clear();
575

576
		/* re-start the decoder */
577
		StartDecoder(pipe);
578
		ActivateDecoder();
579

580 581 582 583 584 585
		pc.seeking = true;
		pc.CommandFinished();

		assert(xfade_state == CrossFadeState::UNKNOWN);

		return true;
586
	} else {
587
		if (!IsDecoderAtCurrentSong()) {
588 589
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
590
			ReplacePipe(dc.pipe);
591 592
		}

593
		pc.next_song.reset();
594
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
595

596 597 598 599
		if (decoder_starting) {
			/* wait for the decoder to complete
			   initialization; postpone the SEEK
			   command */
600

601 602
			pending_seek = pc.seek_time;
			pc.seeking = true;
603
			pc.CommandFinished();
604 605 606 607 608 609 610 611
			return true;
		} else {
			/* send the SEEK command */

			if (!SeekDecoder(pc.seek_time)) {
				pc.CommandFinished();
				return false;
			}
612
		}
613
	}
614

615
	pc.CommandFinished();
616

617
	assert(xfade_state == CrossFadeState::UNKNOWN);
618

619
	/* re-fill the buffer after seeking */
620
	buffering = true;
621 622

	return true;
623 624
}

625
inline bool
626
Player::ProcessCommand() noexcept
627
{
628
	switch (pc.command) {
629
	case PlayerCommand::NONE:
630 631
		break;

632 633 634
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
635
		return false;
636

637
	case PlayerCommand::UPDATE_AUDIO:
638 639 640 641 642
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

643
		pc.CommandFinished();
644 645
		break;

646
	case PlayerCommand::QUEUE:
647
		assert(pc.next_song != nullptr);
648 649
		assert(!queued);
		assert(!IsDecoderAtNextSong());
650

651
		queued = true;
652
		pc.CommandFinished();
653

654
		if (dc.IsIdle())
655
			StartDecoder(std::make_shared<MusicPipe>());
656

657 658
		break;

659
	case PlayerCommand::PAUSE:
660 661
		paused = !paused;
		if (paused) {
662
			pc.state = PlayerState::PAUSE;
663 664 665

			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.Pause();
666
		} else if (!play_audio_format.IsDefined()) {
667 668
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
669
			pc.state = PlayerState::PLAY;
670
		} else {
671
			OpenOutput();
672
		}
673

674
		pc.CommandFinished();
675 676
		break;

677
	case PlayerCommand::SEEK:
678
		return SeekDecoder();
679

680
	case PlayerCommand::CANCEL:
681
		if (pc.next_song == nullptr)
682
			/* the cancel request arrived too late, we're
683 684
			   already playing the queued song...  stop
			   everything now */
685
			return false;
686

687
		if (IsDecoderAtNextSong())
688 689
			/* the decoder is already decoding the song -
			   stop it and reset the position */
690
			StopDecoder();
691

692
		pc.next_song.reset();
693
		queued = false;
694
		pc.CommandFinished();
695
		break;
696

697
	case PlayerCommand::REFRESH:
698
		if (output_open && !paused) {
699
			const ScopeUnlock unlock(pc.mutex);
700
			pc.outputs.CheckPipe();
701
		}
702

703 704
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
705
			: elapsed_time;
706

707
		pc.CommandFinished();
708
		break;
709
	}
710 711

	return true;
712 713
}

714
static void
715 716
update_song_tag(PlayerControl &pc, DetachedSong &song,
		const Tag &new_tag) noexcept
717
{
718
	if (song.IsFile())
719 720 721 722
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

723
	song.SetTag(new_tag);
724

725
	pc.LockSetTaggedSong(song);
726

727 728
	/* the main thread will update the playlist version when he
	   receives this event */
729
	pc.listener.OnPlayerTagModified();
730 731 732 733 734 735

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

736
/**
737
 * Plays a #MusicChunk object (after applying software volume).  If
738 739
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
740 741
 *
 * Player lock is not held.
742
 */
743
static void
744
play_chunk(PlayerControl &pc,
745
	   DetachedSong &song, MusicChunkPtr chunk,
746
	   const AudioFormat format)
747
{
748
	assert(chunk->CheckFormat(format));
749

750
	if (chunk->tag != nullptr)
751
		update_song_tag(pc, song, *chunk->tag);
752

753
	if (chunk->IsEmpty())
754
		return;
755

756
	{
757
		const std::lock_guard<Mutex> lock(pc.mutex);
758 759
		pc.bit_rate = chunk->bit_rate;
	}
760

761 762
	/* send the chunk to the audio outputs */

763 764 765 766
	const double chunk_length(chunk->length);

	pc.outputs.Play(std::move(chunk));
	pc.total_play_time += chunk_length / format.GetTimeToSize();
767 768
}

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

777 778 779 780 781 782 783 784 785 786 787
	/* 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;
	}

788
	MusicChunkPtr chunk;
789
	if (xfade_state == CrossFadeState::ACTIVE) {
790 791
		/* perform cross fade */

792 793 794 795
		assert(IsDecoderAtNextSong());

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

797
		auto other_chunk = dc.pipe->Shift();
798
		if (other_chunk != nullptr) {
799
			chunk = pipe->Shift();
800 801
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
802

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

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

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

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

831
			const std::lock_guard<Mutex> lock(pc.mutex);
832

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

842 843 844 845 846
				return true;
			}
		}
	}

847
	if (chunk == nullptr)
848
		chunk = pipe->Shift();
849

850
	assert(chunk != nullptr);
851

852 853
	/* insert the postponed tag if cross-fading is finished */

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

860 861
	/* play the current chunk */

862
	try {
863 864
		play_chunk(pc, *song, std::move(chunk),
			   play_audio_format);
865 866
	} catch (...) {
		LogError(std::current_exception());
867

868
		chunk.reset();
869 870 871

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

874
		pc.LockSetOutputError(std::current_exception());
875

876 877
		idle_add(IDLE_PLAYER);

878
		return false;
879
	}
880

881
	const std::lock_guard<Mutex> lock(pc.mutex);
882

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

	return true;
}

899
inline void
900
Player::SongBorder() noexcept
901
{
902 903
	{
		const ScopeUnlock unlock(pc.mutex);
904

905
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
906

907
		ReplacePipe(dc.pipe);
908

909
		pc.outputs.SongBorder();
910
	}
911

912 913 914
	ActivateDecoder();

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

923
inline void
924
Player::Run() noexcept
925
{
926
	pipe = std::make_shared<MusicPipe>();
927

928
	const std::lock_guard<Mutex> lock(pc.mutex);
929

930
	StartDecoder(pipe);
931
	ActivateDecoder();
932

933
	pc.state = PlayerState::PLAY;
934

935
	pc.CommandFinished();
936

937
	while (true) {
938
		if (!ProcessCommand())
939 940
			break;

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

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

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

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

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

964
			continue;
965 966
		}

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

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

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

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

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

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

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

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

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

1044 1045 1046 1047 1048 1049
			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
			// TODO: eliminate this kludge
			dc.Signal();

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

1054
	CancelPendingSeek();
1055
	StopDecoder();
1056

1057
	pipe.reset();
1058

1059
	cross_fade_tag.reset();
1060

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

1066 1067
	pc.ClearTaggedSong();

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

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

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

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

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

1094
	MusicBuffer buffer(buffer_chunks);
1095

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

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

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

1110 1111
			break;

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

1118 1119
			/* fall through */

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

1123
			CommandFinished();
1124 1125
			break;

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

1132
			CommandFinished();
1133

1134
			assert(buffer.IsEmptyUnsafe());
1135

1136 1137
			break;

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

1144
			CommandFinished();
1145 1146
			break;

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

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

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

1160
			CommandFinished();
1161 1162
			break;

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

1168
		case PlayerCommand::NONE:
1169
			Wait();
1170 1171 1172 1173 1174
			break;
		}
	}
}

1175
void
1176
StartPlayerThread(PlayerControl &pc)
1177
{
1178 1179
	assert(!pc.thread.IsDefined());

1180
	pc.thread.Start();
1181
}