PlayerThread.cxx 24.5 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2014 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
		break;

617
	case PlayerCommand::PAUSE:
618
		pc.Unlock();
619

620 621
		paused = !paused;
		if (paused) {
622
			pc.outputs.Pause();
623
			pc.Lock();
624

625
			pc.state = PlayerState::PAUSE;
626
		} else if (!play_audio_format.IsDefined()) {
627 628
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
629
			pc.Lock();
630

631
			pc.state = PlayerState::PLAY;
632
		} else {
633
			OpenOutput();
634

635
			pc.Lock();
636
		}
637

638
		pc.CommandFinished();
639 640
		break;

641
	case PlayerCommand::SEEK:
642
		pc.Unlock();
643
		SeekDecoder();
644
		pc.Lock();
645
		break;
646

647
	case PlayerCommand::CANCEL:
648
		if (pc.next_song == nullptr) {
649
			/* the cancel request arrived too late, we're
650 651
			   already playing the queued song...  stop
			   everything now */
652
			pc.command = PlayerCommand::STOP;
653 654 655
			return;
		}

656
		if (IsDecoderAtNextSong()) {
657 658
			/* the decoder is already decoding the song -
			   stop it and reset the position */
659
			pc.Unlock();
660
			StopDecoder();
661
			pc.Lock();
662
		}
663

664
		delete pc.next_song;
665
		pc.next_song = nullptr;
666
		queued = false;
667
		pc.CommandFinished();
668
		break;
669

670
	case PlayerCommand::REFRESH:
671
		if (output_open && !paused) {
672
			pc.Unlock();
673
			pc.outputs.Check();
674
			pc.Lock();
675
		}
676

677 678
		pc.elapsed_time = !pc.outputs.GetElapsedTime().IsNegative()
			? SongTime(pc.outputs.GetElapsedTime())
679
			: elapsed_time;
680

681
		pc.CommandFinished();
682
		break;
683 684 685
	}
}

686
static void
687
update_song_tag(PlayerControl &pc, DetachedSong &song, const Tag &new_tag)
688
{
689
	if (song.IsFile())
690 691 692 693
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

694
	song.SetTag(new_tag);
695

696
	pc.LockSetTaggedSong(song);
697

698 699
	/* the main thread will update the playlist version when he
	   receives this event */
700
	pc.listener.OnPlayerTagModified();
701 702 703 704 705 706

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

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

723
	if (chunk->tag != nullptr)
724
		update_song_tag(pc, song, *chunk->tag);
725

726
	if (chunk->IsEmpty()) {
727
		buffer.Return(chunk);
728
		return true;
729
	}
730

731 732 733
	pc.Lock();
	pc.bit_rate = chunk->bit_rate;
	pc.Unlock();
734

735 736
	/* send the chunk to the audio outputs */

737
	if (!pc.outputs.Play(chunk, error))
738
		return false;
739

740
	pc.total_play_time += (double)chunk->length /
741
		format.GetTimeToSize();
742
	return true;
743 744
}

745
inline bool
746
Player::PlayNextChunk()
747
{
748
	if (!pc.outputs.Wait(pc, 64))
749 750
		/* the output pipe is still large enough, don't send
		   another chunk */
751 752
		return true;

753
	unsigned cross_fade_position;
754
	MusicChunk *chunk = nullptr;
755
	if (xfade_state == CrossFadeState::ENABLED && IsDecoderAtNextSong() &&
756
	    (cross_fade_position = pipe->GetSize()) <= cross_fade_chunks) {
757
		/* perform cross fade */
758
		MusicChunk *other_chunk = dc.pipe->Shift();
759

760
		if (!cross_fading) {
761 762 763 764
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
765 766
			cross_fade_chunks = cross_fade_position;
			cross_fading = true;
767 768
		}

769
		if (other_chunk != nullptr) {
770
			chunk = pipe->Shift();
771 772
			assert(chunk != nullptr);
			assert(chunk->other == nullptr);
773

774 775 776
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
777 778
			cross_fade_tag =
				Tag::MergeReplace(cross_fade_tag,
779
						  other_chunk->tag);
780
			other_chunk->tag = nullptr;
781

782
			if (pc.cross_fade.mixramp_delay <= 0) {
783
				chunk->mix_ratio = ((float)cross_fade_position)
784
					     / cross_fade_chunks;
785
			} else {
786
				chunk->mix_ratio = -1;
787
			}
788

789
			if (other_chunk->IsEmpty()) {
790
				/* the "other" chunk was a MusicChunk
791 792 793 794 795 796
				   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 */
797
				buffer.Return(other_chunk);
798
				other_chunk = nullptr;
799
			}
800

801
			chunk->other = other_chunk;
802
		} else {
803
			/* there are not enough decoded chunks yet */
804

805
			pc.Lock();
806

807
			if (dc.IsIdle()) {
808
				/* the decoder isn't running, abort
809
				   cross fading */
810
				pc.Unlock();
811

812
				xfade_state = CrossFadeState::DISABLED;
813
			} else {
814
				/* wait for the decoder */
815 816
				dc.Signal();
				dc.WaitForDecoder();
817
				pc.Unlock();
818

819 820 821 822 823
				return true;
			}
		}
	}

824
	if (chunk == nullptr)
825
		chunk = pipe->Shift();
826

827
	assert(chunk != nullptr);
828

829 830
	/* insert the postponed tag if cross-fading is finished */

831
	if (xfade_state != CrossFadeState::ENABLED && cross_fade_tag != nullptr) {
832 833
		chunk->tag = Tag::MergeReplace(chunk->tag, cross_fade_tag);
		cross_fade_tag = nullptr;
834 835
	}

836 837
	/* play the current chunk */

838
	Error error;
839
	if (!play_chunk(pc, *song, chunk, buffer, play_audio_format, error)) {
840
		LogError(error);
841

842
		buffer.Return(chunk);
843

844
		pc.Lock();
845

846
		pc.SetError(PlayerError::OUTPUT, std::move(error));
847

848 849
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
850
		pc.state = PlayerState::PAUSE;
851
		paused = true;
852

853
		pc.Unlock();
854

855 856
		idle_add(IDLE_PLAYER);

857
		return false;
858
	}
859

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

	return true;
}

878
inline bool
879
Player::SongBorder()
880
{
881
	xfade_state = CrossFadeState::UNKNOWN;
882

883
	FormatDefault(player_domain, "played \"%s\"", song->GetURI());
884

885
	ReplacePipe(dc.pipe);
886

887
	pc.outputs.SongBorder();
888

889
	if (!WaitForDecoder())
890 891
		return false;

892
	pc.Lock();
893

894
	const bool border_pause = pc.border_pause;
895
	if (border_pause) {
896
		paused = true;
897
		pc.state = PlayerState::PAUSE;
898 899
	}

900
	pc.Unlock();
901

902 903 904
	if (border_pause)
		idle_add(IDLE_PLAYER);

905
	return true;
906 907
}

908
inline void
909
Player::Run()
910
{
911
	pipe = new MusicPipe();
912

913 914
	StartDecoder(*pipe);
	if (!WaitForDecoder()) {
915
		assert(song == nullptr);
916

917
		StopDecoder();
918
		player_command_finished(pc);
919
		delete pipe;
920
		return;
921
	}
922

923
	pc.Lock();
924
	pc.state = PlayerState::PLAY;
925

926
	if (pc.command == PlayerCommand::SEEK)
927
		elapsed_time = pc.seek_time;
928

929
	pc.CommandFinished();
930

931
	while (true) {
932
		ProcessCommand();
933 934 935
		if (pc.command == PlayerCommand::STOP ||
		    pc.command == PlayerCommand::EXIT ||
		    pc.command == PlayerCommand::CLOSE_AUDIO) {
936
			pc.Unlock();
937
			pc.outputs.Cancel();
938 939 940
			break;
		}

941
		pc.Unlock();
942

943
		if (buffering) {
944 945 946 947
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

948
			if (pipe->GetSize() < pc.buffered_before_play &&
949
			    !dc.LockIsIdle()) {
950
				/* not enough decoded buffer space yet */
951

952
				if (!paused && output_open &&
953
				    pc.outputs.Check() < 4 &&
954
				    !SendSilence())
955 956
					break;

957
				pc.Lock();
958
				/* XXX race condition: check decoder again */
959
				dc.WaitForDecoder();
960 961 962
				continue;
			} else {
				/* buffering is complete */
963
				buffering = false;
964 965 966
			}
		}

967
		if (decoder_starting) {
968
			/* wait until the decoder is initialized completely */
969

970
			if (!CheckDecoderStartup())
971
				break;
972

973
			pc.Lock();
974
			continue;
975 976
		}

977
#ifndef NDEBUG
978
		/*
979
		music_pipe_check_format(&play_audio_format,
980
					next_song_chunk,
981
					&dc.out_audio_format);
982
		*/
983 984
#endif

985
		if (dc.LockIsIdle() && queued && dc.pipe == pipe) {
986 987
			/* the decoder has finished the current song;
			   make it decode the next song */
988

989
			assert(dc.pipe == nullptr || dc.pipe == pipe);
990

991
			StartDecoder(*new MusicPipe());
992
		}
993

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

1022
		if (paused) {
1023
			pc.Lock();
1024

1025
			if (pc.command == PlayerCommand::NONE)
1026
				pc.Wait();
1027
			continue;
1028
		} else if (!pipe->IsEmpty()) {
1029 1030
			/* at least one music chunk is ready - send it
			   to the audio output */
1031

1032
			PlayNextChunk();
1033
		} else if (pc.outputs.Check() > 0) {
1034 1035 1036 1037
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

1038 1039 1040 1041 1042 1043 1044 1045
			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;
1046
		} else if (IsDecoderAtNextSong()) {
1047 1048
			/* at the beginning of a new song */

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

1069
		pc.Lock();
1070 1071
	}

1072
	StopDecoder();
1073

1074
	ClearAndDeletePipe();
1075

1076
	delete cross_fade_tag;
1077

1078
	if (song != nullptr) {
1079 1080
		FormatDefault(player_domain, "played \"%s\"", song->GetURI());
		delete song;
1081
	}
1082

1083
	pc.Lock();
1084

1085 1086
	pc.ClearTaggedSong();

1087
	if (queued) {
1088
		assert(pc.next_song != nullptr);
1089
		delete pc.next_song;
1090
		pc.next_song = nullptr;
1091 1092
	}

1093
	pc.state = PlayerState::STOP;
1094

1095
	pc.Unlock();
1096 1097
}

1098
static void
1099
do_play(PlayerControl &pc, DecoderControl &dc,
1100 1101
	MusicBuffer &buffer)
{
1102
	Player player(pc, dc, buffer);
1103 1104 1105
	player.Run();
}

1106 1107
static void
player_task(void *arg)
1108
{
1109
	PlayerControl &pc = *(PlayerControl *)arg;
1110

1111 1112
	SetThreadName("player");

1113
	DecoderControl dc(pc.mutex, pc.cond);
1114
	decoder_thread_start(dc);
1115

1116
	MusicBuffer buffer(pc.buffer_chunks);
1117

1118
	pc.Lock();
1119

1120
	while (1) {
1121
		switch (pc.command) {
1122 1123
		case PlayerCommand::SEEK:
		case PlayerCommand::QUEUE:
1124
			assert(pc.next_song != nullptr);
1125

1126
			pc.Unlock();
1127
			do_play(pc, dc, buffer);
1128
			pc.listener.OnPlayerSync();
1129
			pc.Lock();
1130 1131
			break;

1132
		case PlayerCommand::STOP:
1133
			pc.Unlock();
1134
			pc.outputs.Cancel();
1135
			pc.Lock();
1136

1137 1138
			/* fall through */

1139
		case PlayerCommand::PAUSE:
1140 1141
			delete pc.next_song;
			pc.next_song = nullptr;
1142

1143
			pc.CommandFinished();
1144 1145
			break;

1146
		case PlayerCommand::CLOSE_AUDIO:
1147
			pc.Unlock();
1148

1149
			pc.outputs.Release();
1150

1151
			pc.Lock();
1152
			pc.CommandFinished();
1153

1154
			assert(buffer.IsEmptyUnsafe());
1155

1156 1157
			break;

1158
		case PlayerCommand::UPDATE_AUDIO:
1159
			pc.Unlock();
1160
			pc.outputs.EnableDisable();
1161
			pc.Lock();
1162
			pc.CommandFinished();
1163 1164
			break;

1165
		case PlayerCommand::EXIT:
1166
			pc.Unlock();
1167

1168 1169
			dc.Quit();

1170
			pc.outputs.Close();
1171

1172
			player_command_finished(pc);
1173
			return;
Max Kellermann's avatar
Max Kellermann committed
1174

1175
		case PlayerCommand::CANCEL:
1176 1177
			delete pc.next_song;
			pc.next_song = nullptr;
1178

1179
			pc.CommandFinished();
1180 1181
			break;

1182
		case PlayerCommand::REFRESH:
1183
			/* no-op when not playing */
1184
			pc.CommandFinished();
1185 1186
			break;

1187
		case PlayerCommand::NONE:
1188
			pc.Wait();
1189 1190 1191 1192 1193
			break;
		}
	}
}

1194
void
1195
StartPlayerThread(PlayerControl &pc)
1196
{
1197 1198 1199 1200 1201
	assert(!pc.thread.IsDefined());

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