Thread.cxx 25.9 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 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 "thread/Name.hxx"
37
#include "Log.hxx"
38

39 40
#include <stdexcept>

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
	MusicPipe *pipe;
53

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

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

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

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

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

81 82 83 84 85 86 87 88
	/**
	 * 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;

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

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

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

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

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

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

128 129 130 131 132
	/**
	 * 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
133
	Tag *cross_fade_tag;
134

135 136 137
	/**
	 * The current audio format for the audio outputs.
	 */
138
	AudioFormat play_audio_format;
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;
148

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

165
private:
166 167 168 169 170 171 172 173
	/**
	 * 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;
	}

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

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

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

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

	/**
	 * The decoder has acknowledged the "START" command (see
200
	 * ActivateDecoder()).  This function checks if the decoder
201 202
	 * initialization has completed yet.
	 *
203
	 * Caller must lock the mutex.
204 205 206
	 */
	bool CheckDecoderStartup();

207 208 209 210 211 212 213 214 215
	/**
	 * 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() {
216
		const std::lock_guard<Mutex> lock(pc.mutex);
217

218 219
		while (decoder_starting) {
			if (!CheckDecoderStartup()) {
220 221 222
				/* if decoder startup fails, make sure
				   the previous song is not being
				   played anymore */
223 224 225 226
				{
					const ScopeUnlock unlock(pc.mutex);
					pc.outputs.Cancel();
				}
227

228
				pc.CommandFinished();
229 230 231 232 233 234 235
				return false;
			}
		}

		return true;
	}

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 261 262 263 264 265 266
	/**
	 * 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();
	}

	/**
267
	 * This is the handler for the #PlayerCommand::SEEK command.
268 269 270 271 272
	 *
	 * The player lock is not held.
	 */
	bool SeekDecoder();

273 274 275 276 277 278 279 280
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
	bool ForwardDecoderError();

281
	/**
282 283 284 285 286 287 288 289 290
	 * 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().
291 292 293
	 *
	 * The player lock is not held.
	 */
294
	void ActivateDecoder();
295 296

	/**
297 298
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
299
	 *
300 301
	 * Caller must lock the mutex.
	 *
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 327 328 329 330 331 332 333 334
	 * @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.
	 */
335
	void SongBorder();
336

337
public:
338 339 340 341 342 343
	/*
	 * 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();
344 345
};

346
void
347
Player::StartDecoder(MusicPipe &_pipe)
348
{
349
	assert(queued || pc.command == PlayerCommand::SEEK);
350
	assert(pc.next_song != nullptr);
351

352 353
	{
		/* copy ReplayGain parameters to the decoder */
354
		const std::lock_guard<Mutex> protect(pc.mutex);
355 356 357
		dc.replay_gain_mode = pc.replay_gain_mode;
	}

358
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
359

360
	dc.Start(new DetachedSong(*pc.next_song),
361
		 start_time, pc.next_song->GetEndTime(),
362
		 buffer, _pipe);
363 364
}

365
void
366
Player::StopDecoder()
367
{
368
	dc.Stop();
369

370
	if (dc.pipe != nullptr) {
371 372
		/* clear and free the decoder pipe */

373
		dc.pipe->Clear(buffer);
374

375
		if (dc.pipe != pipe)
376
			delete dc.pipe;
377

378
		dc.pipe = nullptr;
379 380 381 382 383

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

387 388 389
bool
Player::ForwardDecoderError()
{
390 391 392 393
	try {
		dc.CheckRethrowError();
	} catch (...) {
		pc.SetError(PlayerError::DECODER, std::current_exception());
394 395 396 397 398 399
		return false;
	}

	return true;
}

400
void
401
Player::ActivateDecoder()
402
{
403
	assert(queued || pc.command == PlayerCommand::SEEK);
404
	assert(pc.next_song != nullptr);
405

406
	queued = false;
407

408
	{
409
		const std::lock_guard<Mutex> lock(pc.mutex);
410

411
		pc.ClearTaggedSong();
412

413 414 415
		delete song;
		song = pc.next_song;
		pc.next_song = nullptr;
416

417
		elapsed_time = pc.seek_time;
418

419 420 421
		/* set the "starting" flag, which will be cleared by
		   player_check_decoder_startup() */
		decoder_starting = true;
422

423 424 425 426 427
		/* update PlayerControl's song information */
		pc.total_time = song->GetDuration();
		pc.bit_rate = 0;
		pc.audio_format.Clear();
	}
428

429
	/* call syncPlaylistWithQueue() in the main thread */
430
	pc.listener.OnPlayerSync();
431 432
}

433 434 435 436
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
437 438
static SignedSongTime
real_song_duration(const DetachedSong &song, SignedSongTime decoder_duration)
439
{
440
	if (decoder_duration.IsNegative())
441
		/* the decoder plugin didn't provide information; fall
442
		   back to Song::GetDuration() */
443
		return song.GetDuration();
444

445 446
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
447

448 449
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
450

451
	return SignedSongTime(SongTime(decoder_duration) - start_time);
452 453
}

454
bool
455
Player::OpenOutput()
456
{
457
	assert(play_audio_format.IsDefined());
458 459
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);
460

461
	try {
462
		const ScopeUnlock unlock(pc.mutex);
463 464 465
		pc.outputs.Open(play_audio_format, buffer);
	} catch (const std::runtime_error &e) {
		LogError(e);
466

467
		output_open = false;
468

469 470
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
471
		paused = true;
472

473
		pc.SetOutputError(std::current_exception());
474

475 476
		idle_add(IDLE_PLAYER);

477 478
		return false;
	}
479 480 481 482

	output_open = true;
	paused = false;

483
	pc.state = PlayerState::PLAY;
484 485 486 487

	idle_add(IDLE_PLAYER);

	return true;
488 489
}

490
bool
491
Player::CheckDecoderStartup()
492
{
493
	assert(decoder_starting);
494

495
	if (!ForwardDecoderError()) {
496 497
		/* the decoder failed */
		return false;
498
	} else if (!dc.IsStarting()) {
499
		/* the decoder is ready and ok */
500

501
		if (output_open &&
502
		    !pc.WaitOutputConsumed(1))
503 504 505 506
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

507 508 509
		pc.total_time = real_song_duration(*dc.song,
						   dc.total_time);
		pc.audio_format = dc.in_audio_format;
510 511
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
512

513 514
		idle_add(IDLE_PLAYER);

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

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
527
		dc.WaitForDecoder();
528 529 530 531 532

		return true;
	}
}

533
bool
534
Player::SendSilence()
535
{
536 537
	assert(output_open);
	assert(play_audio_format.IsDefined());
538

539
	MusicChunk *chunk = buffer.Allocate();
540
	if (chunk == nullptr) {
541 542 543 544 545 546
		/* 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;
547 548 549
	}

#ifndef NDEBUG
550
	chunk->audio_format = play_audio_format;
551 552
#endif

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

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

562 563 564 565
	try {
		pc.outputs.Play(chunk);
	} catch (const std::runtime_error &e) {
		LogError(e);
566
		buffer.Return(chunk);
567 568 569 570 571 572
		return false;
	}

	return true;
}

573
inline bool
574
Player::SeekDecoder()
575
{
576
	assert(pc.next_song != nullptr);
577

578 579
	pc.outputs.Cancel();

580
	const SongTime start_time = pc.next_song->GetStartTime();
581

582
	if (!dc.LockIsCurrentSong(*pc.next_song)) {
583 584 585
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

586
		StopDecoder();
587

588 589
		/* clear music chunks which might still reside in the
		   pipe */
590
		pipe->Clear(buffer);
591

592
		/* re-start the decoder */
593
		StartDecoder(*pipe);
594
		ActivateDecoder();
595 596 597

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

605
		delete pc.next_song;
606
		pc.next_song = nullptr;
607
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
608

609 610 611
		/* wait for the decoder to complete initialization
		   (just in case that happens to be still in
		   progress) */
612

613 614
		if (!WaitDecoderStartup())
			return false;
615

616
		/* send the SEEK command */
617

618 619 620 621 622 623
		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
624

625 626 627
		try {
			dc.Seek(where + start_time);
		} catch (...) {
628
			/* decoder failure */
629 630
			pc.SetError(PlayerError::DECODER,
				    std::current_exception());
631 632 633
			pc.LockCommandFinished();
			return false;
		}
634

635 636
		elapsed_time = where;
	}
637

638
	pc.LockCommandFinished();
639

640
	assert(xfade_state == CrossFadeState::UNKNOWN);
641

642
	/* re-fill the buffer after seeking */
643
	buffering = true;
644 645

	return true;
646 647
}

648
inline void
649
Player::ProcessCommand()
650
{
651
	switch (pc.command) {
652 653 654 655
	case PlayerCommand::NONE:
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
656 657
		break;

658
	case PlayerCommand::UPDATE_AUDIO:
659 660 661 662 663
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

664
		pc.CommandFinished();
665 666
		break;

667
	case PlayerCommand::QUEUE:
668
		assert(pc.next_song != nullptr);
669 670
		assert(!queued);
		assert(!IsDecoderAtNextSong());
671

672
		queued = true;
673
		pc.CommandFinished();
674

675 676 677 678 679
		{
			const ScopeUnlock unlock(pc.mutex);
			if (dc.LockIsIdle())
				StartDecoder(*new MusicPipe());
		}
680

681 682
		break;

683
	case PlayerCommand::PAUSE:
684 685
		paused = !paused;
		if (paused) {
686
			pc.state = PlayerState::PAUSE;
687 688 689

			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.Pause();
690
		} else if (!play_audio_format.IsDefined()) {
691 692
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
693
			pc.state = PlayerState::PLAY;
694
		} else {
695
			OpenOutput();
696
		}
697

698
		pc.CommandFinished();
699 700
		break;

701
	case PlayerCommand::SEEK:
702 703 704 705
		{
			const ScopeUnlock unlock(pc.mutex);
			SeekDecoder();
		}
706
		break;
707

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

717
		if (IsDecoderAtNextSong()) {
718 719
			/* the decoder is already decoding the song -
			   stop it and reset the position */
720
			const ScopeUnlock unlock(pc.mutex);
721
			StopDecoder();
722
		}
723

724
		delete pc.next_song;
725
		pc.next_song = nullptr;
726
		queued = false;
727
		pc.CommandFinished();
728
		break;
729

730
	case PlayerCommand::REFRESH:
731
		if (output_open && !paused) {
732
			const ScopeUnlock unlock(pc.mutex);
733
			pc.outputs.Check();
734
		}
735

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

740
		pc.CommandFinished();
741
		break;
742 743 744
	}
}

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

753
	song.SetTag(new_tag);
754

755
	pc.LockSetTaggedSong(song);
756

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

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

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

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

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

789
	{
790
		const std::lock_guard<Mutex> lock(pc.mutex);
791 792
		pc.bit_rate = chunk->bit_rate;
	}
793

794 795
	/* send the chunk to the audio outputs */

796
	pc.outputs.Play(chunk);
797
	pc.total_play_time += (double)chunk->length /
798
		format.GetTimeToSize();
799 800
}

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

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

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

824 825 826 827
		assert(IsDecoderAtNextSong());

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

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

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

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

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

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

866
			const std::lock_guard<Mutex> lock(pc.mutex);
867

868
			if (dc.IsIdle()) {
869
				/* the decoder isn't running, abort
870
				   cross fading */
871
				xfade_state = CrossFadeState::DISABLED;
872
			} else {
873
				/* wait for the decoder */
874 875
				dc.Signal();
				dc.WaitForDecoder();
876

877 878 879 880 881
				return true;
			}
		}
	}

882
	if (chunk == nullptr)
883
		chunk = pipe->Shift();
884

885
	assert(chunk != nullptr);
886

887 888
	/* insert the postponed tag if cross-fading is finished */

889
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
890 891
		chunk->tag = Tag::MergeReplace(chunk->tag, cross_fade_tag);
		cross_fade_tag = nullptr;
892 893
	}

894 895
	/* play the current chunk */

896 897 898 899
	try {
		play_chunk(pc, *song, chunk, buffer, play_audio_format);
	} catch (const std::runtime_error &e) {
		LogError(e);
900

901
		buffer.Return(chunk);
902 903 904

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

907
		pc.LockSetOutputError(std::current_exception());
908

909 910
		idle_add(IDLE_PLAYER);

911
		return false;
912
	}
913

914
	const std::lock_guard<Mutex> lock(pc.mutex);
915

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

	return true;
}

932
inline void
933
Player::SongBorder()
934
{
935
	FormatDefault(player_domain, "played \"%s\"", song->GetURI());
936

937
	ReplacePipe(dc.pipe);
938

939
	pc.outputs.SongBorder();
940

941
	ActivateDecoder();
942

943
	const bool border_pause = pc.LockApplyBorderPause();
944
	if (border_pause) {
945
		paused = true;
946
		idle_add(IDLE_PLAYER);
947
	}
948 949
}

950
inline void
951
Player::Run()
952
{
953
	pipe = new MusicPipe();
954

955
	StartDecoder(*pipe);
956
	ActivateDecoder();
957

958
	pc.Lock();
959
	pc.state = PlayerState::PLAY;
960

961
	pc.CommandFinished();
962

963
	while (true) {
964
		ProcessCommand();
965 966 967
		if (pc.command == PlayerCommand::STOP ||
		    pc.command == PlayerCommand::EXIT ||
		    pc.command == PlayerCommand::CLOSE_AUDIO) {
968
			pc.Unlock();
969
			pc.outputs.Cancel();
970 971 972
			break;
		}

973
		pc.Unlock();
974

975
		if (buffering) {
976 977 978 979
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

980
			if (pipe->GetSize() < pc.buffered_before_play &&
981
			    !dc.LockIsIdle()) {
982
				/* not enough decoded buffer space yet */
983

984
				if (!paused && output_open &&
985
				    pc.outputs.Check() < 4 &&
986
				    !SendSilence())
987 988
					break;

989
				pc.Lock();
990
				/* XXX race condition: check decoder again */
991
				dc.WaitForDecoder();
992 993 994
				continue;
			} else {
				/* buffering is complete */
995
				buffering = false;
996 997 998
			}
		}

999
		if (decoder_starting) {
1000
			/* wait until the decoder is initialized completely */
1001

1002 1003 1004 1005
			pc.Lock();

			if (!CheckDecoderStartup()) {
				pc.Unlock();
1006
				break;
1007
			}
1008

1009
			continue;
1010 1011
		}

1012
#ifndef NDEBUG
1013
		/*
1014
		music_pipe_check_format(&play_audio_format,
1015
					next_song_chunk,
1016
					&dc.out_audio_format);
1017
		*/
1018 1019
#endif

1020
		if (dc.LockIsIdle() && queued && dc.pipe == pipe) {
1021 1022
			/* the decoder has finished the current song;
			   make it decode the next song */
1023

1024
			assert(dc.pipe == nullptr || dc.pipe == pipe);
1025

1026
			StartDecoder(*new MusicPipe());
1027
		}
1028

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

1056
		if (paused) {
1057
			pc.Lock();
1058

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

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

1072 1073 1074 1075 1076 1077 1078 1079
			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;
1080
		} else if (IsDecoderAtNextSong()) {
1081 1082
			/* at the beginning of a new song */

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

1102
		pc.Lock();
1103 1104
	}

1105
	StopDecoder();
1106

1107
	ClearAndDeletePipe();
1108

1109
	delete cross_fade_tag;
1110

1111
	if (song != nullptr) {
1112 1113
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
		delete song;
1114
	}
1115

1116
	pc.Lock();
1117

1118 1119
	pc.ClearTaggedSong();

1120
	if (queued) {
1121
		assert(pc.next_song != nullptr);
1122
		delete pc.next_song;
1123
		pc.next_song = nullptr;
1124 1125
	}

1126
	pc.state = PlayerState::STOP;
1127

1128
	pc.Unlock();
1129 1130
}

1131
static void
1132
do_play(PlayerControl &pc, DecoderControl &dc,
1133 1134
	MusicBuffer &buffer)
{
1135
	Player player(pc, dc, buffer);
1136 1137 1138
	player.Run();
}

1139 1140
void
PlayerControl::RunThread()
1141
{
1142 1143
	SetThreadName("player");

1144 1145 1146
	DecoderControl dc(mutex, cond,
			  configured_audio_format,
			  replay_gain_config);
1147
	decoder_thread_start(dc);
1148

1149
	MusicBuffer buffer(buffer_chunks);
1150

1151
	Lock();
1152

1153
	while (1) {
1154
		switch (command) {
1155 1156
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1157
			assert(next_song != nullptr);
1158

1159 1160 1161 1162
			Unlock();
			do_play(*this, dc, buffer);
			listener.OnPlayerSync();
			Lock();
1163 1164
			break;

1165
		case PlayerCommand::STOP:
1166 1167 1168
			Unlock();
			outputs.Cancel();
			Lock();
1169

1170 1171
			/* fall through */

1172
		case PlayerCommand::PAUSE:
1173 1174
			delete next_song;
			next_song = nullptr;
1175

1176
			CommandFinished();
1177 1178
			break;

1179
		case PlayerCommand::CLOSE_AUDIO:
1180
			Unlock();
1181

1182
			outputs.Release();
1183

1184 1185
			Lock();
			CommandFinished();
1186

1187
			assert(buffer.IsEmptyUnsafe());
1188

1189 1190
			break;

1191
		case PlayerCommand::UPDATE_AUDIO:
1192 1193 1194 1195
			Unlock();
			outputs.EnableDisable();
			Lock();
			CommandFinished();
1196 1197
			break;

1198
		case PlayerCommand::EXIT:
1199
			Unlock();
1200

1201 1202
			dc.Quit();

1203
			outputs.Close();
1204

1205
			LockCommandFinished();
1206
			return;
Max Kellermann's avatar
Max Kellermann committed
1207

1208
		case PlayerCommand::CANCEL:
1209 1210
			delete next_song;
			next_song = nullptr;
1211

1212
			CommandFinished();
1213 1214
			break;

1215
		case PlayerCommand::REFRESH:
1216
			/* no-op when not playing */
1217
			CommandFinished();
1218 1219
			break;

1220
		case PlayerCommand::NONE:
1221
			Wait();
1222 1223 1224 1225 1226
			break;
		}
	}
}

1227
void
1228
StartPlayerThread(PlayerControl &pc)
1229
{
1230 1231
	assert(!pc.thread.IsDefined());

1232
	pc.thread.Start();
1233
}