PlayerThread.cxx 24.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
#include "PlayerThread.hxx"
22
#include "PlayerListener.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 "PlayerControl.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 44 45 46
enum class CrossFadeState : int8_t {
	DISABLED = -1,
	UNKNOWN = 0,
	ENABLED = 1
47 48
};

49
class Player {
50
	PlayerControl &pc;
51

52
	DecoderControl &dc;
53

54 55
	MusicBuffer &buffer;

56
	MusicPipe *pipe;
57

58
	/**
59
	 * are we waiting for buffered_before_play?
60
	 */
61
	bool buffering;
62 63 64 65 66 67 68

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

69 70 71 72 73 74
	/**
	 * Did we wake up the DecoderThread recently?  This avoids
	 * duplicate wakeup calls.
	 */
	bool decoder_woken;

75 76 77 78 79
	/**
	 * is the player paused?
	 */
	bool paused;

80 81 82 83 84
	/**
	 * is there a new song in pc.next_song?
	 */
	bool queued;

85 86 87 88 89 90 91 92
	/**
	 * 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;

93 94 95
	/**
	 * the song currently being played
	 */
96
	DetachedSong *song;
97

98 99 100
	/**
	 * is cross fading enabled?
	 */
101
	CrossFadeState xfade_state;
102

103 104 105 106 107 108 109 110 111 112
	/**
	 * has cross-fading begun?
	 */
	bool cross_fading;

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

113 114 115 116 117
	/**
	 * 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
118
	Tag *cross_fade_tag;
119

120 121 122
	/**
	 * The current audio format for the audio outputs.
	 */
123
	AudioFormat play_audio_format;
124 125 126 127

	/**
	 * The time stamp of the chunk most recently sent to the
	 * output thread.  This attribute is only used if
128
	 * MultipleOutputs::GetElapsedTime() didn't return a usable
129
	 * value; the output thread can estimate the elapsed time more
130
	 * precisely.
131
	 */
132
	SongTime elapsed_time;
133

134
public:
135
	Player(PlayerControl &_pc, DecoderControl &_dc,
136 137
	       MusicBuffer &_buffer)
		:pc(_pc), dc(_dc), buffer(_buffer),
138
		 buffering(true),
139
		 decoder_starting(false),
140
		 decoder_woken(false),
141 142 143
		 paused(false),
		 queued(true),
		 output_open(false),
144
		 song(nullptr),
145
		 xfade_state(CrossFadeState::UNKNOWN),
146 147
		 cross_fading(false),
		 cross_fade_chunks(0),
148
		 cross_fade_tag(nullptr),
149
		 elapsed_time(SongTime::zero()) {}
150

151
private:
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
	void ClearAndDeletePipe() {
		pipe->Clear(buffer);
		delete pipe;
	}

	void ClearAndReplacePipe(MusicPipe *_pipe) {
		ClearAndDeletePipe();
		pipe = _pipe;
	}

	void ReplacePipe(MusicPipe *_pipe) {
		delete pipe;
		pipe = _pipe;
	}

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

	/**
	 * The decoder has acknowledged the "START" command (see
	 * player::WaitForDecoder()).  This function checks if the decoder
	 * initialization has completed yet.
	 *
	 * The player lock is not held.
	 */
	bool CheckDecoderStartup();

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

	/**
214
	 * This is the handler for the #PlayerCommand::SEEK command.
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230
	 *
	 * The player lock is not held.
	 */
	bool SeekDecoder();

	/**
	 * After the decoder has been started asynchronously, wait for
	 * the "START" command to finish.  The decoder may not be
	 * initialized yet, i.e. there is no audio_format information
	 * yet.
	 *
	 * The player lock is not held.
	 */
	bool WaitForDecoder();

	/**
231 232
	 * Wrapper for MultipleOutputs::Open().  Upon failure, it
	 * pauses the player.
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
	 *
	 * @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.
	 *
	 * @return true on success, false on error (playback will be stopped)
	 */
	bool SongBorder();

271
public:
272 273 274 275 276 277
	/*
	 * 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();
278 279
};

280
static void
281
player_command_finished(PlayerControl &pc)
282
{
283
	pc.Lock();
284
	pc.CommandFinished();
285
	pc.Unlock();
286 287
}

288
void
289
Player::StartDecoder(MusicPipe &_pipe)
290
{
291
	assert(queued || pc.command == PlayerCommand::SEEK);
292
	assert(pc.next_song != nullptr);
293

294
	SongTime start_time = pc.next_song->GetStartTime();
295
	if (pc.command == PlayerCommand::SEEK)
296
		start_time += pc.seek_time;
297

298
	dc.Start(new DetachedSong(*pc.next_song),
299
		 start_time, pc.next_song->GetEndTime(),
300
		 buffer, _pipe);
301 302
}

303
void
304
Player::StopDecoder()
305
{
306
	dc.Stop();
307

308
	if (dc.pipe != nullptr) {
309 310
		/* clear and free the decoder pipe */

311
		dc.pipe->Clear(buffer);
312

313
		if (dc.pipe != pipe)
314
			delete dc.pipe;
315

316
		dc.pipe = nullptr;
317 318 319
	}
}

320
bool
321
Player::WaitForDecoder()
322
{
323
	assert(queued || pc.command == PlayerCommand::SEEK);
324
	assert(pc.next_song != nullptr);
325

326
	queued = false;
327

328 329
	pc.Lock();
	Error error = dc.GetError();
330
	if (error.IsDefined()) {
331
		pc.SetError(PlayerError::DECODER, std::move(error));
332

333
		delete pc.next_song;
334
		pc.next_song = nullptr;
335

336
		pc.Unlock();
337

338
		return false;
339 340
	}

341 342
	pc.ClearTaggedSong();

343
	delete song;
344
	song = pc.next_song;
345
	elapsed_time = SongTime::zero();
346 347 348

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

351
	/* update PlayerControl's song information */
352
	pc.total_time = pc.next_song->GetDuration();
353 354
	pc.bit_rate = 0;
	pc.audio_format.Clear();
355

356
	/* clear the queued song */
357
	pc.next_song = nullptr;
358

359
	pc.Unlock();
360

361
	/* call syncPlaylistWithQueue() in the main thread */
362
	pc.listener.OnPlayerSync();
363

364
	return true;
365 366
}

367 368 369 370
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
371 372
static SignedSongTime
real_song_duration(const DetachedSong &song, SignedSongTime decoder_duration)
373
{
374
	if (decoder_duration.IsNegative())
375
		/* the decoder plugin didn't provide information; fall
376
		   back to Song::GetDuration() */
377
		return song.GetDuration();
378

379 380
	const SongTime start_time = song.GetStartTime();
	const SongTime end_time = song.GetEndTime();
381

382 383
	if (end_time.IsPositive() && end_time < SongTime(decoder_duration))
		return SignedSongTime(end_time - start_time);
384

385
	return SignedSongTime(SongTime(decoder_duration) - start_time);
386 387
}

388
bool
389
Player::OpenOutput()
390
{
391
	assert(play_audio_format.IsDefined());
392 393
	assert(pc.state == PlayerState::PLAY ||
	       pc.state == PlayerState::PAUSE);
394

395
	Error error;
396
	if (pc.outputs.Open(play_audio_format, buffer, error)) {
397 398
		output_open = true;
		paused = false;
399

400
		pc.Lock();
401
		pc.state = PlayerState::PLAY;
402
		pc.Unlock();
403

404 405
		idle_add(IDLE_PLAYER);

406 407
		return true;
	} else {
408
		LogError(error);
409

410
		output_open = false;
411

412 413
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
414
		paused = true;
415

416
		pc.Lock();
417 418
		pc.SetError(PlayerError::OUTPUT, std::move(error));
		pc.state = PlayerState::PAUSE;
419
		pc.Unlock();
420

421 422
		idle_add(IDLE_PLAYER);

423 424 425 426
		return false;
	}
}

427
bool
428
Player::CheckDecoderStartup()
429
{
430
	assert(decoder_starting);
431

432
	pc.Lock();
433

434
	Error error = dc.GetError();
435
	if (error.IsDefined()) {
436
		/* the decoder failed */
437
		pc.SetError(PlayerError::DECODER, std::move(error));
438
		pc.Unlock();
439 440

		return false;
441
	} else if (!dc.IsStarting()) {
442
		/* the decoder is ready and ok */
443

444
		pc.Unlock();
445

446
		if (output_open &&
447
		    !pc.outputs.Wait(pc, 1))
448 449 450 451
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

452
		pc.Lock();
453
		pc.total_time = real_song_duration(*dc.song, dc.total_time);
454 455
		pc.audio_format = dc.in_audio_format;
		pc.Unlock();
456

457 458
		idle_add(IDLE_PLAYER);

459 460
		play_audio_format = dc.out_audio_format;
		decoder_starting = false;
461

462
		if (!paused && !OpenOutput()) {
463 464
			FormatError(player_domain,
				    "problems opening audio device "
465 466
				    "while playing \"%s\"",
				    dc.song->GetURI());
467 468
			return true;
		}
469 470 471 472 473

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
474
		dc.WaitForDecoder();
475
		pc.Unlock();
476 477 478 479 480

		return true;
	}
}

481
bool
482
Player::SendSilence()
483
{
484 485
	assert(output_open);
	assert(play_audio_format.IsDefined());
486

487
	MusicChunk *chunk = buffer.Allocate();
488
	if (chunk == nullptr) {
489
		LogError(player_domain, "Failed to allocate silence buffer");
490 491 492 493
		return false;
	}

#ifndef NDEBUG
494
	chunk->audio_format = play_audio_format;
495 496
#endif

497
	const size_t frame_size = play_audio_format.GetFrameSize();
498 499 500 501
	/* this formula ensures that we don't send
	   partial frames */
	unsigned num_frames = sizeof(chunk->data) / frame_size;

502
	chunk->time = SignedSongTime::Negative(); /* undefined time stamp */
503 504 505
	chunk->length = num_frames * frame_size;
	memset(chunk->data, 0, chunk->length);

506
	Error error;
507
	if (!pc.outputs.Play(chunk, error)) {
508
		LogError(error);
509
		buffer.Return(chunk);
510 511 512 513 514 515
		return false;
	}

	return true;
}

516
inline bool
517
Player::SeekDecoder()
518
{
519
	assert(pc.next_song != nullptr);
520

521
	const SongTime start_time = pc.next_song->GetStartTime();
522

523
	if (!dc.LockIsCurrentSong(*pc.next_song)) {
524 525 526
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

527
		StopDecoder();
528

529 530
		/* clear music chunks which might still reside in the
		   pipe */
531
		pipe->Clear(buffer);
532

533
		/* re-start the decoder */
534 535
		StartDecoder(*pipe);
		if (!WaitForDecoder()) {
536
			/* decoder failure */
537
			player_command_finished(pc);
538
			return false;
539
		}
540
	} else {
541
		if (!IsDecoderAtCurrentSong()) {
542 543
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
544
			ClearAndReplacePipe(dc.pipe);
545 546
		}

547
		delete pc.next_song;
548
		pc.next_song = nullptr;
549
		queued = false;
550
	}
Max Kellermann's avatar
Max Kellermann committed
551

552 553
	/* wait for the decoder to complete initialization */

554 555
	while (decoder_starting) {
		if (!CheckDecoderStartup()) {
556
			/* decoder failure */
557
			player_command_finished(pc);
558 559 560 561
			return false;
		}
	}

562 563
	/* send the SEEK command */

564
	SongTime where = pc.seek_time;
565 566
	if (!pc.total_time.IsNegative()) {
		const SongTime total_time(pc.total_time);
567 568 569
		if (where > total_time)
			where = total_time;
	}
Max Kellermann's avatar
Max Kellermann committed
570

571
	if (!dc.Seek(where + start_time)) {
572
		/* decoder failure */
573
		player_command_finished(pc);
574 575
		return false;
	}
576

577
	elapsed_time = where;
578

579
	player_command_finished(pc);
580

581
	xfade_state = CrossFadeState::UNKNOWN;
582

583
	/* re-fill the buffer after seeking */
584
	buffering = true;
585

586
	pc.outputs.Cancel();
587 588

	return true;
589 590
}

591
inline void
592
Player::ProcessCommand()
593
{
594
	switch (pc.command) {
595 596 597 598
	case PlayerCommand::NONE:
	case PlayerCommand::STOP:
	case PlayerCommand::EXIT:
	case PlayerCommand::CLOSE_AUDIO:
599 600
		break;

601
	case PlayerCommand::UPDATE_AUDIO:
602
		pc.Unlock();
603
		pc.outputs.EnableDisable();
604
		pc.Lock();
605
		pc.CommandFinished();
606 607
		break;

608
	case PlayerCommand::QUEUE:
609
		assert(pc.next_song != nullptr);
610 611
		assert(!queued);
		assert(!IsDecoderAtNextSong());
612

613
		queued = true;
614
		pc.CommandFinished();
615 616 617 618 619 620

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

621 622
		break;

623
	case PlayerCommand::PAUSE:
624
		pc.Unlock();
625

626 627
		paused = !paused;
		if (paused) {
628
			pc.outputs.Pause();
629
			pc.Lock();
630

631
			pc.state = PlayerState::PAUSE;
632
		} else if (!play_audio_format.IsDefined()) {
633 634
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
635
			pc.Lock();
636

637
			pc.state = PlayerState::PLAY;
638
		} else {
639
			OpenOutput();
640

641
			pc.Lock();
642
		}
643

644
		pc.CommandFinished();
645 646
		break;

647
	case PlayerCommand::SEEK:
648
		pc.Unlock();
649
		SeekDecoder();
650
		pc.Lock();
651
		break;
652

653
	case PlayerCommand::CANCEL:
654
		if (pc.next_song == nullptr) {
655
			/* the cancel request arrived too late, we're
656 657
			   already playing the queued song...  stop
			   everything now */
658
			pc.command = PlayerCommand::STOP;
659 660 661
			return;
		}

662
		if (IsDecoderAtNextSong()) {
663 664
			/* the decoder is already decoding the song -
			   stop it and reset the position */
665
			pc.Unlock();
666
			StopDecoder();
667
			pc.Lock();
668
		}
669

670
		delete pc.next_song;
671
		pc.next_song = nullptr;
672
		queued = false;
673
		pc.CommandFinished();
674
		break;
675

676
	case PlayerCommand::REFRESH:
677
		if (output_open && !paused) {
678
			pc.Unlock();
679
			pc.outputs.Check();
680
			pc.Lock();
681
		}
682

683 684
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
685
			: elapsed_time;
686

687
		pc.CommandFinished();
688
		break;
689 690 691
	}
}

692
static void
693
update_song_tag(PlayerControl &pc, DetachedSong &song, const Tag &new_tag)
694
{
695
	if (song.IsFile())
696 697 698 699
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

700
	song.SetTag(new_tag);
701

702
	pc.LockSetTaggedSong(song);
703

704 705
	/* the main thread will update the playlist version when he
	   receives this event */
706
	pc.listener.OnPlayerTagModified();
707 708 709 710 711 712

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

713
/**
714
 * Plays a #MusicChunk object (after applying software volume).  If
715 716
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
717 718
 *
 * Player lock is not held.
719
 */
720
static bool
721
play_chunk(PlayerControl &pc,
722
	   DetachedSong &song, MusicChunk *chunk,
723
	   MusicBuffer &buffer,
724
	   const AudioFormat format,
725
	   Error &error)
726
{
727
	assert(chunk->CheckFormat(format));
728

729
	if (chunk->tag != nullptr)
730
		update_song_tag(pc, song, *chunk->tag);
731

732
	if (chunk->IsEmpty()) {
733
		buffer.Return(chunk);
734
		return true;
735
	}
736

737 738 739
	pc.Lock();
	pc.bit_rate = chunk->bit_rate;
	pc.Unlock();
740

741 742
	/* send the chunk to the audio outputs */

743
	if (!pc.outputs.Play(chunk, error))
744
		return false;
745

746
	pc.total_play_time += (double)chunk->length /
747
		format.GetTimeToSize();
748
	return true;
749 750
}

751
inline bool
752
Player::PlayNextChunk()
753
{
754
	if (!pc.outputs.Wait(pc, 64))
755 756
		/* the output pipe is still large enough, don't send
		   another chunk */
757 758
		return true;

759
	unsigned cross_fade_position;
760
	MusicChunk *chunk = nullptr;
761
	if (xfade_state == CrossFadeState::ENABLED && IsDecoderAtNextSong() &&
762
	    (cross_fade_position = pipe->GetSize()) <= cross_fade_chunks) {
763
		/* perform cross fade */
764
		MusicChunk *other_chunk = dc.pipe->Shift();
765

766
		if (!cross_fading) {
767 768 769 770
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
771 772
			cross_fade_chunks = cross_fade_position;
			cross_fading = true;
773 774
		}

775
		if (other_chunk != nullptr) {
776
			chunk = pipe->Shift();
777 778
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
779

780 781 782
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
783 784
			cross_fade_tag =
				Tag::MergeReplace(cross_fade_tag,
785
						  other_chunk->tag);
786
			other_chunk->tag = nullptr;
787

788
			if (pc.cross_fade.mixramp_delay <= 0) {
789
				chunk->mix_ratio = ((float)cross_fade_position)
790
					     / cross_fade_chunks;
791
			} else {
792
				chunk->mix_ratio = -1;
793
			}
794

795
			if (other_chunk->IsEmpty()) {
796
				/* the "other" chunk was a MusicChunk
797 798 799 800 801 802
				   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 */
803
				buffer.Return(other_chunk);
804
				other_chunk = nullptr;
805
			}
806

807
			chunk->other = other_chunk;
808
		} else {
809
			/* there are not enough decoded chunks yet */
810

811
			pc.Lock();
812

813
			if (dc.IsIdle()) {
814
				/* the decoder isn't running, abort
815
				   cross fading */
816
				pc.Unlock();
817

818
				xfade_state = CrossFadeState::DISABLED;
819
			} else {
820
				/* wait for the decoder */
821 822
				dc.Signal();
				dc.WaitForDecoder();
823
				pc.Unlock();
824

825 826 827 828 829
				return true;
			}
		}
	}

830
	if (chunk == nullptr)
831
		chunk = pipe->Shift();
832

833
	assert(chunk != nullptr);
834

835 836
	/* insert the postponed tag if cross-fading is finished */

837
	if (xfade_state != CrossFadeState::ENABLED && cross_fade_tag != nullptr) {
838 839
		chunk->tag = Tag::MergeReplace(chunk->tag, cross_fade_tag);
		cross_fade_tag = nullptr;
840 841
	}

842 843
	/* play the current chunk */

844
	Error error;
845
	if (!play_chunk(pc, *song, chunk, buffer, play_audio_format, error)) {
846
		LogError(error);
847

848
		buffer.Return(chunk);
849

850
		pc.Lock();
851

852
		pc.SetError(PlayerError::OUTPUT, std::move(error));
853

854 855
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
856
		pc.state = PlayerState::PAUSE;
857
		paused = true;
858

859
		pc.Unlock();
860

861 862
		idle_add(IDLE_PLAYER);

863
		return false;
864
	}
865

866 867
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
868
	   larger block at a time */
869
	pc.Lock();
870 871
	if (!dc.IsIdle() &&
	    dc.pipe->GetSize() <= (pc.buffered_before_play +
872 873 874 875 876 877 878
				   buffer.GetSize() * 3) / 4) {
		if (!decoder_woken) {
			decoder_woken = true;
			dc.Signal();
		}
	} else
		decoder_woken = false;
879
	pc.Unlock();
880 881 882 883

	return true;
}

884
inline bool
885
Player::SongBorder()
886
{
887
	xfade_state = CrossFadeState::UNKNOWN;
888

889
	FormatDefault(player_domain, "played \"%s\"", song->GetURI());
890

891
	ReplacePipe(dc.pipe);
892

893
	pc.outputs.SongBorder();
894

895
	if (!WaitForDecoder())
896 897
		return false;

898
	pc.Lock();
899

900
	const bool border_pause = pc.border_pause;
901
	if (border_pause) {
902
		paused = true;
903
		pc.state = PlayerState::PAUSE;
904 905
	}

906
	pc.Unlock();
907

908 909 910
	if (border_pause)
		idle_add(IDLE_PLAYER);

911
	return true;
912 913
}

914
inline void
915
Player::Run()
916
{
917
	pipe = new MusicPipe();
918

919 920
	StartDecoder(*pipe);
	if (!WaitForDecoder()) {
921
		assert(song == nullptr);
922

923
		StopDecoder();
924
		player_command_finished(pc);
925
		delete pipe;
926
		return;
927
	}
928

929
	pc.Lock();
930
	pc.state = PlayerState::PLAY;
931

932
	if (pc.command == PlayerCommand::SEEK)
933
		elapsed_time = pc.seek_time;
934

935
	pc.CommandFinished();
936

937
	while (true) {
938
		ProcessCommand();
939 940 941
		if (pc.command == PlayerCommand::STOP ||
		    pc.command == PlayerCommand::EXIT ||
		    pc.command == PlayerCommand::CLOSE_AUDIO) {
942
			pc.Unlock();
943
			pc.outputs.Cancel();
944 945 946
			break;
		}

947
		pc.Unlock();
948

949
		if (buffering) {
950 951 952 953
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

954
			if (pipe->GetSize() < pc.buffered_before_play &&
955
			    !dc.LockIsIdle()) {
956
				/* not enough decoded buffer space yet */
957

958
				if (!paused && output_open &&
959
				    pc.outputs.Check() < 4 &&
960
				    !SendSilence())
961 962
					break;

963
				pc.Lock();
964
				/* XXX race condition: check decoder again */
965
				dc.WaitForDecoder();
966 967 968
				continue;
			} else {
				/* buffering is complete */
969
				buffering = false;
970 971 972
			}
		}

973
		if (decoder_starting) {
974
			/* wait until the decoder is initialized completely */
975

976
			if (!CheckDecoderStartup())
977
				break;
978

979
			pc.Lock();
980
			continue;
981 982
		}

983
#ifndef NDEBUG
984
		/*
985
		music_pipe_check_format(&play_audio_format,
986
					next_song_chunk,
987
					&dc.out_audio_format);
988
		*/
989 990
#endif

991
		if (dc.LockIsIdle() && queued && dc.pipe == pipe) {
992 993
			/* the decoder has finished the current song;
			   make it decode the next song */
994

995
			assert(dc.pipe == nullptr || dc.pipe == pipe);
996

997
			StartDecoder(*new MusicPipe());
998
		}
999

1000 1001
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
1002
		    !pc.border_pause &&
1003
		    IsDecoderAtNextSong() &&
1004
		    xfade_state == CrossFadeState::UNKNOWN &&
1005
		    !dc.LockIsStarting()) {
1006 1007 1008
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
1009
			cross_fade_chunks =
1010
				pc.cross_fade.Calculate(dc.total_time,
1011 1012 1013 1014 1015 1016 1017 1018
							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);
1019
			if (cross_fade_chunks > 0) {
1020
				xfade_state = CrossFadeState::ENABLED;
1021
				cross_fading = false;
1022 1023 1024
			} else
				/* cross fading is disabled or the
				   next song is too short */
1025
				xfade_state = CrossFadeState::DISABLED;
1026 1027
		}

1028
		if (paused) {
1029
			pc.Lock();
1030

1031
			if (pc.command == PlayerCommand::NONE)
1032
				pc.Wait();
1033
			continue;
1034
		} else if (!pipe->IsEmpty()) {
1035 1036
			/* at least one music chunk is ready - send it
			   to the audio output */
1037

1038
			PlayNextChunk();
1039
		} else if (pc.outputs.Check() > 0) {
1040 1041 1042 1043
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1044 1045 1046 1047 1048 1049 1050 1051
			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;
1052
		} else if (IsDecoderAtNextSong()) {
1053 1054
			/* at the beginning of a new song */

1055
			if (!SongBorder())
1056
				break;
1057
		} else if (dc.LockIsIdle()) {
1058 1059 1060
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1061
			if (pipe->IsEmpty()) {
1062 1063
				/* wait for the hardware to finish
				   playback */
1064
				pc.outputs.Drain();
1065
				break;
1066
			}
1067
		} else if (output_open) {
1068 1069 1070
			/* the decoder is too busy and hasn't provided
			   new PCM data in time: send silence (if the
			   output pipe is empty) */
1071
			if (!SendSilence())
1072 1073
				break;
		}
1074

1075
		pc.Lock();
1076 1077
	}

1078
	StopDecoder();
1079

1080
	ClearAndDeletePipe();
1081

1082
	delete cross_fade_tag;
1083

1084
	if (song != nullptr) {
1085 1086
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
		delete song;
1087
	}
1088

1089
	pc.Lock();
1090

1091 1092
	pc.ClearTaggedSong();

1093
	if (queued) {
1094
		assert(pc.next_song != nullptr);
1095
		delete pc.next_song;
1096
		pc.next_song = nullptr;
1097 1098
	}

1099
	pc.state = PlayerState::STOP;
1100

1101
	pc.Unlock();
1102 1103
}

1104
static void
1105
do_play(PlayerControl &pc, DecoderControl &dc,
1106 1107
	MusicBuffer &buffer)
{
1108
	Player player(pc, dc, buffer);
1109 1110 1111
	player.Run();
}

1112 1113
static void
player_task(void *arg)
1114
{
1115
	PlayerControl &pc = *(PlayerControl *)arg;
1116

1117 1118
	SetThreadName("player");

1119
	DecoderControl dc(pc.mutex, pc.cond);
1120
	decoder_thread_start(dc);
1121

1122
	MusicBuffer buffer(pc.buffer_chunks);
1123

1124
	pc.Lock();
1125

1126
	while (1) {
1127
		switch (pc.command) {
1128 1129
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1130
			assert(pc.next_song != nullptr);
1131

1132
			pc.Unlock();
1133
			do_play(pc, dc, buffer);
1134
			pc.listener.OnPlayerSync();
1135
			pc.Lock();
1136 1137
			break;

1138
		case PlayerCommand::STOP:
1139
			pc.Unlock();
1140
			pc.outputs.Cancel();
1141
			pc.Lock();
1142

1143 1144
			/* fall through */

1145
		case PlayerCommand::PAUSE:
1146 1147
			delete pc.next_song;
			pc.next_song = nullptr;
1148

1149
			pc.CommandFinished();
1150 1151
			break;

1152
		case PlayerCommand::CLOSE_AUDIO:
1153
			pc.Unlock();
1154

1155
			pc.outputs.Release();
1156

1157
			pc.Lock();
1158
			pc.CommandFinished();
1159

1160
			assert(buffer.IsEmptyUnsafe());
1161

1162 1163
			break;

1164
		case PlayerCommand::UPDATE_AUDIO:
1165
			pc.Unlock();
1166
			pc.outputs.EnableDisable();
1167
			pc.Lock();
1168
			pc.CommandFinished();
1169 1170
			break;

1171
		case PlayerCommand::EXIT:
1172
			pc.Unlock();
1173

1174 1175
			dc.Quit();

1176
			pc.outputs.Close();
1177

1178
			player_command_finished(pc);
1179
			return;
Max Kellermann's avatar
Max Kellermann committed
1180

1181
		case PlayerCommand::CANCEL:
1182 1183
			delete pc.next_song;
			pc.next_song = nullptr;
1184

1185
			pc.CommandFinished();
1186 1187
			break;

1188
		case PlayerCommand::REFRESH:
1189
			/* no-op when not playing */
1190
			pc.CommandFinished();
1191 1192
			break;

1193
		case PlayerCommand::NONE:
1194
			pc.Wait();
1195 1196 1197 1198 1199
			break;
		}
	}
}

1200
void
1201
StartPlayerThread(PlayerControl &pc)
1202
{
1203 1204 1205 1206 1207
	assert(!pc.thread.IsDefined());

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