player_thread.c 26.4 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright (C) 2003-2011 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 "player_thread.h"
22
#include "player_control.h"
23
#include "decoder_control.h"
24
#include "decoder_thread.h"
25
#include "output_all.h"
26
#include "pcm_volume.h"
27
#include "path.h"
28
#include "event_pipe.h"
29
#include "crossfade.h"
30
#include "song.h"
31
#include "tag.h"
32
#include "pipe.h"
33
#include "chunk.h"
34
#include "idle.h"
35
#include "main.h"
36
#include "buffer.h"
37
#include "mpd_error.h"
38

39 40
#include <glib.h>

41 42 43
#undef G_LOG_DOMAIN
#define G_LOG_DOMAIN "player_thread"

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

50
struct player {
51 52
	struct player_control *pc;

53 54
	struct decoder_control *dc;

55 56
	struct music_pipe *pipe;

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

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

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

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

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

86 87 88 89 90
	/**
	 * the song currently being played
	 */
	struct song *song;

91 92 93 94
	/**
	 * is cross fading enabled?
	 */
	enum xfade_state xfade;
95

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

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

106 107 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.
	 */
	struct tag *cross_fade_tag;

113 114 115 116
	/**
	 * The current audio format for the audio outputs.
	 */
	struct audio_format play_audio_format;
117 118 119 120 121 122

	/**
	 * 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
123
	 * precisely.
124 125
	 */
	float elapsed_time;
126 127
};

128 129
static struct music_buffer *player_buffer;

130 131
static void
player_command_finished_locked(struct player_control *pc)
132
{
133
	assert(pc->command != PLAYER_COMMAND_NONE);
134

135
	pc->command = PLAYER_COMMAND_NONE;
136 137 138
	g_cond_signal(main_cond);
}

139 140
static void
player_command_finished(struct player_control *pc)
141
{
142 143 144
	player_lock(pc);
	player_command_finished_locked(pc);
	player_unlock(pc);
145 146
}

147 148 149 150 151 152
/**
 * Start the decoder.
 *
 * Player lock is not held.
 */
static void
153
player_dc_start(struct player *player, struct music_pipe *pipe)
154
{
155
	struct player_control *pc = player->pc;
156 157
	struct decoder_control *dc = player->dc;

158 159
	assert(player->queued || pc->command == PLAYER_COMMAND_SEEK);
	assert(pc->next_song != NULL);
160

Max Kellermann's avatar
Max Kellermann committed
161 162 163
	unsigned start_ms = pc->next_song->start_ms;
	if (pc->command == PLAYER_COMMAND_SEEK)
		start_ms += (unsigned)(pc->seek_where * 1000);
164

Max Kellermann's avatar
Max Kellermann committed
165 166
	dc_start(dc, pc->next_song,
		 start_ms, pc->next_song->end_ms,
167
		 player_buffer, pipe);
168 169
}

170 171 172 173 174 175 176 177 178 179 180 181
/**
 * 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);

182
	return player->dc->pipe == player->pipe;
183 184 185
}

/**
186 187 188
 * 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.
189 190 191 192
 */
static bool
player_dc_at_next_song(const struct player *player)
{
193
	return player->dc->pipe != NULL && !player_dc_at_current_song(player);
194 195
}

196 197
/**
 * Stop the decoder and clears (and frees) its music pipe.
198 199
 *
 * Player lock is not held.
200
 */
201 202 203
static void
player_dc_stop(struct player *player)
{
204 205 206
	struct decoder_control *dc = player->dc;

	dc_stop(dc);
207

208
	if (dc->pipe != NULL) {
209 210
		/* clear and free the decoder pipe */

211
		music_pipe_clear(dc->pipe, player_buffer);
212

213 214
		if (dc->pipe != player->pipe)
			music_pipe_free(dc->pipe);
215

216
		dc->pipe = NULL;
217 218 219
	}
}

220 221 222 223
/**
 * 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.
224 225
 *
 * The player lock is not held.
226
 */
227 228
static bool
player_wait_for_decoder(struct player *player)
229
{
230
	struct player_control *pc = player->pc;
231 232
	struct decoder_control *dc = player->dc;

233 234
	assert(player->queued || pc->command == PLAYER_COMMAND_SEEK);
	assert(pc->next_song != NULL);
235 236 237

	player->queued = false;

238
	if (decoder_lock_has_failed(dc)) {
239 240 241 242 243
		player_lock(pc);
		pc->errored_song = dc->song;
		pc->error = PLAYER_ERROR_FILE;
		pc->next_song = NULL;
		player_unlock(pc);
244

245
		return false;
246 247
	}

248
	player->song = pc->next_song;
249 250 251 252 253 254
	player->elapsed_time = 0.0;

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

255
	player_lock(pc);
256 257

	/* update player_control's song information */
258 259 260
	pc->total_time = song_get_duration(pc->next_song);
	pc->bit_rate = 0;
	audio_format_clear(&pc->audio_format);
261

262
	/* clear the queued song */
263
	pc->next_song = NULL;
264

265
	player_unlock(pc);
266

267 268 269
	/* call syncPlaylistWithQueue() in the main thread */
	event_pipe_emit(PIPE_EVENT_PLAYLIST);

270
	return true;
271 272
}

273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
/**
 * Returns the real duration of the song, comprising the duration
 * indicated by the decoder plugin.
 */
static double
real_song_duration(const struct song *song, double decoder_duration)
{
	assert(song != NULL);

	if (decoder_duration <= 0.0)
		/* the decoder plugin didn't provide information; fall
		   back to song_get_duration() */
		return song_get_duration(song);

	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;
}

293 294 295 296 297 298 299 300 301
/**
 * 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
302 303
	struct player_control *pc = player->pc;

304
	assert(audio_format_defined(&player->play_audio_format));
Max Kellermann's avatar
Max Kellermann committed
305 306
	assert(pc->state == PLAYER_STATE_PLAY ||
	       pc->state == PLAYER_STATE_PAUSE);
307 308

	if (audio_output_all_open(&player->play_audio_format, player_buffer)) {
309
		player->output_open = true;
310 311
		player->paused = false;

Max Kellermann's avatar
Max Kellermann committed
312 313 314
		player_lock(pc);
		pc->state = PLAYER_STATE_PLAY;
		player_unlock(pc);
315 316 317

		return true;
	} else {
318 319
		player->output_open = false;

320 321 322 323
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		player->paused = true;

Max Kellermann's avatar
Max Kellermann committed
324 325 326 327
		player_lock(pc);
		pc->error = PLAYER_ERROR_AUDIO;
		pc->state = PLAYER_STATE_PAUSE;
		player_unlock(pc);
328 329 330 331 332

		return false;
	}
}

333 334 335 336
/**
 * The decoder has acknowledged the "START" command (see
 * player_wait_for_decoder()).  This function checks if the decoder
 * initialization has completed yet.
337 338
 *
 * The player lock is not held.
339
 */
340 341 342
static bool
player_check_decoder_startup(struct player *player)
{
343
	struct player_control *pc = player->pc;
344 345
	struct decoder_control *dc = player->dc;

346 347
	assert(player->decoder_starting);

348
	decoder_lock(dc);
349

350
	if (decoder_has_failed(dc)) {
351
		/* the decoder failed */
352
		decoder_unlock(dc);
353

354 355 356 357
		player_lock(pc);
		pc->errored_song = dc->song;
		pc->error = PLAYER_ERROR_FILE;
		player_unlock(pc);
358 359

		return false;
360
	} else if (!decoder_is_starting(dc)) {
361
		/* the decoder is ready and ok */
362

363
		decoder_unlock(dc);
364

365
		if (player->output_open &&
366
		    !audio_output_all_wait(pc, 1))
367 368 369 370
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

371 372 373 374
		player_lock(pc);
		pc->total_time = real_song_duration(dc->song, dc->total_time);
		pc->audio_format = dc->in_audio_format;
		player_unlock(pc);
375

376
		player->play_audio_format = dc->out_audio_format;
377 378
		player->decoder_starting = false;

379
		if (!player->paused && !player_open_output(player)) {
380
			char *uri = song_get_uri(dc->song);
381 382 383 384
			g_warning("problems opening audio device "
				  "while playing \"%s\"", uri);
			g_free(uri);

385 386
			return true;
		}
387 388 389 390 391

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
392
		player_wait_decoder(pc, dc);
393
		decoder_unlock(dc);
394 395 396 397 398

		return true;
	}
}

399 400 401 402
/**
 * 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.
403 404
 *
 * The player lock is not held.
405 406 407 408
 */
static bool
player_send_silence(struct player *player)
{
409
	assert(player->output_open);
410 411
	assert(audio_format_defined(&player->play_audio_format));

412
	struct music_chunk *chunk = music_buffer_allocate(player_buffer);
413 414 415 416 417 418 419 420 421
	if (chunk == NULL) {
		g_warning("Failed to allocate silence buffer");
		return false;
	}

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

422 423 424 425 426 427
	size_t frame_size =
		audio_format_frame_size(&player->play_audio_format);
	/* this formula ensures that we don't send
	   partial frames */
	unsigned num_frames = sizeof(chunk->data) / frame_size;

428
	chunk->times = -1.0; /* undefined time stamp */
429 430 431 432 433 434 435 436 437 438 439
	chunk->length = num_frames * frame_size;
	memset(chunk->data, 0, chunk->length);

	if (!audio_output_all_play(chunk)) {
		music_buffer_return(player_buffer, chunk);
		return false;
	}

	return true;
}

440 441
/**
 * This is the handler for the #PLAYER_COMMAND_SEEK command.
442 443
 *
 * The player lock is not held.
444
 */
Max Kellermann's avatar
Max Kellermann committed
445
static bool player_seek_decoder(struct player *player)
446
{
447 448
	struct player_control *pc = player->pc;
	struct song *song = pc->next_song;
449
	struct decoder_control *dc = player->dc;
450

451
	assert(pc->next_song != NULL);
452

453 454
	const unsigned start_ms = song->start_ms;

455
	if (decoder_current_song(dc) != song) {
456 457 458
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

459 460
		player_dc_stop(player);

461 462
		/* clear music chunks which might still reside in the
		   pipe */
463
		music_pipe_clear(player->pipe, player_buffer);
464

465
		/* re-start the decoder */
466
		player_dc_start(player, player->pipe);
467
		if (!player_wait_for_decoder(player)) {
468
			/* decoder failure */
469
			player_command_finished(pc);
470
			return false;
471
		}
472
	} else {
473 474 475 476 477
		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);
478
			player->pipe = dc->pipe;
479 480
		}

481
		pc->next_song = NULL;
482
		player->queued = false;
483
	}
Max Kellermann's avatar
Max Kellermann committed
484

485 486 487
	/* wait for the decoder to complete initialization */

	while (player->decoder_starting) {
488
		if (!player_check_decoder_startup(player)) {
489
			/* decoder failure */
490
			player_command_finished(pc);
491 492 493 494
			return false;
		}
	}

495 496
	/* send the SEEK command */

497 498 499
	double where = pc->seek_where;
	if (where > pc->total_time)
		where = pc->total_time - 0.1;
Max Kellermann's avatar
Max Kellermann committed
500 501 502
	if (where < 0.0)
		where = 0.0;

503
	if (!dc_seek(dc, where + start_ms / 1000.0)) {
504
		/* decoder failure */
505
		player_command_finished(pc);
506 507
		return false;
	}
508

509 510
	player->elapsed_time = where;

511
	player_command_finished(pc);
512

513 514
	player->xfade = XFADE_UNKNOWN;

515 516
	/* re-fill the buffer after seeking */
	player->buffering = true;
517 518 519 520

	audio_output_all_cancel();

	return true;
521 522
}

523 524 525
/**
 * Player lock must be held before calling.
 */
Max Kellermann's avatar
Max Kellermann committed
526
static void player_process_command(struct player *player)
527
{
528
	struct player_control *pc = player->pc;
529
	G_GNUC_UNUSED struct decoder_control *dc = player->dc;
530

531
	switch (pc->command) {
532 533
	case PLAYER_COMMAND_NONE:
	case PLAYER_COMMAND_STOP:
Max Kellermann's avatar
Max Kellermann committed
534
	case PLAYER_COMMAND_EXIT:
535 536 537
	case PLAYER_COMMAND_CLOSE_AUDIO:
		break;

538
	case PLAYER_COMMAND_UPDATE_AUDIO:
539
		player_unlock(pc);
540
		audio_output_all_enable_disable();
541 542
		player_lock(pc);
		player_command_finished_locked(pc);
543 544
		break;

545
	case PLAYER_COMMAND_QUEUE:
546
		assert(pc->next_song != NULL);
547
		assert(!player->queued);
548
		assert(!player_dc_at_next_song(player));
549

550
		player->queued = true;
551
		player_command_finished_locked(pc);
552 553 554
		break;

	case PLAYER_COMMAND_PAUSE:
555
		player_unlock(pc);
556

557 558
		player->paused = !player->paused;
		if (player->paused) {
559
			audio_output_all_pause();
560
			player_lock(pc);
561

562
			pc->state = PLAYER_STATE_PAUSE;
563 564 565
		} else if (!audio_format_defined(&player->play_audio_format)) {
			/* the decoder hasn't provided an audio format
			   yet - don't open the audio device yet */
566
			player_lock(pc);
567

568
			pc->state = PLAYER_STATE_PLAY;
569
		} else {
570
			player_open_output(player);
571

572
			player_lock(pc);
573
		}
574

575
		player_command_finished_locked(pc);
576 577 578
		break;

	case PLAYER_COMMAND_SEEK:
579
		player_unlock(pc);
580
		player_seek_decoder(player);
581
		player_lock(pc);
582
		break;
583 584

	case PLAYER_COMMAND_CANCEL:
585
		if (pc->next_song == NULL) {
586
			/* the cancel request arrived too late, we're
587 588
			   already playing the queued song...  stop
			   everything now */
589
			pc->command = PLAYER_COMMAND_STOP;
590 591 592
			return;
		}

593
		if (player_dc_at_next_song(player)) {
594 595
			/* the decoder is already decoding the song -
			   stop it and reset the position */
596
			player_unlock(pc);
597
			player_dc_stop(player);
598
			player_lock(pc);
599
		}
600

601
		pc->next_song = NULL;
602
		player->queued = false;
603
		player_command_finished_locked(pc);
604
		break;
605 606

	case PLAYER_COMMAND_REFRESH:
607
		if (player->output_open && !player->paused) {
608
			player_unlock(pc);
609
			audio_output_all_check();
610
			player_lock(pc);
611
		}
612

613 614 615
		pc->elapsed_time = audio_output_all_get_elapsed_time();
		if (pc->elapsed_time < 0.0)
			pc->elapsed_time = player->elapsed_time;
616

617
		player_command_finished_locked(pc);
618
		break;
619 620 621
	}
}

622 623 624 625 626 627 628 629
static void
update_song_tag(struct song *song, const struct tag *new_tag)
{
	if (song_is_file(song))
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

630
	struct tag *old_tag = song->tag;
631 632 633 634 635 636 637 638 639 640 641 642 643 644
	song->tag = tag_dup(new_tag);

	if (old_tag != NULL)
		tag_free(old_tag);

	/* the main thread will update the playlist version when he
	   receives this event */
	event_pipe_emit(PIPE_EVENT_TAG);

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

645 646 647 648
/**
 * 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.
649 650
 *
 * Player lock is not held.
651
 */
652
static bool
653 654
play_chunk(struct player_control *pc,
	   struct song *song, struct music_chunk *chunk,
655
	   const struct audio_format *format)
656
{
657 658
	assert(music_chunk_check_format(chunk, format));

659 660
	if (chunk->tag != NULL)
		update_song_tag(song, chunk->tag);
661

662 663
	if (chunk->length == 0) {
		music_buffer_return(player_buffer, chunk);
664
		return true;
665
	}
666

Max Kellermann's avatar
Max Kellermann committed
667
	player_lock(pc);
668
	pc->bit_rate = chunk->bit_rate;
Max Kellermann's avatar
Max Kellermann committed
669
	player_unlock(pc);
670

671 672
	/* send the chunk to the audio outputs */

673
	if (!audio_output_all_play(chunk))
674
		return false;
675

676
	pc->total_play_time += (double)chunk->length /
677
		audio_format_time_to_size(format);
678
	return true;
679 680
}

681 682 683 684 685 686 687 688 689
/**
 * 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)
{
690
	struct player_control *pc = player->pc;
691
	struct decoder_control *dc = player->dc;
692

693
	if (!audio_output_all_wait(pc, 64))
694 695
		/* the output pipe is still large enough, don't send
		   another chunk */
696 697
		return true;

698 699
	unsigned cross_fade_position;
	struct music_chunk *chunk = NULL;
700
	if (player->xfade == XFADE_ENABLED &&
701
	    player_dc_at_next_song(player) &&
702 703 704 705
	    (cross_fade_position = music_pipe_size(player->pipe))
	    <= player->cross_fade_chunks) {
		/* perform cross fade */
		struct music_chunk *other_chunk =
706
			music_pipe_shift(dc->pipe);
707 708

		if (!player->cross_fading) {
709 710 711 712
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
713 714 715 716 717 718 719
			player->cross_fade_chunks = cross_fade_position;
			player->cross_fading = true;
		}

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

722 723 724 725 726 727 728 729
			/* 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 =
				tag_merge_replace(player->cross_fade_tag,
						  other_chunk->tag);
			other_chunk->tag = NULL;

730
			if (isnan(pc->mixramp_delay_seconds)) {
731
				chunk->mix_ratio = ((float)cross_fade_position)
732 733
					     / player->cross_fade_chunks;
			} else {
734
				chunk->mix_ratio = nan("");
735
			}
736 737 738 739 740 741 742 743 744 745 746 747 748

			if (music_chunk_is_empty(other_chunk)) {
				/* 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;
			}
749

750
			chunk->other = other_chunk;
751
		} else {
752
			/* there are not enough decoded chunks yet */
753

754
			decoder_lock(dc);
755

756
			if (decoder_is_idle(dc)) {
757
				/* the decoder isn't running, abort
758
				   cross fading */
759
				decoder_unlock(dc);
760

761 762
				player->xfade = XFADE_DISABLED;
			} else {
763
				/* wait for the decoder */
764
				decoder_signal(dc);
765
				player_wait_decoder(pc, dc);
766
				decoder_unlock(dc);
767

768 769 770 771 772 773 774 775 776 777
				return true;
			}
		}
	}

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

	assert(chunk != NULL);

778 779 780 781 782 783 784 785
	/* insert the postponed tag if cross-fading is finished */

	if (player->xfade != XFADE_ENABLED && player->cross_fade_tag != NULL) {
		chunk->tag = tag_merge_replace(chunk->tag,
					       player->cross_fade_tag);
		player->cross_fade_tag = NULL;
	}

786 787
	/* play the current chunk */

788 789
	if (!play_chunk(player->pc, player->song, chunk,
			&player->play_audio_format)) {
790
		music_buffer_return(player_buffer, chunk);
791

792
		player_lock(pc);
793

794
		pc->error = PLAYER_ERROR_AUDIO;
795

796 797
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
798
		pc->state = PLAYER_STATE_PAUSE;
799 800
		player->paused = true;

801
		player_unlock(pc);
802

803
		return false;
804
	}
805

806 807
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
808
	   larger block at a time */
809 810
	decoder_lock(dc);
	if (!decoder_is_idle(dc) &&
811
	    music_pipe_size(dc->pipe) <= (pc->buffered_before_play +
812
					 music_buffer_size(player_buffer) * 3) / 4)
813 814
		decoder_signal(dc);
	decoder_unlock(dc);
815 816 817 818

	return true;
}

819 820 821 822 823
/**
 * 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.
 *
824 825
 * The player lock is not held.
 *
826 827 828 829 830 831 832
 * @return true on success, false on error (playback will be stopped)
 */
static bool
player_song_border(struct player *player)
{
	player->xfade = XFADE_UNKNOWN;

833
	char *uri = song_get_uri(player->song);
834 835 836
	g_message("played \"%s\"", uri);
	g_free(uri);

837
	music_pipe_free(player->pipe);
838
	player->pipe = player->dc->pipe;
839

840 841
	audio_output_all_song_border();

842 843 844
	if (!player_wait_for_decoder(player))
		return false;

845 846 847 848 849 850 851 852 853 854
	struct player_control *const pc = player->pc;
	player_lock(pc);

	if (pc->border_pause) {
		player->paused = true;
		pc->state = PLAYER_STATE_PAUSE;
	}

	player_unlock(pc);

855
	return true;
856 857
}

858 859 860 861 862
/*
 * 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.
 */
863
static void do_play(struct player_control *pc, struct decoder_control *dc)
864
{
865
	struct player player = {
866
		.pc = pc,
867
		.dc = dc,
868
		.buffering = true,
869 870
		.decoder_starting = false,
		.paused = false,
871
		.queued = true,
872
		.output_open = false,
873
		.song = NULL,
874
		.xfade = XFADE_UNKNOWN,
875 876
		.cross_fading = false,
		.cross_fade_chunks = 0,
877
		.cross_fade_tag = NULL,
878
		.elapsed_time = 0.0,
879
	};
880

881
	player_unlock(pc);
882

883
	player.pipe = music_pipe_new();
884

885
	player_dc_start(&player, player.pipe);
886
	if (!player_wait_for_decoder(&player)) {
887
		player_dc_stop(&player);
888
		player_command_finished(pc);
889
		music_pipe_free(player.pipe);
890
		event_pipe_emit(PIPE_EVENT_PLAYLIST);
891
		player_lock(pc);
892
		return;
893
	}
894

895 896
	player_lock(pc);
	pc->state = PLAYER_STATE_PLAY;
897

Max Kellermann's avatar
Max Kellermann committed
898 899
	if (pc->command == PLAYER_COMMAND_SEEK)
		player.elapsed_time = pc->seek_where;
900

901
	player_command_finished_locked(pc);
902

903
	while (true) {
Max Kellermann's avatar
Max Kellermann committed
904
		player_process_command(&player);
905 906 907 908
		if (pc->command == PLAYER_COMMAND_STOP ||
		    pc->command == PLAYER_COMMAND_EXIT ||
		    pc->command == PLAYER_COMMAND_CLOSE_AUDIO) {
			player_unlock(pc);
909
			audio_output_all_cancel();
910 911 912
			break;
		}

913
		player_unlock(pc);
914

915
		if (player.buffering) {
916 917 918 919
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

920
			if (music_pipe_size(player.pipe) < pc->buffered_before_play &&
921
			    !decoder_lock_is_idle(dc)) {
922
				/* not enough decoded buffer space yet */
923 924

				if (!player.paused &&
925
				    player.output_open &&
926 927 928 929
				    audio_output_all_check() < 4 &&
				    !player_send_silence(&player))
					break;

930
				decoder_lock(dc);
931
				/* XXX race condition: check decoder again */
932
				player_wait_decoder(pc, dc);
933
				decoder_unlock(dc);
934
				player_lock(pc);
935 936 937
				continue;
			} else {
				/* buffering is complete */
938
				player.buffering = false;
939 940 941
			}
		}

942
		if (player.decoder_starting) {
943
			/* wait until the decoder is initialized completely */
944

945
			if (!player_check_decoder_startup(&player))
946
				break;
947

948
			player_lock(pc);
949
			continue;
950 951
		}

952
#ifndef NDEBUG
953
		/*
954 955
		music_pipe_check_format(&play_audio_format,
					player.next_song_chunk,
956
					&dc->out_audio_format);
957
		*/
958 959
#endif

960 961
		if (decoder_lock_is_idle(dc) && player.queued &&
		    dc->pipe == player.pipe) {
962 963
			/* the decoder has finished the current song;
			   make it decode the next song */
964

965
			assert(dc->pipe == NULL || dc->pipe == player.pipe);
966

967
			player_dc_start(&player, music_pipe_new());
968
		}
969

970 971 972 973
		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) &&
974
		    player.xfade == XFADE_UNKNOWN &&
975
		    !decoder_lock_is_starting(dc)) {
976 977 978
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
979
			player.cross_fade_chunks =
980 981 982
				cross_fade_calc(pc->cross_fade_seconds, dc->total_time,
						pc->mixramp_db,
						pc->mixramp_delay_seconds,
983 984
						dc->replay_gain_db,
						dc->replay_gain_prev_db,
985 986
						dc->mixramp_start,
						dc->mixramp_prev_end,
987
						&dc->out_audio_format,
988
						&player.play_audio_format,
989
						music_buffer_size(player_buffer) -
990
						pc->buffered_before_play);
991
			if (player.cross_fade_chunks > 0) {
992
				player.xfade = XFADE_ENABLED;
993
				player.cross_fading = false;
994 995 996
			} else
				/* cross fading is disabled or the
				   next song is too short */
997
				player.xfade = XFADE_DISABLED;
998 999
		}

1000
		if (player.paused) {
1001
			player_lock(pc);
1002

1003 1004
			if (pc->command == PLAYER_COMMAND_NONE)
				player_wait(pc);
1005
			continue;
1006
		} else if (!music_pipe_empty(player.pipe)) {
1007 1008
			/* at least one music chunk is ready - send it
			   to the audio output */
1009

1010
			play_next_chunk(&player);
1011 1012 1013 1014 1015 1016 1017
		} 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);
1018
		} else if (player_dc_at_next_song(&player)) {
1019 1020
			/* at the beginning of a new song */

1021
			if (!player_song_border(&player))
1022
				break;
1023
		} else if (decoder_lock_is_idle(dc)) {
1024 1025 1026
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1027
			if (music_pipe_empty(player.pipe)) {
1028 1029 1030
				/* wait for the hardware to finish
				   playback */
				audio_output_all_drain();
1031
				break;
1032
			}
1033
		} else if (player.output_open) {
1034 1035 1036
			/* the decoder is too busy and hasn't provided
			   new PCM data in time: send silence (if the
			   output pipe is empty) */
1037
			if (!player_send_silence(&player))
1038 1039
				break;
		}
1040

1041
		player_lock(pc);
1042 1043
	}

1044
	player_dc_stop(&player);
1045

1046
	music_pipe_clear(player.pipe, player_buffer);
1047
	music_pipe_free(player.pipe);
1048

1049 1050 1051
	if (player.cross_fade_tag != NULL)
		tag_free(player.cross_fade_tag);

1052
	player_lock(pc);
1053 1054

	if (player.queued) {
1055 1056
		assert(pc->next_song != NULL);
		pc->next_song = NULL;
1057 1058
	}

1059
	pc->state = PLAYER_STATE_STOP;
1060

1061
	player_unlock(pc);
1062

1063
	event_pipe_emit(PIPE_EVENT_PLAYLIST);
1064

1065
	player_lock(pc);
1066 1067
}

1068 1069
static gpointer
player_task(gpointer arg)
1070
{
1071
	struct player_control *pc = arg;
1072

1073
	struct decoder_control *dc = dc_new(pc->cond);
1074
	decoder_thread_start(dc);
1075

1076
	player_buffer = music_buffer_new(pc->buffer_chunks);
1077

1078
	player_lock(pc);
1079

1080
	while (1) {
1081
		switch (pc->command) {
1082
		case PLAYER_COMMAND_SEEK:
1083
		case PLAYER_COMMAND_QUEUE:
1084
			assert(pc->next_song != NULL);
1085

1086
			do_play(pc, dc);
1087 1088 1089
			break;

		case PLAYER_COMMAND_STOP:
1090
			player_unlock(pc);
1091
			audio_output_all_cancel();
1092
			player_lock(pc);
1093

1094 1095
			/* fall through */

1096
		case PLAYER_COMMAND_PAUSE:
1097 1098
			pc->next_song = NULL;
			player_command_finished_locked(pc);
1099 1100 1101
			break;

		case PLAYER_COMMAND_CLOSE_AUDIO:
1102
			player_unlock(pc);
1103

1104
			audio_output_all_release();
1105

1106 1107
			player_lock(pc);
			player_command_finished_locked(pc);
1108 1109 1110 1111 1112 1113

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

1117 1118
			break;

1119
		case PLAYER_COMMAND_UPDATE_AUDIO:
1120
			player_unlock(pc);
1121
			audio_output_all_enable_disable();
1122 1123
			player_lock(pc);
			player_command_finished_locked(pc);
1124 1125
			break;

Max Kellermann's avatar
Max Kellermann committed
1126
		case PLAYER_COMMAND_EXIT:
1127
			player_unlock(pc);
1128

1129 1130
			dc_quit(dc);
			dc_free(dc);
1131
			audio_output_all_close();
1132
			music_buffer_free(player_buffer);
1133

1134
			player_command_finished(pc);
1135
			return NULL;
Max Kellermann's avatar
Max Kellermann committed
1136

1137
		case PLAYER_COMMAND_CANCEL:
1138 1139
			pc->next_song = NULL;
			player_command_finished_locked(pc);
1140 1141
			break;

1142 1143
		case PLAYER_COMMAND_REFRESH:
			/* no-op when not playing */
1144
			player_command_finished_locked(pc);
1145 1146
			break;

1147
		case PLAYER_COMMAND_NONE:
1148
			player_wait(pc);
1149 1150 1151 1152 1153
			break;
		}
	}
}

1154 1155
void
player_create(struct player_control *pc)
1156
{
1157
	assert(pc->thread == NULL);
1158

1159
	GError *e = NULL;
1160 1161
	pc->thread = g_thread_create(player_task, pc, true, &e);
	if (pc->thread == NULL)
1162
		MPD_ERROR("Failed to spawn player task: %s", e->message);
1163
}