Thread.cxx 25.6 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2015 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 "DetachedSong.hxx"
29
#include "system/FatalError.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

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

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

43
class Player {
44
	PlayerControl &pc;
45

46
	DecoderControl &dc;
47

48 49
	MusicBuffer &buffer;

50
	MusicPipe *pipe;
51

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
	/**
	 * 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()) {
				pc.LockCommandFinished();
				return false;
			}
		}

		return true;
	}

224 225 226 227 228 229 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
	/**
	 * 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();
	}

	/**
255
	 * This is the handler for the #PlayerCommand::SEEK command.
256 257 258 259 260
	 *
	 * The player lock is not held.
	 */
	bool SeekDecoder();

261 262 263 264 265 266 267 268
	/**
	 * Check if the decoder has reported an error, and forward it
	 * to PlayerControl::SetError().
	 *
	 * @return false if an error has occurred
	 */
	bool ForwardDecoderError();

269
	/**
270 271 272 273 274 275 276 277 278
	 * 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().
279 280 281
	 *
	 * The player lock is not held.
	 */
282
	void ActivateDecoder();
283 284

	/**
285 286
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
287 288 289 290 291 292 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
	 *
	 * @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.
	 */
321
	void SongBorder();
322

323
public:
324 325 326 327 328 329
	/*
	 * 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();
330 331
};

332
void
333
Player::StartDecoder(MusicPipe &_pipe)
334
{
335
	assert(queued || pc.command == PlayerCommand::SEEK);
336
	assert(pc.next_song != nullptr);
337

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

340
	dc.Start(new DetachedSong(*pc.next_song),
341
		 start_time, pc.next_song->GetEndTime(),
342
		 buffer, _pipe);
343 344
}

345
void
346
Player::StopDecoder()
347
{
348
	dc.Stop();
349

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

353
		dc.pipe->Clear(buffer);
354

355
		if (dc.pipe != pipe)
356
			delete dc.pipe;
357

358
		dc.pipe = nullptr;
359 360 361 362 363

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

367 368 369 370 371 372 373 374 375 376 377 378
bool
Player::ForwardDecoderError()
{
	Error error = dc.GetError();
	if (error.IsDefined()) {
		pc.SetError(PlayerError::DECODER, std::move(error));
		return false;
	}

	return true;
}

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

385
	queued = false;
386

387
	pc.Lock();
388 389
	pc.ClearTaggedSong();

390
	delete song;
391
	song = pc.next_song;
392 393
	pc.next_song = nullptr;

394
	elapsed_time = pc.seek_time;
395 396 397

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

400
	/* update PlayerControl's song information */
401
	pc.total_time = song->GetDuration();
402 403
	pc.bit_rate = 0;
	pc.audio_format.Clear();
404

405
	pc.Unlock();
406

407
	/* call syncPlaylistWithQueue() in the main thread */
408
	pc.listener.OnPlayerSync();
409 410
}

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

423 424
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
425

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

429
	return SignedSongTime(SongTime(decoder_duration) - start_time);
430 431
}

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

439
	Error error;
440
	if (pc.outputs.Open(play_audio_format, buffer, error)) {
441 442
		output_open = true;
		paused = false;
443

444
		pc.Lock();
445
		pc.state = PlayerState::PLAY;
446
		pc.Unlock();
447

448 449
		idle_add(IDLE_PLAYER);

450 451
		return true;
	} else {
452
		LogError(error);
453

454
		output_open = false;
455

456 457
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
458
		paused = true;
459

460
		pc.Lock();
461 462
		pc.SetError(PlayerError::OUTPUT, std::move(error));
		pc.state = PlayerState::PAUSE;
463
		pc.Unlock();
464

465 466
		idle_add(IDLE_PLAYER);

467 468 469 470
		return false;
	}
}

471
bool
472
Player::CheckDecoderStartup()
473
{
474
	assert(decoder_starting);
475

476
	pc.Lock();
477

478
	if (!ForwardDecoderError()) {
479
		/* the decoder failed */
480
		pc.Unlock();
481 482

		return false;
483
	} else if (!dc.IsStarting()) {
484
		/* the decoder is ready and ok */
485

486
		pc.Unlock();
487

488
		if (output_open &&
489
		    !pc.outputs.Wait(pc, 1))
490 491 492 493
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

494
		pc.Lock();
495
		pc.total_time = real_song_duration(*dc.song, dc.total_time);
496 497
		pc.audio_format = dc.in_audio_format;
		pc.Unlock();
498

499 500
		idle_add(IDLE_PLAYER);

501 502
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
503

504
		if (!paused && !OpenOutput()) {
505 506
			FormatError(player_domain,
				    "problems opening audio device "
507 508
				    "while playing \"%s\"",
				    dc.song->GetURI());
509 510
			return true;
		}
511 512 513 514 515

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
516
		dc.WaitForDecoder();
517
		pc.Unlock();
518 519 520 521 522

		return true;
	}
}

523
bool
524
Player::SendSilence()
525
{
526 527
	assert(output_open);
	assert(play_audio_format.IsDefined());
528

529
	MusicChunk *chunk = buffer.Allocate();
530
	if (chunk == nullptr) {
531
		LogError(player_domain, "Failed to allocate silence buffer");
532 533 534 535
		return false;
	}

#ifndef NDEBUG
536
	chunk->audio_format = play_audio_format;
537 538
#endif

539
	const size_t frame_size = play_audio_format.GetFrameSize();
540 541 542 543
	/* this formula ensures that we don't send
	   partial frames */
	unsigned num_frames = sizeof(chunk->data) / frame_size;

544
	chunk->time = SignedSongTime::Negative(); /* undefined time stamp */
545 546 547
	chunk->length = num_frames * frame_size;
	memset(chunk->data, 0, chunk->length);

548
	Error error;
549
	if (!pc.outputs.Play(chunk, error)) {
550
		LogError(error);
551
		buffer.Return(chunk);
552 553 554 555 556 557
		return false;
	}

	return true;
}

558
inline bool
559
Player::SeekDecoder()
560
{
561
	assert(pc.next_song != nullptr);
562

563
	const SongTime start_time = pc.next_song->GetStartTime();
564

565
	if (!dc.LockIsCurrentSong(*pc.next_song)) {
566 567 568
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

569
		StopDecoder();
570

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

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

		if (!WaitDecoderStartup())
			return false;
581
	} else {
582
		if (!IsDecoderAtCurrentSong()) {
583 584
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
585
			ClearAndReplacePipe(dc.pipe);
586 587
		}

588
		delete pc.next_song;
589
		pc.next_song = nullptr;
590
		queued = false;
Max Kellermann's avatar
Max Kellermann committed
591

592 593 594
		/* wait for the decoder to complete initialization
		   (just in case that happens to be still in
		   progress) */
595

596 597
		if (!WaitDecoderStartup())
			return false;
598

599
		/* send the SEEK command */
600

601 602 603 604 605 606
		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
607

608 609
		Error error;
		if (!dc.Seek(where + start_time, error)) {
610
			/* decoder failure */
611
			pc.SetError(PlayerError::DECODER, std::move(error));
612 613 614
			pc.LockCommandFinished();
			return false;
		}
615

616 617
		elapsed_time = where;
	}
618

619
	pc.LockCommandFinished();
620

621
	assert(xfade_state == CrossFadeState::UNKNOWN);
622

623
	/* re-fill the buffer after seeking */
624
	buffering = true;
625

626
	pc.outputs.Cancel();
627 628

	return true;
629 630
}

631
inline void
632
Player::ProcessCommand()
633
{
634
	switch (pc.command) {
635 636 637 638
	case PlayerCommand::NONE:
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
639 640
		break;

641
	case PlayerCommand::UPDATE_AUDIO:
642
		pc.Unlock();
643
		pc.outputs.EnableDisable();
644
		pc.Lock();
645
		pc.CommandFinished();
646 647
		break;

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

653
		queued = true;
654
		pc.CommandFinished();
655 656 657 658 659 660

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

661 662
		break;

663
	case PlayerCommand::PAUSE:
664
		pc.Unlock();
665

666 667
		paused = !paused;
		if (paused) {
668
			pc.outputs.Pause();
669
			pc.Lock();
670

671
			pc.state = PlayerState::PAUSE;
672
		} else if (!play_audio_format.IsDefined()) {
673 674
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
675
			pc.Lock();
676

677
			pc.state = PlayerState::PLAY;
678
		} else {
679
			OpenOutput();
680

681
			pc.Lock();
682
		}
683

684
		pc.CommandFinished();
685 686
		break;

687
	case PlayerCommand::SEEK:
688
		pc.Unlock();
689
		SeekDecoder();
690
		pc.Lock();
691
		break;
692

693
	case PlayerCommand::CANCEL:
694
		if (pc.next_song == nullptr) {
695
			/* the cancel request arrived too late, we're
696 697
			   already playing the queued song...  stop
			   everything now */
698
			pc.command = PlayerCommand::STOP;
699 700 701
			return;
		}

702
		if (IsDecoderAtNextSong()) {
703 704
			/* the decoder is already decoding the song -
			   stop it and reset the position */
705
			pc.Unlock();
706
			StopDecoder();
707
			pc.Lock();
708
		}
709

710
		delete pc.next_song;
711
		pc.next_song = nullptr;
712
		queued = false;
713
		pc.CommandFinished();
714
		break;
715

716
	case PlayerCommand::REFRESH:
717
		if (output_open && !paused) {
718
			pc.Unlock();
719
			pc.outputs.Check();
720
			pc.Lock();
721
		}
722

723 724
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
725
			: elapsed_time;
726

727
		pc.CommandFinished();
728
		break;
729 730 731
	}
}

732
static void
733
update_song_tag(PlayerControl &pc, DetachedSong &song, const Tag &new_tag)
734
{
735
	if (song.IsFile())
736 737 738 739
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

740
	song.SetTag(new_tag);
741

742
	pc.LockSetTaggedSong(song);
743

744 745
	/* the main thread will update the playlist version when he
	   receives this event */
746
	pc.listener.OnPlayerTagModified();
747 748 749 750 751 752

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

753
/**
754
 * Plays a #MusicChunk object (after applying software volume).  If
755 756
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
757 758
 *
 * Player lock is not held.
759
 */
760
static bool
761
play_chunk(PlayerControl &pc,
762
	   DetachedSong &song, MusicChunk *chunk,
763
	   MusicBuffer &buffer,
764
	   const AudioFormat format,
765
	   Error &error)
766
{
767
	assert(chunk->CheckFormat(format));
768

769
	if (chunk->tag != nullptr)
770
		update_song_tag(pc, song, *chunk->tag);
771

772
	if (chunk->IsEmpty()) {
773
		buffer.Return(chunk);
774
		return true;
775
	}
776

777 778 779
	pc.Lock();
	pc.bit_rate = chunk->bit_rate;
	pc.Unlock();
780

781 782
	/* send the chunk to the audio outputs */

783
	if (!pc.outputs.Play(chunk, error))
784
		return false;
785

786
	pc.total_play_time += (double)chunk->length /
787
		format.GetTimeToSize();
788
	return true;
789 790
}

791
inline bool
792
Player::PlayNextChunk()
793
{
794
	if (!pc.outputs.Wait(pc, 64))
795 796
		/* the output pipe is still large enough, don't send
		   another chunk */
797 798
		return true;

799 800 801 802 803 804 805 806 807 808 809
	/* 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;
	}

810
	MusicChunk *chunk = nullptr;
811
	if (xfade_state == CrossFadeState::ACTIVE) {
812 813
		/* perform cross fade */

814 815 816 817
		assert(IsDecoderAtNextSong());

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

819
		MusicChunk *other_chunk = dc.pipe->Shift();
820
		if (other_chunk != nullptr) {
821
			chunk = pipe->Shift();
822 823
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
824

825 826 827
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
828 829
			cross_fade_tag =
				Tag::MergeReplace(cross_fade_tag,
830
						  other_chunk->tag);
831
			other_chunk->tag = nullptr;
832

833
			if (pc.cross_fade.mixramp_delay <= 0) {
834
				chunk->mix_ratio = ((float)cross_fade_position)
835
					     / cross_fade_chunks;
836
			} else {
837
				chunk->mix_ratio = -1;
838
			}
839

840
			if (other_chunk->IsEmpty()) {
841
				/* the "other" chunk was a MusicChunk
842 843 844 845 846 847
				   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 */
848
				buffer.Return(other_chunk);
849
				other_chunk = nullptr;
850
			}
851

852
			chunk->other = other_chunk;
853
		} else {
854
			/* there are not enough decoded chunks yet */
855

856
			pc.Lock();
857

858
			if (dc.IsIdle()) {
859
				/* the decoder isn't running, abort
860
				   cross fading */
861
				pc.Unlock();
862

863
				xfade_state = CrossFadeState::DISABLED;
864
			} else {
865
				/* wait for the decoder */
866 867
				dc.Signal();
				dc.WaitForDecoder();
868
				pc.Unlock();
869

870 871 872 873 874
				return true;
			}
		}
	}

875
	if (chunk == nullptr)
876
		chunk = pipe->Shift();
877

878
	assert(chunk != nullptr);
879

880 881
	/* insert the postponed tag if cross-fading is finished */

882
	if (xfade_state != CrossFadeState::ACTIVE && cross_fade_tag != nullptr) {
883 884
		chunk->tag = Tag::MergeReplace(chunk->tag, cross_fade_tag);
		cross_fade_tag = nullptr;
885 886
	}

887 888
	/* play the current chunk */

889
	Error error;
890
	if (!play_chunk(pc, *song, chunk, buffer, play_audio_format, error)) {
891
		LogError(error);
892

893
		buffer.Return(chunk);
894

895
		pc.Lock();
896

897
		pc.SetError(PlayerError::OUTPUT, std::move(error));
898

899 900
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
901
		pc.state = PlayerState::PAUSE;
902
		paused = true;
903

904
		pc.Unlock();
905

906 907
		idle_add(IDLE_PLAYER);

908
		return false;
909
	}
910

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

	return true;
}

929
inline void
930
Player::SongBorder()
931
{
932
	FormatDefault(player_domain, "played \"%s\"", song->GetURI());
933

934
	ReplacePipe(dc.pipe);
935

936
	pc.outputs.SongBorder();
937

938
	ActivateDecoder();
939

940
	pc.Lock();
941

942
	const bool border_pause = pc.border_pause;
943
	if (border_pause) {
944
		paused = true;
945
		pc.state = PlayerState::PAUSE;
946 947
	}

948
	pc.Unlock();
949

950 951
	if (border_pause)
		idle_add(IDLE_PLAYER);
952 953
}

954
inline void
955
Player::Run()
956
{
957
	pipe = new MusicPipe();
958

959
	StartDecoder(*pipe);
960
	ActivateDecoder();
961

962
	pc.Lock();
963
	pc.state = PlayerState::PLAY;
964

965
	pc.CommandFinished();
966

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

977
		pc.Unlock();
978

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

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

988
				if (!paused && output_open &&
989
				    pc.outputs.Check() < 4 &&
990
				    !SendSilence())
991 992
					break;

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

1003
		if (decoder_starting) {
1004
			/* wait until the decoder is initialized completely */
1005

1006
			if (!CheckDecoderStartup())
1007
				break;
1008

1009
			pc.Lock();
1010
			continue;
1011 1012
		}

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

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

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

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

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

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

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

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

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

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

1103
		pc.Lock();
1104 1105
	}

1106
	StopDecoder();
1107

1108
	ClearAndDeletePipe();
1109

1110
	delete cross_fade_tag;
1111

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

1117
	pc.Lock();
1118

1119 1120
	pc.ClearTaggedSong();

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

1127
	pc.state = PlayerState::STOP;
1128

1129
	pc.Unlock();
1130 1131
}

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

1140 1141
static void
player_task(void *arg)
1142
{
1143
	PlayerControl &pc = *(PlayerControl *)arg;
1144

1145 1146
	SetThreadName("player");

1147
	DecoderControl dc(pc.mutex, pc.cond);
1148
	decoder_thread_start(dc);
1149

1150
	MusicBuffer buffer(pc.buffer_chunks);
1151

1152
	pc.Lock();
1153

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

1160
			pc.Unlock();
1161
			do_play(pc, dc, buffer);
1162
			pc.listener.OnPlayerSync();
1163
			pc.Lock();
1164 1165
			break;

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

1171 1172
			/* fall through */

1173
		case PlayerCommand::PAUSE:
1174 1175
			delete pc.next_song;
			pc.next_song = nullptr;
1176

1177
			pc.CommandFinished();
1178 1179
			break;

1180
		case PlayerCommand::CLOSE_AUDIO:
1181
			pc.Unlock();
1182

1183
			pc.outputs.Release();
1184

1185
			pc.Lock();
1186
			pc.CommandFinished();
1187

1188
			assert(buffer.IsEmptyUnsafe());
1189

1190 1191
			break;

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

1199
		case PlayerCommand::EXIT:
1200
			pc.Unlock();
1201

1202 1203
			dc.Quit();

1204
			pc.outputs.Close();
1205

1206
			pc.LockCommandFinished();
1207
			return;
Max Kellermann's avatar
Max Kellermann committed
1208

1209
		case PlayerCommand::CANCEL:
1210 1211
			delete pc.next_song;
			pc.next_song = nullptr;
1212

1213
			pc.CommandFinished();
1214 1215
			break;

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

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

1228
void
1229
StartPlayerThread(PlayerControl &pc)
1230
{
1231 1232 1233 1234 1235
	assert(!pc.thread.IsDefined());

	Error error;
	if (!pc.thread.Start(player_task, &pc, error))
		FatalError(error);
1236
}