Thread.cxx 25.9 KB
Newer Older
1
/*
2
 * Copyright 2003-2016 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 22
#include "Thread.hxx"
#include "Listener.hxx"
23 24
#include "decoder/DecoderThread.hxx"
#include "decoder/DecoderControl.hxx"
25 26 27
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
28
#include "pcm/Silence.hxx"
29
#include "DetachedSong.hxx"
30
#include "CrossFade.hxx"
31
#include "Control.hxx"
32
#include "output/MultipleOutputs.hxx"
33
#include "tag/Tag.hxx"
Max Kellermann's avatar
Max Kellermann committed
34
#include "Idle.hxx"
35
#include "util/Domain.hxx"
36
#include "util/Error.hxx"
37
#include "thread/Name.hxx"
38
#include "Log.hxx"
39

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

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

44
class Player {
45
	PlayerControl &pc;
46

47
	DecoderControl &dc;
48

49 50
	MusicBuffer &buffer;

51
	MusicPipe *pipe;
52

53
	/**
54
	 * are we waiting for buffered_before_play?
55
	 */
56
	bool buffering;
57 58 59 60 61 62 63

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

64 65 66 67 68 69
	/**
	 * Did we wake up the DecoderThread recently?  This avoids
	 * duplicate wakeup calls.
	 */
	bool decoder_woken;

70 71 72 73 74
	/**
	 * is the player paused?
	 */
	bool paused;

75 76 77 78 79
	/**
	 * is there a new song in pc.next_song?
	 */
	bool queued;

80 81 82 83 84 85 86 87
	/**
	 * 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.
	 */
	bool output_open;

88 89 90
	/**
	 * the song currently being played
	 */
91
	DetachedSong *song;
92

93
	/**
94
	 * Is cross-fading to the next song enabled?
95
	 */
96
	enum class CrossFadeState : uint8_t {
97 98 99 100
		/**
		 * The initial state: we don't know yet if we will
		 * cross-fade; it will be determined soon.
		 */
101
		UNKNOWN,
102 103 104 105 106

		/**
		 * Cross-fading is disabled for the transition to the
		 * next song.
		 */
107
		DISABLED,
108 109 110 111 112 113

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

116 117 118 119 120
		/**
		 * Currently cross-fading to the next song.
		 */
		ACTIVE,
	} xfade_state;
121 122 123 124 125 126

	/**
	 * The number of chunks used for crossfading.
	 */
	unsigned cross_fade_chunks;

127 128 129 130 131
	/**
	 * The tag of the "next" song during cross-fade.  It is
	 * postponed, and sent to the output thread when the new song
	 * really begins.
	 */
Max Kellermann's avatar
Max Kellermann committed
132
	Tag *cross_fade_tag;
133

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

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

148
public:
149
	Player(PlayerControl &_pc, DecoderControl &_dc,
150 151
	       MusicBuffer &_buffer)
		:pc(_pc), dc(_dc), buffer(_buffer),
152
		 buffering(true),
153
		 decoder_starting(false),
154
		 decoder_woken(false),
155 156 157
		 paused(false),
		 queued(true),
		 output_open(false),
158
		 song(nullptr),
159
		 xfade_state(CrossFadeState::UNKNOWN),
160
		 cross_fade_chunks(0),
161
		 cross_fade_tag(nullptr),
162
		 elapsed_time(SongTime::zero()) {}
163

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

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

	void ClearAndReplacePipe(MusicPipe *_pipe) {
179
		ResetCrossFade();
180 181 182 183 184
		ClearAndDeletePipe();
		pipe = _pipe;
	}

	void ReplacePipe(MusicPipe *_pipe) {
185
		ResetCrossFade();
186 187 188 189 190 191 192 193 194 195 196 197 198
		delete pipe;
		pipe = _pipe;
	}

	/**
	 * Start the decoder.
	 *
	 * Player lock is not held.
	 */
	void StartDecoder(MusicPipe &pipe);

	/**
	 * The decoder has acknowledged the "START" command (see
199
	 * ActivateDecoder()).  This function checks if the decoder
200 201 202 203 204 205
	 * initialization has completed yet.
	 *
	 * The player lock is not held.
	 */
	bool CheckDecoderStartup();

206 207 208 209 210 211 212 213 214 215 216
	/**
	 * Call CheckDecoderStartup() repeatedly until the decoder has
	 * finished startup.  Returns false on decoder error (and
	 * finishes the #PlayerCommand).
	 *
	 * This method does not check for commands.  It is only
	 * allowed to be used while a command is being handled.
	 */
	bool WaitDecoderStartup() {
		while (decoder_starting) {
			if (!CheckDecoderStartup()) {
217 218 219 220 221
				/* if decoder startup fails, make sure
				   the previous song is not being
				   played anymore */
				pc.outputs.Cancel();

222 223 224 225 226 227 228 229
				pc.LockCommandFinished();
				return false;
			}
		}

		return true;
	}

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
	/**
	 * Stop the decoder and clears (and frees) its music pipe.
	 *
	 * Player lock is not held.
	 */
	void StopDecoder();

	/**
	 * 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
	bool IsDecoderAtCurrentSong() const {
		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
	bool IsDecoderAtNextSong() const {
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

	/**
261
	 * This is the handler for the #PlayerCommand::SEEK command.
262 263 264 265 266
	 *
	 * The player lock is not held.
	 */
	bool SeekDecoder();

267 268 269 270 271 272 273 274
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
	bool ForwardDecoderError();

275
	/**
276 277 278 279 280 281 282 283 284
	 * 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().
285 286 287
	 *
	 * The player lock is not held.
	 */
288
	void ActivateDecoder();
289 290

	/**
291 292
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326
	 *
	 * @return true on success
	 */
	bool OpenOutput();

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

	/**
	 * Sends a chunk of silence to the audio outputs.  This is
	 * called when there is not enough decoded data in the pipe
	 * yet, to prevent underruns in the hardware buffers.
	 *
	 * The player lock is not held.
	 */
	bool SendSilence();

	/**
	 * Player lock must be held before calling.
	 */
	void ProcessCommand();

	/**
	 * 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.
	 *
	 * The player lock is not held.
	 */
327
	void SongBorder();
328

329
public:
330 331 332 333 334 335
	/*
	 * 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.
	 */
	void Run();
336 337
};

338
void
339
Player::StartDecoder(MusicPipe &_pipe)
340
{
341
	assert(queued || pc.command == PlayerCommand::SEEK);
342
	assert(pc.next_song != nullptr);
343

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

346
	dc.Start(new DetachedSong(*pc.next_song),
347
		 start_time, pc.next_song->GetEndTime(),
348
		 buffer, _pipe);
349 350
}

351
void
352
Player::StopDecoder()
353
{
354
	dc.Stop();
355

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

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

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

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

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

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

	return true;
}

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

392
	queued = false;
393

394
	pc.Lock();
395 396
	pc.ClearTaggedSong();

397
	delete song;
398
	song = pc.next_song;
399 400
	pc.next_song = nullptr;

401
	elapsed_time = pc.seek_time;
402 403 404

	/* set the "starting" flag, which will be cleared by
	   player_check_decoder_startup() */
405
	decoder_starting = true;
406

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

412
	pc.Unlock();
413

414
	/* call syncPlaylistWithQueue() in the main thread */
415
	pc.listener.OnPlayerSync();
416 417
}

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

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

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

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

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

446
	Error error;
447
	if (pc.outputs.Open(play_audio_format, buffer, error)) {
448 449
		output_open = true;
		paused = false;
450

451
		pc.Lock();
452
		pc.state = PlayerState::PLAY;
453
		pc.Unlock();
454

455 456
		idle_add(IDLE_PLAYER);

457 458
		return true;
	} else {
459
		LogError(error);
460

461
		output_open = false;
462

463 464
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
465
		paused = true;
466

467
		pc.Lock();
468 469
		pc.SetError(PlayerError::OUTPUT, std::move(error));
		pc.state = PlayerState::PAUSE;
470
		pc.Unlock();
471

472 473
		idle_add(IDLE_PLAYER);

474 475 476 477
		return false;
	}
}

478
bool
479
Player::CheckDecoderStartup()
480
{
481
	assert(decoder_starting);
482

483
	pc.Lock();
484

485
	if (!ForwardDecoderError()) {
486
		/* the decoder failed */
487
		pc.Unlock();
488 489

		return false;
490
	} else if (!dc.IsStarting()) {
491
		/* the decoder is ready and ok */
492

493
		pc.Unlock();
494

495
		if (output_open &&
496
		    !pc.outputs.Wait(pc, 1))
497 498 499 500
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

501
		pc.Lock();
502
		pc.total_time = real_song_duration(*dc.song, dc.total_time);
503 504
		pc.audio_format = dc.in_audio_format;
		pc.Unlock();
505

506 507
		idle_add(IDLE_PLAYER);

508 509
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
510

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

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

		return true;
	}
}

530
bool
531
Player::SendSilence()
532
{
533 534
	assert(output_open);
	assert(play_audio_format.IsDefined());
535

536
	MusicChunk *chunk = buffer.Allocate();
537
	if (chunk == nullptr) {
538 539 540 541 542 543
		/* this is non-fatal, because this means that the
		   decoder has filled to buffer completely meanwhile;
		   by ignoring the error, we work around this race
		   condition */
		LogDebug(player_domain, "Failed to allocate silence buffer");
		return true;
544 545 546
	}

#ifndef NDEBUG
547
	chunk->audio_format = play_audio_format;
548 549
#endif

550
	const size_t frame_size = play_audio_format.GetFrameSize();
551 552 553 554
	/* this formula ensures that we don't send
	   partial frames */
	unsigned num_frames = sizeof(chunk->data) / frame_size;

555
	chunk->time = SignedSongTime::Negative(); /* undefined time stamp */
556
	chunk->length = num_frames * frame_size;
557
	PcmSilence({chunk->data, chunk->length}, play_audio_format.format);
558

559
	Error error;
560
	if (!pc.outputs.Play(chunk, error)) {
561
		LogError(error);
562
		buffer.Return(chunk);
563 564 565 566 567 568
		return false;
	}

	return true;
}

569
inline bool
570
Player::SeekDecoder()
571
{
572
	assert(pc.next_song != nullptr);
573

574 575
	pc.outputs.Cancel();

576
	const SongTime start_time = pc.next_song->GetStartTime();
577

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

582
		StopDecoder();
583

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

588
		/* re-start the decoder */
589
		StartDecoder(*pipe);
590
		ActivateDecoder();
591 592 593

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

601
		delete pc.next_song;
602
		pc.next_song = nullptr;
603
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
604

605 606 607
		/* wait for the decoder to complete initialization
		   (just in case that happens to be still in
		   progress) */
608

609 610
		if (!WaitDecoderStartup())
			return false;
611

612
		/* send the SEEK command */
613

614 615 616 617 618 619
		SongTime where = pc.seek_time;
		if (!pc.total_time.IsNegative()) {
			const SongTime total_time(pc.total_time);
			if (where > total_time)
				where = total_time;
		}
Max Kellermann's avatar
Max Kellermann committed
620

621 622
		Error error;
		if (!dc.Seek(where + start_time, error)) {
623
			/* decoder failure */
624
			pc.SetError(PlayerError::DECODER, std::move(error));
625 626 627
			pc.LockCommandFinished();
			return false;
		}
628

629 630
		elapsed_time = where;
	}
631

632
	pc.LockCommandFinished();
633

634
	assert(xfade_state == CrossFadeState::UNKNOWN);
635

636
	/* re-fill the buffer after seeking */
637
	buffering = true;
638 639

	return true;
640 641
}

642
inline void
643
Player::ProcessCommand()
644
{
645
	switch (pc.command) {
646 647 648 649
	case PlayerCommand::NONE:
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
650 651
		break;

652
	case PlayerCommand::UPDATE_AUDIO:
653
		pc.Unlock();
654
		pc.outputs.EnableDisable();
655
		pc.Lock();
656
		pc.CommandFinished();
657 658
		break;

659
	case PlayerCommand::QUEUE:
660
		assert(pc.next_song != nullptr);
661 662
		assert(!queued);
		assert(!IsDecoderAtNextSong());
663

664
		queued = true;
665
		pc.CommandFinished();
666 667 668 669 670 671

		pc.Unlock();
		if (dc.LockIsIdle())
			StartDecoder(*new MusicPipe());
		pc.Lock();

672 673
		break;

674
	case PlayerCommand::PAUSE:
675
		pc.Unlock();
676

677 678
		paused = !paused;
		if (paused) {
679
			pc.outputs.Pause();
680
			pc.Lock();
681

682
			pc.state = PlayerState::PAUSE;
683
		} else if (!play_audio_format.IsDefined()) {
684 685
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
686
			pc.Lock();
687

688
			pc.state = PlayerState::PLAY;
689
		} else {
690
			OpenOutput();
691

692
			pc.Lock();
693
		}
694

695
		pc.CommandFinished();
696 697
		break;

698
	case PlayerCommand::SEEK:
699
		pc.Unlock();
700
		SeekDecoder();
701
		pc.Lock();
702
		break;
703

704
	case PlayerCommand::CANCEL:
705
		if (pc.next_song == nullptr) {
706
			/* the cancel request arrived too late, we're
707 708
			   already playing the queued song...  stop
			   everything now */
709
			pc.command = PlayerCommand::STOP;
710 711 712
			return;
		}

713
		if (IsDecoderAtNextSong()) {
714 715
			/* the decoder is already decoding the song -
			   stop it and reset the position */
716
			pc.Unlock();
717
			StopDecoder();
718
			pc.Lock();
719
		}
720

721
		delete pc.next_song;
722
		pc.next_song = nullptr;
723
		queued = false;
724
		pc.CommandFinished();
725
		break;
726

727
	case PlayerCommand::REFRESH:
728
		if (output_open && !paused) {
729
			pc.Unlock();
730
			pc.outputs.Check();
731
			pc.Lock();
732
		}
733

734 735
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
736
			: elapsed_time;
737

738
		pc.CommandFinished();
739
		break;
740 741 742
	}
}

743
static void
744
update_song_tag(PlayerControl &pc, DetachedSong &song, const Tag &new_tag)
745
{
746
	if (song.IsFile())
747 748 749 750
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

751
	song.SetTag(new_tag);
752

753
	pc.LockSetTaggedSong(song);
754

755 756
	/* the main thread will update the playlist version when he
	   receives this event */
757
	pc.listener.OnPlayerTagModified();
758 759 760 761 762 763

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

764
/**
765
 * Plays a #MusicChunk object (after applying software volume).  If
766 767
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
768 769
 *
 * Player lock is not held.
770
 */
771
static bool
772
play_chunk(PlayerControl &pc,
773
	   DetachedSong &song, MusicChunk *chunk,
774
	   MusicBuffer &buffer,
775
	   const AudioFormat format,
776
	   Error &error)
777
{
778
	assert(chunk->CheckFormat(format));
779

780
	if (chunk->tag != nullptr)
781
		update_song_tag(pc, song, *chunk->tag);
782

783
	if (chunk->IsEmpty()) {
784
		buffer.Return(chunk);
785
		return true;
786
	}
787

788 789 790
	pc.Lock();
	pc.bit_rate = chunk->bit_rate;
	pc.Unlock();
791

792 793
	/* send the chunk to the audio outputs */

794
	if (!pc.outputs.Play(chunk, error))
795
		return false;
796

797
	pc.total_play_time += (double)chunk->length /
798
		format.GetTimeToSize();
799
	return true;
800 801
}

802
inline bool
803
Player::PlayNextChunk()
804
{
805
	if (!pc.outputs.Wait(pc, 64))
806 807
		/* the output pipe is still large enough, don't send
		   another chunk */
808 809
		return true;

810 811 812 813 814 815 816 817 818 819 820
	/* 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;
	}

821
	MusicChunk *chunk = nullptr;
822
	if (xfade_state == CrossFadeState::ACTIVE) {
823 824
		/* perform cross fade */

825 826 827 828
		assert(IsDecoderAtNextSong());

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

830
		MusicChunk *other_chunk = dc.pipe->Shift();
831
		if (other_chunk != nullptr) {
832
			chunk = pipe->Shift();
833 834
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
835

836 837 838
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
839 840
			cross_fade_tag =
				Tag::MergeReplace(cross_fade_tag,
841
						  other_chunk->tag);
842
			other_chunk->tag = nullptr;
843

844
			if (pc.cross_fade.mixramp_delay <= 0) {
845
				chunk->mix_ratio = ((float)cross_fade_position)
846
					     / cross_fade_chunks;
847
			} else {
848
				chunk->mix_ratio = -1;
849
			}
850

851
			if (other_chunk->IsEmpty()) {
852
				/* the "other" chunk was a MusicChunk
853 854 855 856 857 858
				   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 */
859
				buffer.Return(other_chunk);
860
				other_chunk = nullptr;
861
			}
862

863
			chunk->other = other_chunk;
864
		} else {
865
			/* there are not enough decoded chunks yet */
866

867
			pc.Lock();
868

869
			if (dc.IsIdle()) {
870
				/* the decoder isn't running, abort
871
				   cross fading */
872
				pc.Unlock();
873

874
				xfade_state = CrossFadeState::DISABLED;
875
			} else {
876
				/* wait for the decoder */
877 878
				dc.Signal();
				dc.WaitForDecoder();
879
				pc.Unlock();
880

881 882 883 884 885
				return true;
			}
		}
	}

886
	if (chunk == nullptr)
887
		chunk = pipe->Shift();
888

889
	assert(chunk != nullptr);
890

891 892
	/* insert the postponed tag if cross-fading is finished */

893
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
894 895
		chunk->tag = Tag::MergeReplace(chunk->tag, cross_fade_tag);
		cross_fade_tag = nullptr;
896 897
	}

898 899
	/* play the current chunk */

900
	Error error;
901
	if (!play_chunk(pc, *song, chunk, buffer, play_audio_format, error)) {
902
		LogError(error);
903

904
		buffer.Return(chunk);
905

906
		pc.Lock();
907

908
		pc.SetError(PlayerError::OUTPUT, std::move(error));
909

910 911
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
912
		pc.state = PlayerState::PAUSE;
913
		paused = true;
914

915
		pc.Unlock();
916

917 918
		idle_add(IDLE_PLAYER);

919
		return false;
920
	}
921

922 923
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
924
	   larger block at a time */
925
	pc.Lock();
926 927
	if (!dc.IsIdle() &&
	    dc.pipe->GetSize() <= (pc.buffered_before_play +
928 929 930 931 932 933 934
				   buffer.GetSize() * 3) / 4) {
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
935
	pc.Unlock();
936 937 938 939

	return true;
}

940
inline void
941
Player::SongBorder()
942
{
943
	FormatDefault(player_domain, "played \"%s\"", song->GetURI());
944

945
	ReplacePipe(dc.pipe);
946

947
	pc.outputs.SongBorder();
948

949
	ActivateDecoder();
950

951
	pc.Lock();
952

953
	const bool border_pause = pc.border_pause;
954
	if (border_pause) {
955
		paused = true;
956
		pc.state = PlayerState::PAUSE;
957 958
	}

959
	pc.Unlock();
960

961 962
	if (border_pause)
		idle_add(IDLE_PLAYER);
963 964
}

965
inline void
966
Player::Run()
967
{
968
	pipe = new MusicPipe();
969

970
	StartDecoder(*pipe);
971
	ActivateDecoder();
972

973
	pc.Lock();
974
	pc.state = PlayerState::PLAY;
975

976
	pc.CommandFinished();
977

978
	while (true) {
979
		ProcessCommand();
980 981 982
		if (pc.command == PlayerCommand::STOP ||
		    pc.command == PlayerCommand::EXIT ||
		    pc.command == PlayerCommand::CLOSE_AUDIO) {
983
			pc.Unlock();
984
			pc.outputs.Cancel();
985 986 987
			break;
		}

988
		pc.Unlock();
989

990
		if (buffering) {
991 992 993 994
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

995
			if (pipe->GetSize() < pc.buffered_before_play &&
996
			    !dc.LockIsIdle()) {
997
				/* not enough decoded buffer space yet */
998

999
				if (!paused && output_open &&
1000
				    pc.outputs.Check() < 4 &&
1001
				    !SendSilence())
1002 1003
					break;

1004
				pc.Lock();
1005
				/* XXX race condition: check decoder again */
1006
				dc.WaitForDecoder();
1007 1008 1009
				continue;
			} else {
				/* buffering is complete */
1010
				buffering = false;
1011 1012 1013
			}
		}

1014
		if (decoder_starting) {
1015
			/* wait until the decoder is initialized completely */
1016

1017
			if (!CheckDecoderStartup())
1018
				break;
1019

1020
			pc.Lock();
1021
			continue;
1022 1023
		}

1024
#ifndef NDEBUG
1025
		/*
1026
		music_pipe_check_format(&play_audio_format,
1027
					next_song_chunk,
1028
					&dc.out_audio_format);
1029
		*/
1030 1031
#endif

1032
		if (dc.LockIsIdle() && queued && dc.pipe == pipe) {
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

1038
			StartDecoder(*new MusicPipe());
1039
		}
1040

1041 1042
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
1043
		    !pc.border_pause &&
1044
		    IsDecoderAtNextSong() &&
1045
		    xfade_state == CrossFadeState::UNKNOWN &&
1046
		    !dc.LockIsStarting()) {
1047 1048 1049
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
1050
			cross_fade_chunks =
1051
				pc.cross_fade.Calculate(dc.total_time,
1052 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() -
							pc.buffered_before_play);
1060
			if (cross_fade_chunks > 0)
1061
				xfade_state = CrossFadeState::ENABLED;
1062
			else
1063 1064
				/* cross fading is disabled or the
				   next song is too short */
1065
				xfade_state = CrossFadeState::DISABLED;
1066 1067
		}

1068
		if (paused) {
1069
			pc.Lock();
1070

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

1078
			PlayNextChunk();
1079
		} else if (pc.outputs.Check() > 0) {
1080 1081 1082 1083
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1084 1085 1086 1087 1088 1089 1090 1091
			pc.Lock();

			/* wake up the decoder (just in case it's
			   waiting for space in the MusicBuffer) and
			   wait for it */
			dc.Signal();
			dc.WaitForDecoder();
			continue;
1092
		} else if (IsDecoderAtNextSong()) {
1093 1094
			/* at the beginning of a new song */

1095
			SongBorder();
1096
		} else if (dc.LockIsIdle()) {
1097 1098 1099
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1100
			if (pipe->IsEmpty()) {
1101 1102
				/* wait for the hardware to finish
				   playback */
1103
				pc.outputs.Drain();
1104
				break;
1105
			}
1106
		} else if (output_open) {
1107 1108 1109
			/* the decoder is too busy and hasn't provided
			   new PCM data in time: send silence (if the
			   output pipe is empty) */
1110
			if (!SendSilence())
1111 1112
				break;
		}
1113

1114
		pc.Lock();
1115 1116
	}

1117
	StopDecoder();
1118

1119
	ClearAndDeletePipe();
1120

1121
	delete cross_fade_tag;
1122

1123
	if (song != nullptr) {
1124 1125
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
		delete song;
1126
	}
1127

1128
	pc.Lock();
1129

1130 1131
	pc.ClearTaggedSong();

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

1138
	pc.state = PlayerState::STOP;
1139

1140
	pc.Unlock();
1141 1142
}

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

1151 1152
static void
player_task(void *arg)
1153
{
1154
	PlayerControl &pc = *(PlayerControl *)arg;
1155

1156 1157
	SetThreadName("player");

1158
	DecoderControl dc(pc.mutex, pc.cond);
1159
	decoder_thread_start(dc);
1160

1161
	MusicBuffer buffer(pc.buffer_chunks);
1162

1163
	pc.Lock();
1164

1165
	while (1) {
1166
		switch (pc.command) {
1167 1168
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1169
			assert(pc.next_song != nullptr);
1170

1171
			pc.Unlock();
1172
			do_play(pc, dc, buffer);
1173
			pc.listener.OnPlayerSync();
1174
			pc.Lock();
1175 1176
			break;

1177
		case PlayerCommand::STOP:
1178
			pc.Unlock();
1179
			pc.outputs.Cancel();
1180
			pc.Lock();
1181

1182 1183
			/* fall through */

1184
		case PlayerCommand::PAUSE:
1185 1186
			delete pc.next_song;
			pc.next_song = nullptr;
1187

1188
			pc.CommandFinished();
1189 1190
			break;

1191
		case PlayerCommand::CLOSE_AUDIO:
1192
			pc.Unlock();
1193

1194
			pc.outputs.Release();
1195

1196
			pc.Lock();
1197
			pc.CommandFinished();
1198

1199
			assert(buffer.IsEmptyUnsafe());
1200

1201 1202
			break;

1203
		case PlayerCommand::UPDATE_AUDIO:
1204
			pc.Unlock();
1205
			pc.outputs.EnableDisable();
1206
			pc.Lock();
1207
			pc.CommandFinished();
1208 1209
			break;

1210
		case PlayerCommand::EXIT:
1211
			pc.Unlock();
1212

1213 1214
			dc.Quit();

1215
			pc.outputs.Close();
1216

1217
			pc.LockCommandFinished();
1218
			return;
Max Kellermann's avatar
Max Kellermann committed
1219

1220
		case PlayerCommand::CANCEL:
1221 1222
			delete pc.next_song;
			pc.next_song = nullptr;
1223

1224
			pc.CommandFinished();
1225 1226
			break;

1227
		case PlayerCommand::REFRESH:
1228
			/* no-op when not playing */
1229
			pc.CommandFinished();
1230 1231
			break;

1232
		case PlayerCommand::NONE:
1233
			pc.Wait();
1234 1235 1236 1237 1238
			break;
		}
	}
}

1239
void
1240
StartPlayerThread(PlayerControl &pc)
1241
{
1242 1243
	assert(!pc.thread.IsDefined());

1244
	pc.thread.Start(player_task, &pc);
1245
}