player_thread.c 27.1 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"
Max Kellermann's avatar
Max Kellermann committed
35
#include "Main.hxx"
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

165
	dc_start(dc, song_dup_detached(pc->next_song),
Max Kellermann's avatar
Max Kellermann committed
166
		 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 239
	GError *error = dc_lock_get_error(dc);
	if (error != NULL) {
240
		player_lock(pc);
241
		pc_set_error(pc, PLAYER_ERROR_DECODER, error);
242 243

		song_free(pc->next_song);
244
		pc->next_song = NULL;
245

246
		player_unlock(pc);
247

248
		return false;
249 250
	}

251 252 253
	if (player->song != NULL)
		song_free(player->song);

254
	player->song = pc->next_song;
255 256 257 258 259 260
	player->elapsed_time = 0.0;

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

261
	player_lock(pc);
262 263

	/* update player_control's song information */
264 265 266
	pc->total_time = song_get_duration(pc->next_song);
	pc->bit_rate = 0;
	audio_format_clear(&pc->audio_format);
267

268
	/* clear the queued song */
269
	pc->next_song = NULL;
270

271
	player_unlock(pc);
272

273 274 275
	/* call syncPlaylistWithQueue() in the main thread */
	event_pipe_emit(PIPE_EVENT_PLAYLIST);

276
	return true;
277 278
}

279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
/**
 * 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;
}

299 300 301 302 303 304 305 306 307
/**
 * 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
308 309
	struct player_control *pc = player->pc;

310
	assert(audio_format_defined(&player->play_audio_format));
Max Kellermann's avatar
Max Kellermann committed
311 312
	assert(pc->state == PLAYER_STATE_PLAY ||
	       pc->state == PLAYER_STATE_PAUSE);
313

314 315 316
	GError *error = NULL;
	if (audio_output_all_open(&player->play_audio_format, player_buffer,
				  &error)) {
317
		player->output_open = true;
318 319
		player->paused = false;

Max Kellermann's avatar
Max Kellermann committed
320 321 322
		player_lock(pc);
		pc->state = PLAYER_STATE_PLAY;
		player_unlock(pc);
323 324 325

		return true;
	} else {
326 327
		g_warning("%s", error->message);

328 329
		player->output_open = false;

330 331 332 333
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		player->paused = true;

Max Kellermann's avatar
Max Kellermann committed
334
		player_lock(pc);
335
		pc_set_error(pc, PLAYER_ERROR_OUTPUT, error);
Max Kellermann's avatar
Max Kellermann committed
336 337
		pc->state = PLAYER_STATE_PAUSE;
		player_unlock(pc);
338 339 340 341 342

		return false;
	}
}

343 344 345 346
/**
 * The decoder has acknowledged the "START" command (see
 * player_wait_for_decoder()).  This function checks if the decoder
 * initialization has completed yet.
347 348
 *
 * The player lock is not held.
349
 */
350 351 352
static bool
player_check_decoder_startup(struct player *player)
{
353
	struct player_control *pc = player->pc;
354 355
	struct decoder_control *dc = player->dc;

356 357
	assert(player->decoder_starting);

358
	decoder_lock(dc);
359

360 361
	GError *error = dc_get_error(dc);
	if (error != NULL) {
362
		/* the decoder failed */
363
		decoder_unlock(dc);
364

365
		player_lock(pc);
366
		pc_set_error(pc, PLAYER_ERROR_DECODER, error);
367
		player_unlock(pc);
368 369

		return false;
370
	} else if (!decoder_is_starting(dc)) {
371
		/* the decoder is ready and ok */
372

373
		decoder_unlock(dc);
374

375
		if (player->output_open &&
376
		    !audio_output_all_wait(pc, 1))
377 378 379 380
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

381 382 383 384
		player_lock(pc);
		pc->total_time = real_song_duration(dc->song, dc->total_time);
		pc->audio_format = dc->in_audio_format;
		player_unlock(pc);
385

386
		player->play_audio_format = dc->out_audio_format;
387 388
		player->decoder_starting = false;

389
		if (!player->paused && !player_open_output(player)) {
390
			char *uri = song_get_uri(dc->song);
391 392 393 394
			g_warning("problems opening audio device "
				  "while playing \"%s\"", uri);
			g_free(uri);

395 396
			return true;
		}
397 398 399 400 401

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
402
		player_wait_decoder(pc, dc);
403
		decoder_unlock(dc);
404 405 406 407 408

		return true;
	}
}

409 410 411 412
/**
 * 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.
413 414
 *
 * The player lock is not held.
415 416 417 418
 */
static bool
player_send_silence(struct player *player)
{
419
	assert(player->output_open);
420 421
	assert(audio_format_defined(&player->play_audio_format));

422
	struct music_chunk *chunk = music_buffer_allocate(player_buffer);
423 424 425 426 427 428 429 430 431
	if (chunk == NULL) {
		g_warning("Failed to allocate silence buffer");
		return false;
	}

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

432 433 434 435 436 437
	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;

438
	chunk->times = -1.0; /* undefined time stamp */
439 440 441
	chunk->length = num_frames * frame_size;
	memset(chunk->data, 0, chunk->length);

442 443 444 445 446
	GError *error = NULL;
	if (!audio_output_all_play(chunk, &error)) {
		g_warning("%s", error->message);
		g_error_free(error);

447 448 449 450 451 452 453
		music_buffer_return(player_buffer, chunk);
		return false;
	}

	return true;
}

454 455
/**
 * This is the handler for the #PLAYER_COMMAND_SEEK command.
456 457
 *
 * The player lock is not held.
458
 */
Max Kellermann's avatar
Max Kellermann committed
459
static bool player_seek_decoder(struct player *player)
460
{
461 462
	struct player_control *pc = player->pc;
	struct song *song = pc->next_song;
463
	struct decoder_control *dc = player->dc;
464

465
	assert(pc->next_song != NULL);
466

467 468
	const unsigned start_ms = song->start_ms;

469
	if (!decoder_lock_is_current_song(dc, song)) {
470 471 472
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

473 474
		player_dc_stop(player);

475 476
		/* clear music chunks which might still reside in the
		   pipe */
477
		music_pipe_clear(player->pipe, player_buffer);
478

479
		/* re-start the decoder */
480
		player_dc_start(player, player->pipe);
481
		if (!player_wait_for_decoder(player)) {
482
			/* decoder failure */
483
			player_command_finished(pc);
484
			return false;
485
		}
486
	} else {
487 488 489 490 491
		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);
492
			player->pipe = dc->pipe;
493 494
		}

495
		song_free(pc->next_song);
496
		pc->next_song = NULL;
497
		player->queued = false;
498
	}
Max Kellermann's avatar
Max Kellermann committed
499

500 501 502
	/* wait for the decoder to complete initialization */

	while (player->decoder_starting) {
503
		if (!player_check_decoder_startup(player)) {
504
			/* decoder failure */
505
			player_command_finished(pc);
506 507 508 509
			return false;
		}
	}

510 511
	/* send the SEEK command */

512 513 514
	double where = pc->seek_where;
	if (where > pc->total_time)
		where = pc->total_time - 0.1;
Max Kellermann's avatar
Max Kellermann committed
515 516 517
	if (where < 0.0)
		where = 0.0;

518
	if (!dc_seek(dc, where + start_ms / 1000.0)) {
519
		/* decoder failure */
520
		player_command_finished(pc);
521 522
		return false;
	}
523

524 525
	player->elapsed_time = where;

526
	player_command_finished(pc);
527

528 529
	player->xfade = XFADE_UNKNOWN;

530 531
	/* re-fill the buffer after seeking */
	player->buffering = true;
532 533 534 535

	audio_output_all_cancel();

	return true;
536 537
}

538 539 540
/**
 * Player lock must be held before calling.
 */
Max Kellermann's avatar
Max Kellermann committed
541
static void player_process_command(struct player *player)
542
{
543
	struct player_control *pc = player->pc;
544
	G_GNUC_UNUSED struct decoder_control *dc = player->dc;
545

546
	switch (pc->command) {
547 548
	case PLAYER_COMMAND_NONE:
	case PLAYER_COMMAND_STOP:
Max Kellermann's avatar
Max Kellermann committed
549
	case PLAYER_COMMAND_EXIT:
550 551 552
	case PLAYER_COMMAND_CLOSE_AUDIO:
		break;

553
	case PLAYER_COMMAND_UPDATE_AUDIO:
554
		player_unlock(pc);
555
		audio_output_all_enable_disable();
556 557
		player_lock(pc);
		player_command_finished_locked(pc);
558 559
		break;

560
	case PLAYER_COMMAND_QUEUE:
561
		assert(pc->next_song != NULL);
562
		assert(!player->queued);
563
		assert(!player_dc_at_next_song(player));
564

565
		player->queued = true;
566
		player_command_finished_locked(pc);
567 568 569
		break;

	case PLAYER_COMMAND_PAUSE:
570
		player_unlock(pc);
571

572 573
		player->paused = !player->paused;
		if (player->paused) {
574
			audio_output_all_pause();
575
			player_lock(pc);
576

577
			pc->state = PLAYER_STATE_PAUSE;
578 579 580
		} 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 */
581
			player_lock(pc);
582

583
			pc->state = PLAYER_STATE_PLAY;
584
		} else {
585
			player_open_output(player);
586

587
			player_lock(pc);
588
		}
589

590
		player_command_finished_locked(pc);
591 592 593
		break;

	case PLAYER_COMMAND_SEEK:
594
		player_unlock(pc);
595
		player_seek_decoder(player);
596
		player_lock(pc);
597
		break;
598 599

	case PLAYER_COMMAND_CANCEL:
600
		if (pc->next_song == NULL) {
601
			/* the cancel request arrived too late, we're
602 603
			   already playing the queued song...  stop
			   everything now */
604
			pc->command = PLAYER_COMMAND_STOP;
605 606 607
			return;
		}

608
		if (player_dc_at_next_song(player)) {
609 610
			/* the decoder is already decoding the song -
			   stop it and reset the position */
611
			player_unlock(pc);
612
			player_dc_stop(player);
613
			player_lock(pc);
614
		}
615

616
		song_free(pc->next_song);
617
		pc->next_song = NULL;
618
		player->queued = false;
619
		player_command_finished_locked(pc);
620
		break;
621 622

	case PLAYER_COMMAND_REFRESH:
623
		if (player->output_open && !player->paused) {
624
			player_unlock(pc);
625
			audio_output_all_check();
626
			player_lock(pc);
627
		}
628

629 630 631
		pc->elapsed_time = audio_output_all_get_elapsed_time();
		if (pc->elapsed_time < 0.0)
			pc->elapsed_time = player->elapsed_time;
632

633
		player_command_finished_locked(pc);
634
		break;
635 636 637
	}
}

638 639 640 641 642 643 644 645
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;

646
	struct tag *old_tag = song->tag;
647 648 649 650 651 652 653 654 655 656 657 658 659 660
	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);
}

661 662 663 664
/**
 * 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.
665 666
 *
 * Player lock is not held.
667
 */
668
static bool
669 670
play_chunk(struct player_control *pc,
	   struct song *song, struct music_chunk *chunk,
671 672
	   const struct audio_format *format,
	   GError **error_r)
673
{
674 675
	assert(music_chunk_check_format(chunk, format));

676 677
	if (chunk->tag != NULL)
		update_song_tag(song, chunk->tag);
678

679 680
	if (chunk->length == 0) {
		music_buffer_return(player_buffer, chunk);
681
		return true;
682
	}
683

Max Kellermann's avatar
Max Kellermann committed
684
	player_lock(pc);
685
	pc->bit_rate = chunk->bit_rate;
Max Kellermann's avatar
Max Kellermann committed
686
	player_unlock(pc);
687

688 689
	/* send the chunk to the audio outputs */

690
	if (!audio_output_all_play(chunk, error_r))
691
		return false;
692

693
	pc->total_play_time += (double)chunk->length /
694
		audio_format_time_to_size(format);
695
	return true;
696 697
}

698 699 700 701 702 703 704 705 706
/**
 * 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)
{
707
	struct player_control *pc = player->pc;
708
	struct decoder_control *dc = player->dc;
709

710
	if (!audio_output_all_wait(pc, 64))
711 712
		/* the output pipe is still large enough, don't send
		   another chunk */
713 714
		return true;

715 716
	unsigned cross_fade_position;
	struct music_chunk *chunk = NULL;
717
	if (player->xfade == XFADE_ENABLED &&
718
	    player_dc_at_next_song(player) &&
719 720 721 722
	    (cross_fade_position = music_pipe_size(player->pipe))
	    <= player->cross_fade_chunks) {
		/* perform cross fade */
		struct music_chunk *other_chunk =
723
			music_pipe_shift(dc->pipe);
724 725

		if (!player->cross_fading) {
726 727 728 729
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
730 731 732 733 734 735 736
			player->cross_fade_chunks = cross_fade_position;
			player->cross_fading = true;
		}

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

739 740 741 742 743 744 745 746
			/* 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;

747
			if (isnan(pc->mixramp_delay_seconds)) {
748
				chunk->mix_ratio = ((float)cross_fade_position)
749 750
					     / player->cross_fade_chunks;
			} else {
751
				chunk->mix_ratio = nan("");
752
			}
753 754 755 756 757 758 759 760 761 762 763 764 765

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

767
			chunk->other = other_chunk;
768
		} else {
769
			/* there are not enough decoded chunks yet */
770

771
			decoder_lock(dc);
772

773
			if (decoder_is_idle(dc)) {
774
				/* the decoder isn't running, abort
775
				   cross fading */
776
				decoder_unlock(dc);
777

778 779
				player->xfade = XFADE_DISABLED;
			} else {
780
				/* wait for the decoder */
781
				decoder_signal(dc);
782
				player_wait_decoder(pc, dc);
783
				decoder_unlock(dc);
784

785 786 787 788 789 790 791 792 793 794
				return true;
			}
		}
	}

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

	assert(chunk != NULL);

795 796 797 798 799 800 801 802
	/* 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;
	}

803 804
	/* play the current chunk */

805
	GError *error = NULL;
806
	if (!play_chunk(player->pc, player->song, chunk,
807 808 809
			&player->play_audio_format, &error)) {
		g_warning("%s", error->message);

810
		music_buffer_return(player_buffer, chunk);
811

812
		player_lock(pc);
813

814
		pc_set_error(pc, PLAYER_ERROR_OUTPUT, error);
815

816 817
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
818
		pc->state = PLAYER_STATE_PAUSE;
819 820
		player->paused = true;

821
		player_unlock(pc);
822

823
		return false;
824
	}
825

826 827
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
828
	   larger block at a time */
829 830
	decoder_lock(dc);
	if (!decoder_is_idle(dc) &&
831
	    music_pipe_size(dc->pipe) <= (pc->buffered_before_play +
832
					 music_buffer_size(player_buffer) * 3) / 4)
833 834
		decoder_signal(dc);
	decoder_unlock(dc);
835 836 837 838

	return true;
}

839 840 841 842 843
/**
 * 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.
 *
844 845
 * The player lock is not held.
 *
846 847 848 849 850 851 852
 * @return true on success, false on error (playback will be stopped)
 */
static bool
player_song_border(struct player *player)
{
	player->xfade = XFADE_UNKNOWN;

853
	char *uri = song_get_uri(player->song);
854 855 856
	g_message("played \"%s\"", uri);
	g_free(uri);

857
	music_pipe_free(player->pipe);
858
	player->pipe = player->dc->pipe;
859

860 861
	audio_output_all_song_border();

862 863 864
	if (!player_wait_for_decoder(player))
		return false;

865 866 867 868 869 870 871 872 873 874
	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);

875
	return true;
876 877
}

878 879 880 881 882
/*
 * 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.
 */
883
static void do_play(struct player_control *pc, struct decoder_control *dc)
884
{
885
	struct player player = {
886
		.pc = pc,
887
		.dc = dc,
888
		.buffering = true,
889 890
		.decoder_starting = false,
		.paused = false,
891
		.queued = true,
892
		.output_open = false,
893
		.song = NULL,
894
		.xfade = XFADE_UNKNOWN,
895 896
		.cross_fading = false,
		.cross_fade_chunks = 0,
897
		.cross_fade_tag = NULL,
898
		.elapsed_time = 0.0,
899
	};
900

901
	player_unlock(pc);
902

903
	player.pipe = music_pipe_new();
904

905
	player_dc_start(&player, player.pipe);
906
	if (!player_wait_for_decoder(&player)) {
907 908
		assert(player.song == NULL);

909
		player_dc_stop(&player);
910
		player_command_finished(pc);
911
		music_pipe_free(player.pipe);
912
		event_pipe_emit(PIPE_EVENT_PLAYLIST);
913
		player_lock(pc);
914
		return;
915
	}
916

917 918
	player_lock(pc);
	pc->state = PLAYER_STATE_PLAY;
919

Max Kellermann's avatar
Max Kellermann committed
920 921
	if (pc->command == PLAYER_COMMAND_SEEK)
		player.elapsed_time = pc->seek_where;
922

923
	player_command_finished_locked(pc);
924

925
	while (true) {
Max Kellermann's avatar
Max Kellermann committed
926
		player_process_command(&player);
927 928 929 930
		if (pc->command == PLAYER_COMMAND_STOP ||
		    pc->command == PLAYER_COMMAND_EXIT ||
		    pc->command == PLAYER_COMMAND_CLOSE_AUDIO) {
			player_unlock(pc);
931
			audio_output_all_cancel();
932 933 934
			break;
		}

935
		player_unlock(pc);
936

937
		if (player.buffering) {
938 939 940 941
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

942
			if (music_pipe_size(player.pipe) < pc->buffered_before_play &&
943
			    !decoder_lock_is_idle(dc)) {
944
				/* not enough decoded buffer space yet */
945 946

				if (!player.paused &&
947
				    player.output_open &&
948 949 950 951
				    audio_output_all_check() < 4 &&
				    !player_send_silence(&player))
					break;

952
				decoder_lock(dc);
953
				/* XXX race condition: check decoder again */
954
				player_wait_decoder(pc, dc);
955
				decoder_unlock(dc);
956
				player_lock(pc);
957 958 959
				continue;
			} else {
				/* buffering is complete */
960
				player.buffering = false;
961 962 963
			}
		}

964
		if (player.decoder_starting) {
965
			/* wait until the decoder is initialized completely */
966

967
			if (!player_check_decoder_startup(&player))
968
				break;
969

970
			player_lock(pc);
971
			continue;
972 973
		}

974
#ifndef NDEBUG
975
		/*
976 977
		music_pipe_check_format(&play_audio_format,
					player.next_song_chunk,
978
					&dc->out_audio_format);
979
		*/
980 981
#endif

982 983
		if (decoder_lock_is_idle(dc) && player.queued &&
		    dc->pipe == player.pipe) {
984 985
			/* the decoder has finished the current song;
			   make it decode the next song */
986

987
			assert(dc->pipe == NULL || dc->pipe == player.pipe);
988

989
			player_dc_start(&player, music_pipe_new());
990
		}
991

992 993 994 995
		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) &&
996
		    player.xfade == XFADE_UNKNOWN &&
997
		    !decoder_lock_is_starting(dc)) {
998 999 1000
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
1001
			player.cross_fade_chunks =
1002 1003 1004
				cross_fade_calc(pc->cross_fade_seconds, dc->total_time,
						pc->mixramp_db,
						pc->mixramp_delay_seconds,
1005 1006
						dc->replay_gain_db,
						dc->replay_gain_prev_db,
1007 1008
						dc->mixramp_start,
						dc->mixramp_prev_end,
1009
						&dc->out_audio_format,
1010
						&player.play_audio_format,
1011
						music_buffer_size(player_buffer) -
1012
						pc->buffered_before_play);
1013
			if (player.cross_fade_chunks > 0) {
1014
				player.xfade = XFADE_ENABLED;
1015
				player.cross_fading = false;
1016 1017 1018
			} else
				/* cross fading is disabled or the
				   next song is too short */
1019
				player.xfade = XFADE_DISABLED;
1020 1021
		}

1022
		if (player.paused) {
1023
			player_lock(pc);
1024

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

1032
			play_next_chunk(&player);
1033 1034 1035 1036 1037 1038 1039
		} 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);
1040
		} else if (player_dc_at_next_song(&player)) {
1041 1042
			/* at the beginning of a new song */

1043
			if (!player_song_border(&player))
1044
				break;
1045
		} else if (decoder_lock_is_idle(dc)) {
1046 1047 1048
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
1049
			if (music_pipe_empty(player.pipe)) {
1050 1051 1052
				/* wait for the hardware to finish
				   playback */
				audio_output_all_drain();
1053
				break;
1054
			}
1055
		} else if (player.output_open) {
1056 1057 1058
			/* the decoder is too busy and hasn't provided
			   new PCM data in time: send silence (if the
			   output pipe is empty) */
1059
			if (!player_send_silence(&player))
1060 1061
				break;
		}
1062

1063
		player_lock(pc);
1064 1065
	}

1066
	player_dc_stop(&player);
1067

1068
	music_pipe_clear(player.pipe, player_buffer);
1069
	music_pipe_free(player.pipe);
1070

1071 1072 1073
	if (player.cross_fade_tag != NULL)
		tag_free(player.cross_fade_tag);

1074 1075 1076
	if (player.song != NULL)
		song_free(player.song);

1077
	player_lock(pc);
1078 1079

	if (player.queued) {
1080
		assert(pc->next_song != NULL);
1081
		song_free(pc->next_song);
1082
		pc->next_song = NULL;
1083 1084
	}

1085
	pc->state = PLAYER_STATE_STOP;
1086

1087
	player_unlock(pc);
1088

1089
	event_pipe_emit(PIPE_EVENT_PLAYLIST);
1090

1091
	player_lock(pc);
1092 1093
}

1094 1095
static gpointer
player_task(gpointer arg)
1096
{
1097
	struct player_control *pc = arg;
1098

1099
	struct decoder_control *dc = dc_new(pc->cond);
1100
	decoder_thread_start(dc);
1101

1102
	player_buffer = music_buffer_new(pc->buffer_chunks);
1103

1104
	player_lock(pc);
1105

1106
	while (1) {
1107
		switch (pc->command) {
1108
		case PLAYER_COMMAND_SEEK:
1109
		case PLAYER_COMMAND_QUEUE:
1110
			assert(pc->next_song != NULL);
1111

1112
			do_play(pc, dc);
1113 1114 1115
			break;

		case PLAYER_COMMAND_STOP:
1116
			player_unlock(pc);
1117
			audio_output_all_cancel();
1118
			player_lock(pc);
1119

1120 1121
			/* fall through */

1122
		case PLAYER_COMMAND_PAUSE:
1123 1124 1125 1126 1127
			if (pc->next_song != NULL) {
				song_free(pc->next_song);
				pc->next_song = NULL;
			}

1128
			player_command_finished_locked(pc);
1129 1130 1131
			break;

		case PLAYER_COMMAND_CLOSE_AUDIO:
1132
			player_unlock(pc);
1133

1134
			audio_output_all_release();
1135

1136 1137
			player_lock(pc);
			player_command_finished_locked(pc);
1138 1139 1140 1141 1142 1143

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

1147 1148
			break;

1149
		case PLAYER_COMMAND_UPDATE_AUDIO:
1150
			player_unlock(pc);
1151
			audio_output_all_enable_disable();
1152 1153
			player_lock(pc);
			player_command_finished_locked(pc);
1154 1155
			break;

Max Kellermann's avatar
Max Kellermann committed
1156
		case PLAYER_COMMAND_EXIT:
1157
			player_unlock(pc);
1158

1159 1160
			dc_quit(dc);
			dc_free(dc);
1161
			audio_output_all_close();
1162
			music_buffer_free(player_buffer);
1163

1164
			player_command_finished(pc);
1165
			return NULL;
Max Kellermann's avatar
Max Kellermann committed
1166

1167
		case PLAYER_COMMAND_CANCEL:
1168 1169 1170 1171 1172
			if (pc->next_song != NULL) {
				song_free(pc->next_song);
				pc->next_song = NULL;
			}

1173
			player_command_finished_locked(pc);
1174 1175
			break;

1176 1177
		case PLAYER_COMMAND_REFRESH:
			/* no-op when not playing */
1178
			player_command_finished_locked(pc);
1179 1180
			break;

1181
		case PLAYER_COMMAND_NONE:
1182
			player_wait(pc);
1183 1184 1185 1186 1187
			break;
		}
	}
}

1188 1189
void
player_create(struct player_control *pc)
1190
{
1191
	assert(pc->thread == NULL);
1192

1193
	GError *e = NULL;
1194 1195
	pc->thread = g_thread_create(player_task, pc, true, &e);
	if (pc->thread == NULL)
1196
		MPD_ERROR("Failed to spawn player task: %s", e->message);
1197
}