Thread.cxx 26.3 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 "system/PeriodClock.hxx"
36
#include "util/Domain.hxx"
37
#include "thread/Name.hxx"
38
#include "Log.hxx"
39

40 41
#include <stdexcept>

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

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

46
class Player {
47
	PlayerControl &pc;
48

49
	DecoderControl &dc;
50

51 52
	MusicBuffer &buffer;

53
	MusicPipe *pipe;
54

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

150 151
	PeriodClock throttle_silence_log;

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

168
private:
169 170 171 172 173 174 175 176
	/**
	 * 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;
	}

177 178 179 180 181 182
	void ClearAndDeletePipe() {
		pipe->Clear(buffer);
		delete pipe;
	}

	void ClearAndReplacePipe(MusicPipe *_pipe) {
183
		ResetCrossFade();
184 185 186 187 188
		ClearAndDeletePipe();
		pipe = _pipe;
	}

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

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

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

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

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

231
				pc.CommandFinished();
232 233 234 235 236 237 238
				return false;
			}
		}

		return true;
	}

239 240 241 242 243 244 245 246 247 248 249 250 251 252
	/**
	 * 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
253
	bool IsDecoderAtCurrentSong() const noexcept {
254 255 256 257 258 259 260 261 262 263 264
		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
265
	bool IsDecoderAtNextSong() const noexcept {
266 267 268 269
		return dc.pipe != nullptr && !IsDecoderAtCurrentSong();
	}

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

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

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

	/**
300 301
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
302
	 *
303 304
	 * Caller must lock the mutex.
	 *
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 335 336 337
	 * @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.
	 */
338
	void SongBorder();
339

340
public:
341 342 343 344 345 346
	/*
	 * 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();
347 348
};

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

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

361
	SongTime start_time = pc.next_song->GetStartTime() + pc.seek_time;
362

363
	dc.Start(new DetachedSong(*pc.next_song),
364
		 start_time, pc.next_song->GetEndTime(),
365
		 buffer, _pipe);
366 367
}

368
void
369
Player::StopDecoder()
370
{
371
	dc.Stop();
372

373
	if (dc.pipe != nullptr) {
374 375
		/* clear and free the decoder pipe */

376
		dc.pipe->Clear(buffer);
377

378
		if (dc.pipe != pipe)
379
			delete dc.pipe;
380

381
		dc.pipe = nullptr;
382 383 384 385 386

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

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

	return true;
}

403
void
404
Player::ActivateDecoder()
405
{
406
	assert(queued || pc.command == PlayerCommand::SEEK);
407
	assert(pc.next_song != nullptr);
408

409
	queued = false;
410

411
	{
412
		const std::lock_guard<Mutex> lock(pc.mutex);
413

414
		pc.ClearTaggedSong();
415

416 417 418
		delete song;
		song = pc.next_song;
		pc.next_song = nullptr;
419

420
		elapsed_time = pc.seek_time;
421

422 423 424
		/* set the "starting" flag, which will be cleared by
		   player_check_decoder_startup() */
		decoder_starting = true;
425

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

432
	/* call syncPlaylistWithQueue() in the main thread */
433
	pc.listener.OnPlayerSync();
434 435
}

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

448 449
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
450

451 452
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
453

454
	return SignedSongTime(SongTime(decoder_duration) - start_time);
455 456
}

457
bool
458
Player::OpenOutput()
459
{
460
	assert(play_audio_format.IsDefined());
461 462
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);
463

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

470
		output_open = false;
471

472 473
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
474
		paused = true;
475

476
		pc.SetOutputError(std::current_exception());
477

478 479
		idle_add(IDLE_PLAYER);

480 481
		return false;
	}
482 483 484 485

	output_open = true;
	paused = false;

486
	pc.state = PlayerState::PLAY;
487 488 489 490

	idle_add(IDLE_PLAYER);

	return true;
491 492
}

493
bool
494
Player::CheckDecoderStartup()
495
{
496
	assert(decoder_starting);
497

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

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

510 511 512
		pc.total_time = real_song_duration(*dc.song,
						   dc.total_time);
		pc.audio_format = dc.in_audio_format;
513 514
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
515

516 517
		idle_add(IDLE_PLAYER);

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

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

		return true;
	}
}

536
bool
537
Player::SendSilence()
538
{
539 540
	assert(output_open);
	assert(play_audio_format.IsDefined());
541

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

#ifndef NDEBUG
553
	chunk->audio_format = play_audio_format;
554 555
#endif

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

561
	chunk->bit_rate = 0;
562
	chunk->time = SignedSongTime::Negative(); /* undefined time stamp */
563
	chunk->length = num_frames * frame_size;
564
	chunk->replay_gain_serial = MusicChunk::IGNORE_REPLAY_GAIN;
565
	PcmSilence({chunk->data, chunk->length}, play_audio_format.format);
566

567 568 569 570
	try {
		pc.outputs.Play(chunk);
	} catch (const std::runtime_error &e) {
		LogError(e);
571
		buffer.Return(chunk);
572 573 574 575 576 577
		return false;
	}

	return true;
}

578
inline bool
579
Player::SeekDecoder()
580
{
581
	assert(pc.next_song != nullptr);
582

583 584
	pc.outputs.Cancel();

585
	const SongTime start_time = pc.next_song->GetStartTime();
586

587
	if (!dc.LockIsCurrentSong(*pc.next_song)) {
588 589 590
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

591
		StopDecoder();
592

593 594
		/* clear music chunks which might still reside in the
		   pipe */
595
		pipe->Clear(buffer);
596

597
		/* re-start the decoder */
598
		StartDecoder(*pipe);
599
		ActivateDecoder();
600 601 602

		if (!WaitDecoderStartup())
			return false;
603
	} else {
604
		if (!IsDecoderAtCurrentSong()) {
605 606
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
607
			ClearAndReplacePipe(dc.pipe);
608 609
		}

610
		delete pc.next_song;
611
		pc.next_song = nullptr;
612
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
613

614 615 616
		/* wait for the decoder to complete initialization
		   (just in case that happens to be still in
		   progress) */
617

618 619
		if (!WaitDecoderStartup())
			return false;
620

621
		/* send the SEEK command */
622

623 624 625 626 627 628
		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
629

630 631 632
		try {
			dc.Seek(where + start_time);
		} catch (...) {
633
			/* decoder failure */
634 635
			pc.SetError(PlayerError::DECODER,
				    std::current_exception());
636 637 638
			pc.LockCommandFinished();
			return false;
		}
639

640 641
		elapsed_time = where;
	}
642

643
	pc.LockCommandFinished();
644

645
	assert(xfade_state == CrossFadeState::UNKNOWN);
646

647
	/* re-fill the buffer after seeking */
648
	buffering = true;
649 650

	return true;
651 652
}

653
inline void
654
Player::ProcessCommand()
655
{
656
	switch (pc.command) {
657 658 659 660
	case PlayerCommand::NONE:
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
661 662
		break;

663
	case PlayerCommand::UPDATE_AUDIO:
664 665 666 667 668
		{
			const ScopeUnlock unlock(pc.mutex);
			pc.outputs.EnableDisable();
		}

669
		pc.CommandFinished();
670 671
		break;

672
	case PlayerCommand::QUEUE:
673
		assert(pc.next_song != nullptr);
674 675
		assert(!queued);
		assert(!IsDecoderAtNextSong());
676

677
		queued = true;
678
		pc.CommandFinished();
679

680 681 682 683 684
		{
			const ScopeUnlock unlock(pc.mutex);
			if (dc.LockIsIdle())
				StartDecoder(*new MusicPipe());
		}
685

686 687
		break;

688
	case PlayerCommand::PAUSE:
689 690
		paused = !paused;
		if (paused) {
691
			pc.state = PlayerState::PAUSE;
692 693 694

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

703
		pc.CommandFinished();
704 705
		break;

706
	case PlayerCommand::SEEK:
707 708 709 710
		{
			const ScopeUnlock unlock(pc.mutex);
			SeekDecoder();
		}
711
		break;
712

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

722
		if (IsDecoderAtNextSong()) {
723 724
			/* the decoder is already decoding the song -
			   stop it and reset the position */
725
			const ScopeUnlock unlock(pc.mutex);
726
			StopDecoder();
727
		}
728

729
		delete pc.next_song;
730
		pc.next_song = nullptr;
731
		queued = false;
732
		pc.CommandFinished();
733
		break;
734

735
	case PlayerCommand::REFRESH:
736
		if (output_open && !paused) {
737
			const ScopeUnlock unlock(pc.mutex);
738
			pc.outputs.Check();
739
		}
740

741 742
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
743
			: elapsed_time;
744

745
		pc.CommandFinished();
746
		break;
747 748 749
	}
}

750
static void
751
update_song_tag(PlayerControl &pc, DetachedSong &song, const Tag &new_tag)
752
{
753
	if (song.IsFile())
754 755 756 757
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

758
	song.SetTag(new_tag);
759

760
	pc.LockSetTaggedSong(song);
761

762 763
	/* the main thread will update the playlist version when he
	   receives this event */
764
	pc.listener.OnPlayerTagModified();
765 766 767 768 769 770

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

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

786
	if (chunk->tag != nullptr)
787
		update_song_tag(pc, song, *chunk->tag);
788

789
	if (chunk->IsEmpty()) {
790
		buffer.Return(chunk);
791
		return;
792
	}
793

794
	{
795
		const std::lock_guard<Mutex> lock(pc.mutex);
796 797
		pc.bit_rate = chunk->bit_rate;
	}
798

799 800
	/* send the chunk to the audio outputs */

801
	pc.outputs.Play(chunk);
802
	pc.total_play_time += (double)chunk->length /
803
		format.GetTimeToSize();
804 805
}

806
inline bool
807
Player::PlayNextChunk()
808
{
809
	if (!pc.LockWaitOutputConsumed(64))
810 811
		/* the output pipe is still large enough, don't send
		   another chunk */
812 813
		return true;

814 815 816 817 818 819 820 821 822 823 824
	/* 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;
	}

825
	MusicChunk *chunk = nullptr;
826
	if (xfade_state == CrossFadeState::ACTIVE) {
827 828
		/* perform cross fade */

829 830 831 832
		assert(IsDecoderAtNextSong());

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

834
		MusicChunk *other_chunk = dc.pipe->Shift();
835
		if (other_chunk != nullptr) {
836
			chunk = pipe->Shift();
837 838
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
839

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

848
			if (pc.cross_fade.mixramp_delay <= 0) {
849
				chunk->mix_ratio = ((float)cross_fade_position)
850
					     / cross_fade_chunks;
851
			} else {
852
				chunk->mix_ratio = -1;
853
			}
854

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

867
			chunk->other = other_chunk;
868
		} else {
869
			/* there are not enough decoded chunks yet */
870

871
			const std::lock_guard<Mutex> lock(pc.mutex);
872

873
			if (dc.IsIdle()) {
874
				/* the decoder isn't running, abort
875
				   cross fading */
876
				xfade_state = CrossFadeState::DISABLED;
877
			} else {
878
				/* wait for the decoder */
879 880
				dc.Signal();
				dc.WaitForDecoder();
881

882 883 884 885 886
				return true;
			}
		}
	}

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

890
	assert(chunk != nullptr);
891

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

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

899 900
	/* play the current chunk */

901 902 903 904
	try {
		play_chunk(pc, *song, chunk, buffer, play_audio_format);
	} catch (const std::runtime_error &e) {
		LogError(e);
905

906
		buffer.Return(chunk);
907 908 909

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

912
		pc.LockSetOutputError(std::current_exception());
913

914 915
		idle_add(IDLE_PLAYER);

916
		return false;
917
	}
918

919
	const std::lock_guard<Mutex> lock(pc.mutex);
920

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

	return true;
}

937
inline void
938
Player::SongBorder()
939
{
940
	FormatDefault(player_domain, "played \"%s\"", song->GetURI());
941

942 943
	throttle_silence_log.Reset();

944
	ReplacePipe(dc.pipe);
945

946
	pc.outputs.SongBorder();
947

948
	ActivateDecoder();
949

950
	const bool border_pause = pc.LockApplyBorderPause();
951
	if (border_pause) {
952
		paused = true;
953
		idle_add(IDLE_PLAYER);
954
	}
955 956
}

957
inline void
958
Player::Run()
959
{
960
	pipe = new MusicPipe();
961

962
	StartDecoder(*pipe);
963
	ActivateDecoder();
964

965
	pc.Lock();
966
	pc.state = PlayerState::PLAY;
967

968
	pc.CommandFinished();
969

970
	while (true) {
971
		ProcessCommand();
972 973 974
		if (pc.command == PlayerCommand::STOP ||
		    pc.command == PlayerCommand::EXIT ||
		    pc.command == PlayerCommand::CLOSE_AUDIO) {
975
			pc.Unlock();
976
			pc.outputs.Cancel();
977 978 979
			break;
		}

980
		pc.Unlock();
981

982
		if (buffering) {
983 984 985 986
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

987
			if (pipe->GetSize() < pc.buffered_before_play &&
988
			    !dc.LockIsIdle()) {
989
				/* not enough decoded buffer space yet */
990

991
				if (!paused && output_open &&
992
				    pc.outputs.Check() < 4 &&
993
				    !SendSilence())
994 995
					break;

996
				pc.Lock();
997
				/* XXX race condition: check decoder again */
998
				dc.WaitForDecoder();
999 1000 1001
				continue;
			} else {
				/* buffering is complete */
1002
				buffering = false;
1003 1004 1005
			}
		}

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

1009 1010 1011 1012
			pc.Lock();

			if (!CheckDecoderStartup()) {
				pc.Unlock();
1013
				break;
1014
			}
1015

1016
			continue;
1017 1018
		}

1019
#ifndef NDEBUG
1020
		/*
1021
		music_pipe_check_format(&play_audio_format,
1022
					next_song_chunk,
1023
					&dc.out_audio_format);
1024
		*/
1025 1026
#endif

1027
		if (dc.LockIsIdle() && queued && dc.pipe == pipe) {
1028 1029
			/* the decoder has finished the current song;
			   make it decode the next song */
1030

1031
			assert(dc.pipe == nullptr || dc.pipe == pipe);
1032

1033
			StartDecoder(*new MusicPipe());
1034
		}
1035

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

1063
		if (paused) {
1064
			pc.Lock();
1065

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

1073
			PlayNextChunk();
1074
		} else if (pc.outputs.Check() > 0) {
1075 1076 1077 1078
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1079 1080 1081 1082 1083 1084 1085 1086
			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;
1087
		} else if (IsDecoderAtNextSong()) {
1088 1089
			/* at the beginning of a new song */

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

			if (throttle_silence_log.CheckUpdate(std::chrono::seconds(5)))
				FormatWarning(player_domain, "Decoder is too slow; playing silence to avoid xrun");

1109
			if (!SendSilence())
1110 1111
				break;
		}
1112

1113
		pc.Lock();
1114 1115
	}

1116
	StopDecoder();
1117

1118
	ClearAndDeletePipe();
1119

1120
	delete cross_fade_tag;
1121

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

1127
	pc.Lock();
1128

1129 1130
	pc.ClearTaggedSong();

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

1137
	pc.state = PlayerState::STOP;
1138

1139
	pc.Unlock();
1140 1141
}

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

1150 1151
void
PlayerControl::RunThread()
1152
{
1153 1154
	SetThreadName("player");

1155 1156 1157
	DecoderControl dc(mutex, cond,
			  configured_audio_format,
			  replay_gain_config);
1158
	decoder_thread_start(dc);
1159

1160
	MusicBuffer buffer(buffer_chunks);
1161

1162
	Lock();
1163

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

1170 1171 1172 1173
			Unlock();
			do_play(*this, dc, buffer);
			listener.OnPlayerSync();
			Lock();
1174 1175
			break;

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

1181 1182
			/* fall through */

1183
		case PlayerCommand::PAUSE:
1184 1185
			delete next_song;
			next_song = nullptr;
1186

1187
			CommandFinished();
1188 1189
			break;

1190
		case PlayerCommand::CLOSE_AUDIO:
1191
			Unlock();
1192

1193
			outputs.Release();
1194

1195 1196
			Lock();
			CommandFinished();
1197

1198
			assert(buffer.IsEmptyUnsafe());
1199

1200 1201
			break;

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

1209
		case PlayerCommand::EXIT:
1210
			Unlock();
1211

1212 1213
			dc.Quit();

1214
			outputs.Close();
1215

1216
			LockCommandFinished();
1217
			return;
Max Kellermann's avatar
Max Kellermann committed
1218

1219
		case PlayerCommand::CANCEL:
1220 1221
			delete next_song;
			next_song = nullptr;
1222

1223
			CommandFinished();
1224 1225
			break;

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

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

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

1243
	pc.thread.Start();
1244
}