PlayerThread.cxx 26.8 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2013 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 "PlayerThread.hxx"
#include "DecoderThread.hxx"
23
#include "DecoderControl.hxx"
24 25 26
#include "MusicPipe.hxx"
#include "MusicBuffer.hxx"
#include "MusicChunk.hxx"
27
#include "Song.hxx"
28
#include "Main.hxx"
29
#include "system/FatalError.hxx"
30
#include "CrossFade.hxx"
31
#include "PlayerControl.hxx"
32
#include "OutputAll.hxx"
Max Kellermann's avatar
Max Kellermann committed
33
#include "Tag.hxx"
Max Kellermann's avatar
Max Kellermann committed
34
#include "Idle.hxx"
35
#include "GlobalEvents.hxx"
36

37 38
#include <cmath>

39 40
#include <glib.h>

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

43 44 45
#undef G_LOG_DOMAIN
#define G_LOG_DOMAIN "player_thread"

46 47 48 49 50 51
enum xfade_state {
	XFADE_DISABLED = -1,
	XFADE_UNKNOWN = 0,
	XFADE_ENABLED = 1
};

52
struct player {
53 54
	struct player_control *pc;

55 56
	struct decoder_control *dc;

57 58
	struct music_pipe *pipe;

59
	/**
60
	 * are we waiting for buffered_before_play?
61
	 */
62
	bool buffering;
63 64 65 66 67 68 69 70 71 72 73 74

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

	/**
	 * is the player paused?
	 */
	bool paused;

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

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

88 89 90
	/**
	 * the song currently being played
	 */
91
	Song *song;
92

93 94 95 96
	/**
	 * is cross fading enabled?
	 */
	enum xfade_state xfade;
97

98 99 100 101 102 103 104 105 106 107
	/**
	 * has cross-fading begun?
	 */
	bool cross_fading;

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

108 109 110 111 112
	/**
	 * 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
113
	Tag *cross_fade_tag;
114

115 116 117
	/**
	 * The current audio format for the audio outputs.
	 */
118
	AudioFormat play_audio_format;
119 120 121 122 123 124

	/**
	 * The time stamp of the chunk most recently sent to the
	 * output thread.  This attribute is only used if
	 * audio_output_all_get_elapsed_time() didn't return a usable
	 * value; the output thread can estimate the elapsed time more
125
	 * precisely.
126 127
	 */
	float elapsed_time;
128 129 130 131 132 133 134 135 136 137 138 139 140 141

	player(player_control *_pc, decoder_control *_dc)
		:pc(_pc), dc(_dc),
		 buffering(false),
		 decoder_starting(false),
		 paused(false),
		 queued(true),
		 output_open(false),
		 song(NULL),
		 xfade(XFADE_UNKNOWN),
		 cross_fading(false),
		 cross_fade_chunks(0),
		 cross_fade_tag(NULL),
		 elapsed_time(0.0) {}
142 143
};

144 145
static struct music_buffer *player_buffer;

146 147
static void
player_command_finished_locked(struct player_control *pc)
148
{
149
	assert(pc->command != PLAYER_COMMAND_NONE);
150

151
	pc->command = PLAYER_COMMAND_NONE;
152
	pc->ClientSignal();
153 154
}

155 156
static void
player_command_finished(struct player_control *pc)
157
{
158
	pc->Lock();
159
	player_command_finished_locked(pc);
160
	pc->Unlock();
161 162
}

163 164 165 166 167 168
/**
 * Start the decoder.
 *
 * Player lock is not held.
 */
static void
169
player_dc_start(struct player *player, struct music_pipe *pipe)
170
{
171
	struct player_control *pc = player->pc;
172 173
	struct decoder_control *dc = player->dc;

174 175
	assert(player->queued || pc->command == PLAYER_COMMAND_SEEK);
	assert(pc->next_song != NULL);
176

Max Kellermann's avatar
Max Kellermann committed
177 178 179
	unsigned start_ms = pc->next_song->start_ms;
	if (pc->command == PLAYER_COMMAND_SEEK)
		start_ms += (unsigned)(pc->seek_where * 1000);
180

181
	dc->Start(pc->next_song->DupDetached(),
182 183
		  start_ms, pc->next_song->end_ms,
		  player_buffer, pipe);
184 185
}

186 187 188 189 190 191 192 193 194 195 196 197
/**
 * Is the decoder still busy on the same song as the player?
 *
 * Note: this function does not check if the decoder is already
 * finished.
 */
static bool
player_dc_at_current_song(const struct player *player)
{
	assert(player != NULL);
	assert(player->pipe != NULL);

198
	return player->dc->pipe == player->pipe;
199 200 201
}

/**
202 203 204
 * 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.
205 206 207 208
 */
static bool
player_dc_at_next_song(const struct player *player)
{
209
	return player->dc->pipe != NULL && !player_dc_at_current_song(player);
210 211
}

212 213
/**
 * Stop the decoder and clears (and frees) its music pipe.
214 215
 *
 * Player lock is not held.
216
 */
217 218 219
static void
player_dc_stop(struct player *player)
{
220 221
	struct decoder_control *dc = player->dc;

222
	dc->Stop();
223

224
	if (dc->pipe != NULL) {
225 226
		/* clear and free the decoder pipe */

227
		music_pipe_clear(dc->pipe, player_buffer);
228

229 230
		if (dc->pipe != player->pipe)
			music_pipe_free(dc->pipe);
231

232
		dc->pipe = NULL;
233 234 235
	}
}

236 237 238 239
/**
 * 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.
240 241
 *
 * The player lock is not held.
242
 */
243 244
static bool
player_wait_for_decoder(struct player *player)
245
{
246
	struct player_control *pc = player->pc;
247 248
	struct decoder_control *dc = player->dc;

249 250
	assert(player->queued || pc->command == PLAYER_COMMAND_SEEK);
	assert(pc->next_song != NULL);
251 252 253

	player->queued = false;

254
	GError *error = dc->LockGetError();
255
	if (error != NULL) {
256 257
		pc->Lock();
		pc->SetError(PLAYER_ERROR_DECODER, error);
258

259
		pc->next_song->Free();
260
		pc->next_song = NULL;
261

262
		pc->Unlock();
263

264
		return false;
265 266
	}

267
	if (player->song != NULL)
268
		player->song->Free();
269

270
	player->song = pc->next_song;
271 272 273 274 275 276
	player->elapsed_time = 0.0;

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

277
	pc->Lock();
278 279

	/* update player_control's song information */
280
	pc->total_time = pc->next_song->GetDuration();
281
	pc->bit_rate = 0;
282
	pc->audio_format.Clear();
283

284
	/* clear the queued song */
285
	pc->next_song = NULL;
286

287
	pc->Unlock();
288

289
	/* call syncPlaylistWithQueue() in the main thread */
290
	GlobalEvents::Emit(GlobalEvents::PLAYLIST);
291

292
	return true;
293 294
}

295 296 297 298 299
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
static double
300
real_song_duration(const Song *song, double decoder_duration)
301 302 303 304 305
{
	assert(song != NULL);

	if (decoder_duration <= 0.0)
		/* the decoder plugin didn't provide information; fall
306 307
		   back to Song::GetDuration() */
		return song->GetDuration();
308 309 310 311 312 313 314

	if (song->end_ms > 0 && song->end_ms / 1000.0 < decoder_duration)
		return (song->end_ms - song->start_ms) / 1000.0;

	return decoder_duration - song->start_ms / 1000.0;
}

315 316 317 318 319 320 321 322 323
/**
 * Wrapper for audio_output_all_open().  Upon failure, it pauses the
 * player.
 *
 * @return true on success
 */
static bool
player_open_output(struct player *player)
{
Max Kellermann's avatar
Max Kellermann committed
324 325
	struct player_control *pc = player->pc;

326
	assert(player->play_audio_format.IsDefined());
Max Kellermann's avatar
Max Kellermann committed
327 328
	assert(pc->state == PLAYER_STATE_PLAY ||
	       pc->state == PLAYER_STATE_PAUSE);
329

330
	GError *error = NULL;
331
	if (audio_output_all_open(player->play_audio_format, player_buffer,
332
				  &error)) {
333
		player->output_open = true;
334 335
		player->paused = false;

336
		pc->Lock();
Max Kellermann's avatar
Max Kellermann committed
337
		pc->state = PLAYER_STATE_PLAY;
338
		pc->Unlock();
339

340 341
		idle_add(IDLE_PLAYER);

342 343
		return true;
	} else {
344 345
		g_warning("%s", error->message);

346 347
		player->output_open = false;

348 349 350 351
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		player->paused = true;

352 353
		pc->Lock();
		pc->SetError(PLAYER_ERROR_OUTPUT, error);
Max Kellermann's avatar
Max Kellermann committed
354
		pc->state = PLAYER_STATE_PAUSE;
355
		pc->Unlock();
356

357 358
		idle_add(IDLE_PLAYER);

359 360 361 362
		return false;
	}
}

363 364 365 366
/**
 * The decoder has acknowledged the "START" command (see
 * player_wait_for_decoder()).  This function checks if the decoder
 * initialization has completed yet.
367 368
 *
 * The player lock is not held.
369
 */
370 371 372
static bool
player_check_decoder_startup(struct player *player)
{
373
	struct player_control *pc = player->pc;
374 375
	struct decoder_control *dc = player->dc;

376 377
	assert(player->decoder_starting);

378
	dc->Lock();
379

380
	GError *error = dc->GetError();
381
	if (error != NULL) {
382
		/* the decoder failed */
383
		dc->Unlock();
384

385 386 387
		pc->Lock();
		pc->SetError(PLAYER_ERROR_DECODER, error);
		pc->Unlock();
388 389

		return false;
390
	} else if (!dc->IsStarting()) {
391
		/* the decoder is ready and ok */
392

393
		dc->Unlock();
394

395
		if (player->output_open &&
396
		    !audio_output_all_wait(pc, 1))
397 398 399 400
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

401
		pc->Lock();
402 403
		pc->total_time = real_song_duration(dc->song, dc->total_time);
		pc->audio_format = dc->in_audio_format;
404
		pc->Unlock();
405

406 407
		idle_add(IDLE_PLAYER);

408
		player->play_audio_format = dc->out_audio_format;
409 410
		player->decoder_starting = false;

411
		if (!player->paused && !player_open_output(player)) {
412
			char *uri = dc->song->GetURI();
413 414 415 416
			g_warning("problems opening audio device "
				  "while playing \"%s\"", uri);
			g_free(uri);

417 418
			return true;
		}
419 420 421 422 423

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
424
		dc->WaitForDecoder();
425
		dc->Unlock();
426 427 428 429 430

		return true;
	}
}

431 432 433 434
/**
 * 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.
435 436
 *
 * The player lock is not held.
437 438 439 440
 */
static bool
player_send_silence(struct player *player)
{
441
	assert(player->output_open);
442
	assert(player->play_audio_format.IsDefined());
443

444
	struct music_chunk *chunk = music_buffer_allocate(player_buffer);
445 446 447 448 449 450 451 452 453
	if (chunk == NULL) {
		g_warning("Failed to allocate silence buffer");
		return false;
	}

#ifndef NDEBUG
	chunk->audio_format = player->play_audio_format;
#endif

454
	const size_t frame_size = player->play_audio_format.GetFrameSize();
455 456 457 458
	/* this formula ensures that we don't send
	   partial frames */
	unsigned num_frames = sizeof(chunk->data) / frame_size;

459
	chunk->times = -1.0; /* undefined time stamp */
460 461 462
	chunk->length = num_frames * frame_size;
	memset(chunk->data, 0, chunk->length);

463 464 465 466 467
	GError *error = NULL;
	if (!audio_output_all_play(chunk, &error)) {
		g_warning("%s", error->message);
		g_error_free(error);

468 469 470 471 472 473 474
		music_buffer_return(player_buffer, chunk);
		return false;
	}

	return true;
}

475 476
/**
 * This is the handler for the #PLAYER_COMMAND_SEEK command.
477 478
 *
 * The player lock is not held.
479
 */
Max Kellermann's avatar
Max Kellermann committed
480
static bool player_seek_decoder(struct player *player)
481
{
482
	struct player_control *pc = player->pc;
483
	Song *song = pc->next_song;
484
	struct decoder_control *dc = player->dc;
485

486
	assert(pc->next_song != NULL);
487

488 489
	const unsigned start_ms = song->start_ms;

490
	if (!dc->LockIsCurrentSong(song)) {
491 492 493
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

494 495
		player_dc_stop(player);

496 497
		/* clear music chunks which might still reside in the
		   pipe */
498
		music_pipe_clear(player->pipe, player_buffer);
499

500
		/* re-start the decoder */
501
		player_dc_start(player, player->pipe);
502
		if (!player_wait_for_decoder(player)) {
503
			/* decoder failure */
504
			player_command_finished(pc);
505
			return false;
506
		}
507
	} else {
508 509 510 511 512
		if (!player_dc_at_current_song(player)) {
			/* the decoder is already decoding the "next" song,
			   but it is the same song file; exchange the pipe */
			music_pipe_clear(player->pipe, player_buffer);
			music_pipe_free(player->pipe);
513
			player->pipe = dc->pipe;
514 515
		}

516
		pc->next_song->Free();
517
		pc->next_song = NULL;
518
		player->queued = false;
519
	}
Max Kellermann's avatar
Max Kellermann committed
520

521 522 523
	/* wait for the decoder to complete initialization */

	while (player->decoder_starting) {
524
		if (!player_check_decoder_startup(player)) {
525
			/* decoder failure */
526
			player_command_finished(pc);
527 528 529 530
			return false;
		}
	}

531 532
	/* send the SEEK command */

533 534 535
	double where = pc->seek_where;
	if (where > pc->total_time)
		where = pc->total_time - 0.1;
Max Kellermann's avatar
Max Kellermann committed
536 537 538
	if (where < 0.0)
		where = 0.0;

539
	if (!dc->Seek(where + start_ms / 1000.0)) {
540
		/* decoder failure */
541
		player_command_finished(pc);
542 543
		return false;
	}
544

545 546
	player->elapsed_time = where;

547
	player_command_finished(pc);
548

549 550
	player->xfade = XFADE_UNKNOWN;

551 552
	/* re-fill the buffer after seeking */
	player->buffering = true;
553 554 555 556

	audio_output_all_cancel();

	return true;
557 558
}

559 560 561
/**
 * Player lock must be held before calling.
 */
Max Kellermann's avatar
Max Kellermann committed
562
static void player_process_command(struct player *player)
563
{
564
	struct player_control *pc = player->pc;
565
	gcc_unused struct decoder_control *dc = player->dc;
566

567
	switch (pc->command) {
568 569
	case PLAYER_COMMAND_NONE:
	case PLAYER_COMMAND_STOP:
Max Kellermann's avatar
Max Kellermann committed
570
	case PLAYER_COMMAND_EXIT:
571 572 573
	case PLAYER_COMMAND_CLOSE_AUDIO:
		break;

574
	case PLAYER_COMMAND_UPDATE_AUDIO:
575
		pc->Unlock();
576
		audio_output_all_enable_disable();
577
		pc->Lock();
578
		player_command_finished_locked(pc);
579 580
		break;

581
	case PLAYER_COMMAND_QUEUE:
582
		assert(pc->next_song != NULL);
583
		assert(!player->queued);
584
		assert(!player_dc_at_next_song(player));
585

586
		player->queued = true;
587
		player_command_finished_locked(pc);
588 589 590
		break;

	case PLAYER_COMMAND_PAUSE:
591
		pc->Unlock();
592

593 594
		player->paused = !player->paused;
		if (player->paused) {
595
			audio_output_all_pause();
596
			pc->Lock();
597

598
			pc->state = PLAYER_STATE_PAUSE;
599
		} else if (!player->play_audio_format.IsDefined()) {
600 601
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
602
			pc->Lock();
603

604
			pc->state = PLAYER_STATE_PLAY;
605
		} else {
606
			player_open_output(player);
607

608
			pc->Lock();
609
		}
610

611
		player_command_finished_locked(pc);
612 613 614
		break;

	case PLAYER_COMMAND_SEEK:
615
		pc->Unlock();
616
		player_seek_decoder(player);
617
		pc->Lock();
618
		break;
619 620

	case PLAYER_COMMAND_CANCEL:
621
		if (pc->next_song == NULL) {
622
			/* the cancel request arrived too late, we're
623 624
			   already playing the queued song...  stop
			   everything now */
625
			pc->command = PLAYER_COMMAND_STOP;
626 627 628
			return;
		}

629
		if (player_dc_at_next_song(player)) {
630 631
			/* the decoder is already decoding the song -
			   stop it and reset the position */
632
			pc->Unlock();
633
			player_dc_stop(player);
634
			pc->Lock();
635
		}
636

637
		pc->next_song->Free();
638
		pc->next_song = NULL;
639
		player->queued = false;
640
		player_command_finished_locked(pc);
641
		break;
642 643

	case PLAYER_COMMAND_REFRESH:
644
		if (player->output_open && !player->paused) {
645
			pc->Unlock();
646
			audio_output_all_check();
647
			pc->Lock();
648
		}
649

650 651 652
		pc->elapsed_time = audio_output_all_get_elapsed_time();
		if (pc->elapsed_time < 0.0)
			pc->elapsed_time = player->elapsed_time;
653

654
		player_command_finished_locked(pc);
655
		break;
656 657 658
	}
}

659
static void
Max Kellermann's avatar
Max Kellermann committed
660
update_song_tag(Song *song, const Tag &new_tag)
661
{
662
	if (song->IsFile())
663 664 665 666
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

Max Kellermann's avatar
Max Kellermann committed
667 668
	Tag *old_tag = song->tag;
	song->tag = new Tag(new_tag);
669

Max Kellermann's avatar
Max Kellermann committed
670
	delete old_tag;
671 672 673

	/* the main thread will update the playlist version when he
	   receives this event */
674
	GlobalEvents::Emit(GlobalEvents::TAG);
675 676 677 678 679 680

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

681 682 683 684
/**
 * Plays a #music_chunk object (after applying software volume).  If
 * it contains a (stream) tag, copy it to the current song, so MPD's
 * playlist reflects the new stream tag.
685 686
 *
 * Player lock is not held.
687
 */
688
static bool
689
play_chunk(struct player_control *pc,
690
	   Song *song, struct music_chunk *chunk,
691
	   const AudioFormat format,
692
	   GError **error_r)
693
{
694
	assert(chunk->CheckFormat(format));
695

696
	if (chunk->tag != NULL)
Max Kellermann's avatar
Max Kellermann committed
697
		update_song_tag(song, *chunk->tag);
698

699 700
	if (chunk->length == 0) {
		music_buffer_return(player_buffer, chunk);
701
		return true;
702
	}
703

704
	pc->Lock();
705
	pc->bit_rate = chunk->bit_rate;
706
	pc->Unlock();
707

708 709
	/* send the chunk to the audio outputs */

710
	if (!audio_output_all_play(chunk, error_r))
711
		return false;
712

713
	pc->total_play_time += (double)chunk->length /
714
		format.GetTimeToSize();
715
	return true;
716 717
}

718 719 720 721 722 723 724 725 726
/**
 * 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)
 */
static bool
play_next_chunk(struct player *player)
{
727
	struct player_control *pc = player->pc;
728
	struct decoder_control *dc = player->dc;
729

730
	if (!audio_output_all_wait(pc, 64))
731 732
		/* the output pipe is still large enough, don't send
		   another chunk */
733 734
		return true;

735 736
	unsigned cross_fade_position;
	struct music_chunk *chunk = NULL;
737
	if (player->xfade == XFADE_ENABLED &&
738
	    player_dc_at_next_song(player) &&
739 740 741 742
	    (cross_fade_position = music_pipe_size(player->pipe))
	    <= player->cross_fade_chunks) {
		/* perform cross fade */
		struct music_chunk *other_chunk =
743
			music_pipe_shift(dc->pipe);
744 745

		if (!player->cross_fading) {
746 747 748 749
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
750 751 752 753 754 755 756
			player->cross_fade_chunks = cross_fade_position;
			player->cross_fading = true;
		}

		if (other_chunk != NULL) {
			chunk = music_pipe_shift(player->pipe);
			assert(chunk != NULL);
757
			assert(chunk->other == NULL);
758

759 760 761 762
			/* don't send the tags of the new song (which
			   is being faded in) yet; postpone it until
			   the current song is faded out */
			player->cross_fade_tag =
Max Kellermann's avatar
Max Kellermann committed
763
				Tag::MergeReplace(player->cross_fade_tag,
764 765 766
						  other_chunk->tag);
			other_chunk->tag = NULL;

767
			if (std::isnan(pc->mixramp_delay_seconds)) {
768
				chunk->mix_ratio = ((float)cross_fade_position)
769 770
					     / player->cross_fade_chunks;
			} else {
771
				chunk->mix_ratio = nan("");
772
			}
773

774
			if (other_chunk->IsEmpty()) {
775 776 777 778 779 780 781 782 783 784 785
				/* the "other" chunk was a music_chunk
				   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 */
				music_buffer_return(player_buffer,
						    other_chunk);
				other_chunk = NULL;
			}
786

787
			chunk->other = other_chunk;
788
		} else {
789
			/* there are not enough decoded chunks yet */
790

791
			dc->Lock();
792

793
			if (dc->IsIdle()) {
794
				/* the decoder isn't running, abort
795
				   cross fading */
796
				dc->Unlock();
797

798 799
				player->xfade = XFADE_DISABLED;
			} else {
800
				/* wait for the decoder */
801
				dc->Signal();
802
				dc->WaitForDecoder();
803
				dc->Unlock();
804

805 806 807 808 809 810 811 812 813 814
				return true;
			}
		}
	}

	if (chunk == NULL)
		chunk = music_pipe_shift(player->pipe);

	assert(chunk != NULL);

815 816 817
	/* insert the postponed tag if cross-fading is finished */

	if (player->xfade != XFADE_ENABLED && player->cross_fade_tag != NULL) {
Max Kellermann's avatar
Max Kellermann committed
818
		chunk->tag = Tag::MergeReplace(chunk->tag,
819 820 821 822
					       player->cross_fade_tag);
		player->cross_fade_tag = NULL;
	}

823 824
	/* play the current chunk */

825
	GError *error = NULL;
826
	if (!play_chunk(player->pc, player->song, chunk,
827
			player->play_audio_format, &error)) {
828 829
		g_warning("%s", error->message);

830
		music_buffer_return(player_buffer, chunk);
831

832
		pc->Lock();
833

834
		pc->SetError(PLAYER_ERROR_OUTPUT, error);
835

836 837
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
838
		pc->state = PLAYER_STATE_PAUSE;
839 840
		player->paused = true;

841
		pc->Unlock();
842

843 844
		idle_add(IDLE_PLAYER);

845
		return false;
846
	}
847

848 849
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
850
	   larger block at a time */
851 852
	dc->Lock();
	if (!dc->IsIdle() &&
853
	    music_pipe_size(dc->pipe) <= (pc->buffered_before_play +
854
					 music_buffer_size(player_buffer) * 3) / 4)
855 856
		dc->Signal();
	dc->Unlock();
857 858 859 860

	return true;
}

861 862 863 864 865
/**
 * 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.
 *
866 867
 * The player lock is not held.
 *
868 869 870 871 872 873 874
 * @return true on success, false on error (playback will be stopped)
 */
static bool
player_song_border(struct player *player)
{
	player->xfade = XFADE_UNKNOWN;

875
	char *uri = player->song->GetURI();
876 877 878
	g_message("played \"%s\"", uri);
	g_free(uri);

879
	music_pipe_free(player->pipe);
880
	player->pipe = player->dc->pipe;
881

882 883
	audio_output_all_song_border();

884 885 886
	if (!player_wait_for_decoder(player))
		return false;

887
	struct player_control *const pc = player->pc;
888
	pc->Lock();
889

890 891
	const bool border_pause = pc->border_pause;
	if (border_pause) {
892 893 894 895
		player->paused = true;
		pc->state = PLAYER_STATE_PAUSE;
	}

896
	pc->Unlock();
897

898 899 900
	if (border_pause)
		idle_add(IDLE_PLAYER);

901
	return true;
902 903
}

904 905 906 907 908
/*
 * 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.
 */
909
static void do_play(struct player_control *pc, struct decoder_control *dc)
910
{
911
	player player(pc, dc);
912

913
	pc->Unlock();
914

915
	player.pipe = music_pipe_new();
916

917
	player_dc_start(&player, player.pipe);
918
	if (!player_wait_for_decoder(&player)) {
919 920
		assert(player.song == NULL);

921
		player_dc_stop(&player);
922
		player_command_finished(pc);
923
		music_pipe_free(player.pipe);
924
		GlobalEvents::Emit(GlobalEvents::PLAYLIST);
925
		pc->Lock();
926
		return;
927
	}
928

929
	pc->Lock();
930
	pc->state = PLAYER_STATE_PLAY;
931

Max Kellermann's avatar
Max Kellermann committed
932 933
	if (pc->command == PLAYER_COMMAND_SEEK)
		player.elapsed_time = pc->seek_where;
934

935
	player_command_finished_locked(pc);
936

937
	while (true) {
Max Kellermann's avatar
Max Kellermann committed
938
		player_process_command(&player);
939 940 941
		if (pc->command == PLAYER_COMMAND_STOP ||
		    pc->command == PLAYER_COMMAND_EXIT ||
		    pc->command == PLAYER_COMMAND_CLOSE_AUDIO) {
942
			pc->Unlock();
943
			audio_output_all_cancel();
944 945 946
			break;
		}

947
		pc->Unlock();
948

949
		if (player.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 (music_pipe_size(player.pipe) < pc->buffered_before_play &&
955
			    !dc->LockIsIdle()) {
956
				/* not enough decoded buffer space yet */
957 958

				if (!player.paused &&
959
				    player.output_open &&
960 961 962 963
				    audio_output_all_check() < 4 &&
				    !player_send_silence(&player))
					break;

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

976
		if (player.decoder_starting) {
977
			/* wait until the decoder is initialized completely */
978

979
			if (!player_check_decoder_startup(&player))
980
				break;
981

982
			pc->Lock();
983
			continue;
984 985
		}

986
#ifndef NDEBUG
987
		/*
988 989
		music_pipe_check_format(&play_audio_format,
					player.next_song_chunk,
990
					&dc->out_audio_format);
991
		*/
992 993
#endif

994
		if (dc->LockIsIdle() && player.queued &&
995
		    dc->pipe == player.pipe) {
996 997
			/* the decoder has finished the current song;
			   make it decode the next song */
998

999
			assert(dc->pipe == NULL || dc->pipe == player.pipe);
1000

1001
			player_dc_start(&player, music_pipe_new());
1002
		}
1003

1004 1005 1006 1007
		if (/* no cross-fading if MPD is going to pause at the
		       end of the current song */
		    !pc->border_pause &&
		    player_dc_at_next_song(&player) &&
1008
		    player.xfade == XFADE_UNKNOWN &&
1009
		    !dc->LockIsStarting()) {
1010 1011 1012
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
1013
			player.cross_fade_chunks =
1014 1015 1016
				cross_fade_calc(pc->cross_fade_seconds, dc->total_time,
						pc->mixramp_db,
						pc->mixramp_delay_seconds,
1017 1018
						dc->replay_gain_db,
						dc->replay_gain_prev_db,
1019 1020
						dc->mixramp_start,
						dc->mixramp_prev_end,
1021 1022
						dc->out_audio_format,
						player.play_audio_format,
1023
						music_buffer_size(player_buffer) -
1024
						pc->buffered_before_play);
1025
			if (player.cross_fade_chunks > 0) {
1026
				player.xfade = XFADE_ENABLED;
1027
				player.cross_fading = false;
1028 1029 1030
			} else
				/* cross fading is disabled or the
				   next song is too short */
1031
				player.xfade = XFADE_DISABLED;
1032 1033
		}

1034
		if (player.paused) {
1035
			pc->Lock();
1036

1037
			if (pc->command == PLAYER_COMMAND_NONE)
1038
				pc->Wait();
1039
			continue;
1040
		} else if (!music_pipe_empty(player.pipe)) {
1041 1042
			/* at least one music chunk is ready - send it
			   to the audio output */
1043

1044
			play_next_chunk(&player);
1045 1046 1047 1048 1049 1050 1051
		} else if (audio_output_all_check() > 0) {
			/* not enough data from decoder, but the
			   output thread is still busy, so it's
			   okay */

			/* XXX synchronize in a better way */
			g_usleep(10000);
1052
		} else if (player_dc_at_next_song(&player)) {
1053 1054
			/* at the beginning of a new song */

1055
			if (!player_song_border(&player))
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 (music_pipe_empty(player.pipe)) {
1062 1063 1064
				/* wait for the hardware to finish
				   playback */
				audio_output_all_drain();
1065
				break;
1066
			}
1067
		} else if (player.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 (!player_send_silence(&player))
1072 1073
				break;
		}
1074

1075
		pc->Lock();
1076 1077
	}

1078
	player_dc_stop(&player);
1079

1080
	music_pipe_clear(player.pipe, player_buffer);
1081
	music_pipe_free(player.pipe);
1082

Max Kellermann's avatar
Max Kellermann committed
1083
	delete player.cross_fade_tag;
1084

1085
	if (player.song != NULL)
1086
		player.song->Free();
1087

1088
	pc->Lock();
1089 1090

	if (player.queued) {
1091
		assert(pc->next_song != NULL);
1092
		pc->next_song->Free();
1093
		pc->next_song = NULL;
1094 1095
	}

1096
	pc->state = PLAYER_STATE_STOP;
1097

1098
	pc->Unlock();
1099

1100
	GlobalEvents::Emit(GlobalEvents::PLAYLIST);
1101

1102
	pc->Lock();
1103 1104
}

1105 1106
static gpointer
player_task(gpointer arg)
1107
{
1108
	struct player_control *pc = (struct player_control *)arg;
1109

1110
	struct decoder_control *dc = new decoder_control();
1111
	decoder_thread_start(dc);
1112

1113
	player_buffer = music_buffer_new(pc->buffer_chunks);
1114

1115
	pc->Lock();
1116

1117
	while (1) {
1118
		switch (pc->command) {
1119
		case PLAYER_COMMAND_SEEK:
1120
		case PLAYER_COMMAND_QUEUE:
1121
			assert(pc->next_song != NULL);
1122

1123
			do_play(pc, dc);
1124 1125 1126
			break;

		case PLAYER_COMMAND_STOP:
1127
			pc->Unlock();
1128
			audio_output_all_cancel();
1129
			pc->Lock();
1130

1131 1132
			/* fall through */

1133
		case PLAYER_COMMAND_PAUSE:
1134
			if (pc->next_song != NULL) {
1135
				pc->next_song->Free();
1136 1137 1138
				pc->next_song = NULL;
			}

1139
			player_command_finished_locked(pc);
1140 1141 1142
			break;

		case PLAYER_COMMAND_CLOSE_AUDIO:
1143
			pc->Unlock();
1144

1145
			audio_output_all_release();
1146

1147
			pc->Lock();
1148
			player_command_finished_locked(pc);
1149 1150 1151 1152 1153 1154

#ifndef NDEBUG
			/* in the DEBUG build, check for leaked
			   music_chunk objects by freeing the
			   music_buffer */
			music_buffer_free(player_buffer);
1155
			player_buffer = music_buffer_new(pc->buffer_chunks);
1156 1157
#endif

1158 1159
			break;

1160
		case PLAYER_COMMAND_UPDATE_AUDIO:
1161
			pc->Unlock();
1162
			audio_output_all_enable_disable();
1163
			pc->Lock();
1164
			player_command_finished_locked(pc);
1165 1166
			break;

Max Kellermann's avatar
Max Kellermann committed
1167
		case PLAYER_COMMAND_EXIT:
1168
			pc->Unlock();
1169

1170 1171
			dc->Quit();
			delete dc;
1172
			audio_output_all_close();
1173
			music_buffer_free(player_buffer);
1174

1175
			player_command_finished(pc);
1176
			return NULL;
Max Kellermann's avatar
Max Kellermann committed
1177

1178
		case PLAYER_COMMAND_CANCEL:
1179
			if (pc->next_song != NULL) {
1180
				pc->next_song->Free();
1181 1182 1183
				pc->next_song = NULL;
			}

1184
			player_command_finished_locked(pc);
1185 1186
			break;

1187 1188
		case PLAYER_COMMAND_REFRESH:
			/* no-op when not playing */
1189
			player_command_finished_locked(pc);
1190 1191
			break;

1192
		case PLAYER_COMMAND_NONE:
1193
			pc->Wait();
1194 1195 1196 1197 1198
			break;
		}
	}
}

1199 1200
void
player_create(struct player_control *pc)
1201
{
1202
	assert(pc->thread == NULL);
1203

1204 1205 1206
#if GLIB_CHECK_VERSION(2,32,0)
	pc->thread = g_thread_new("player", player_task, pc);
#else
1207
	GError *e = NULL;
1208 1209
	pc->thread = g_thread_create(player_task, pc, true, &e);
	if (pc->thread == NULL)
1210
		FatalError("Failed to spawn player task", e);
1211
#endif
1212
}