player_thread.c 24 KB
Newer Older
1
/*
2
 * Copyright (C) 2003-2010 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

38 39
#include <glib.h>

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

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

49
struct player {
50 51
	struct decoder_control *dc;

52 53
	struct music_pipe *pipe;

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

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

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

70 71 72 73 74
	/**
	 * is there a new song in pc.next_song?
	 */
	bool queued;

75 76 77 78 79
	/**
	 * the song currently being played
	 */
	struct song *song;

80 81 82 83
	/**
	 * is cross fading enabled?
	 */
	enum xfade_state xfade;
84

85 86 87 88 89 90 91 92 93 94
	/**
	 * has cross-fading begun?
	 */
	bool cross_fading;

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

95 96 97 98 99 100 101
	/**
	 * 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;

102 103 104 105
	/**
	 * The current audio format for the audio outputs.
	 */
	struct audio_format play_audio_format;
106 107 108 109 110 111 112 113 114

	/**
	 * 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
	 * precisly.
	 */
	float elapsed_time;
115 116
};

117 118
static struct music_buffer *player_buffer;

119
static void player_command_finished_locked(void)
120 121 122 123
{
	assert(pc.command != PLAYER_COMMAND_NONE);

	pc.command = PLAYER_COMMAND_NONE;
124 125 126 127 128 129 130 131
	g_cond_signal(main_cond);
}

static void player_command_finished(void)
{
	player_lock();
	player_command_finished_locked();
	player_unlock();
132 133
}

134 135 136 137 138 139
/**
 * Start the decoder.
 *
 * Player lock is not held.
 */
static void
140
player_dc_start(struct player *player, struct music_pipe *pipe)
141 142 143
{
	struct decoder_control *dc = player->dc;

144
	assert(player->queued || pc.command == PLAYER_COMMAND_SEEK);
145 146
	assert(pc.next_song != NULL);

147
	dc_start(dc, pc.next_song, player_buffer, pipe);
148 149
}

150 151
/**
 * Stop the decoder and clears (and frees) its music pipe.
152 153
 *
 * Player lock is not held.
154
 */
155 156 157
static void
player_dc_stop(struct player *player)
{
158 159 160
	struct decoder_control *dc = player->dc;

	dc_stop(dc);
161

162
	if (dc->pipe != NULL) {
163 164
		/* clear and free the decoder pipe */

165
		music_pipe_clear(dc->pipe, player_buffer);
166

167 168
		if (dc->pipe != player->pipe)
			music_pipe_free(dc->pipe);
169

170
		dc->pipe = NULL;
171 172 173
	}
}

174 175 176 177 178 179 180 181 182 183 184
/**
 * 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.
 */
static bool
decoding_next_song(const struct player *player)
{
	return player->dc->pipe != NULL && player->dc->pipe != player->pipe;
}

185 186 187 188
/**
 * 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.
189 190
 *
 * The player lock is not held.
191
 */
192 193
static bool
player_wait_for_decoder(struct player *player)
194
{
195 196
	struct decoder_control *dc = player->dc;

197
	assert(player->queued || pc.command == PLAYER_COMMAND_SEEK);
198 199 200 201
	assert(pc.next_song != NULL);

	player->queued = false;

202
	if (decoder_lock_has_failed(dc)) {
203
		player_lock();
204
		pc.errored_song = dc->song;
205
		pc.error = PLAYER_ERROR_FILE;
206
		pc.next_song = NULL;
207 208
		player_unlock();

209
		return false;
210 211
	}

212 213 214 215 216 217 218 219 220 221
	player->song = pc.next_song;
	player->elapsed_time = 0.0;

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

	player_lock();

	/* update player_control's song information */
222
	pc.total_time = song_get_duration(pc.next_song);
Max Kellermann's avatar
Max Kellermann committed
223
	pc.bit_rate = 0;
224
	audio_format_clear(&pc.audio_format);
225

226
	/* clear the queued song */
227
	pc.next_song = NULL;
228

229
	player_unlock();
230

231 232 233
	/* call syncPlaylistWithQueue() in the main thread */
	event_pipe_emit(PIPE_EVENT_PLAYLIST);

234
	return true;
235 236
}

237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
/**
 * 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;
}

257 258 259 260
/**
 * The decoder has acknowledged the "START" command (see
 * player_wait_for_decoder()).  This function checks if the decoder
 * initialization has completed yet.
261 262
 *
 * The player lock is not held.
263
 */
264 265 266
static bool
player_check_decoder_startup(struct player *player)
{
267 268
	struct decoder_control *dc = player->dc;

269 270
	assert(player->decoder_starting);

271
	decoder_lock(dc);
272

273
	if (decoder_has_failed(dc)) {
274
		/* the decoder failed */
275
		decoder_unlock(dc);
276

277
		player_lock();
278
		pc.errored_song = dc->song;
279
		pc.error = PLAYER_ERROR_FILE;
280
		player_unlock();
281 282

		return false;
283
	} else if (!decoder_is_starting(dc)) {
284
		/* the decoder is ready and ok */
285

286
		decoder_unlock(dc);
287

288
		if (audio_format_defined(&player->play_audio_format) &&
289
		    !audio_output_all_wait(1))
290 291 292 293
			/* the output devices havn't finished playing
			   all chunks yet - wait for that */
			return true;

294
		player_lock();
295
		pc.total_time = real_song_duration(dc->song, dc->total_time);
296
		pc.audio_format = dc->in_audio_format;
297 298
		player_unlock();

299
		player->play_audio_format = dc->out_audio_format;
300 301
		player->decoder_starting = false;

302
		if (!player->paused &&
303
		    !audio_output_all_open(&dc->out_audio_format,
304
					   player_buffer)) {
305
			char *uri = song_get_uri(dc->song);
306 307 308 309
			g_warning("problems opening audio device "
				  "while playing \"%s\"", uri);
			g_free(uri);

310
			player_lock();
311 312
			pc.error = PLAYER_ERROR_AUDIO;

313 314 315
			/* pause: the user may resume playback as soon
			   as an audio output becomes available */
			pc.state = PLAYER_STATE_PAUSE;
316 317
			player_unlock();

318 319 320
			player->paused = true;
			return true;
		}
321 322 323 324 325

		return true;
	} else {
		/* the decoder is not yet ready; wait
		   some more */
326 327
		player_wait_decoder(dc);
		decoder_unlock(dc);
328 329 330 331 332

		return true;
	}
}

333 334 335 336
/**
 * 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.
337 338
 *
 * The player lock is not held.
339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
 */
static bool
player_send_silence(struct player *player)
{
	struct music_chunk *chunk;
	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;

	assert(audio_format_defined(&player->play_audio_format));

	chunk = music_buffer_allocate(player_buffer);
	if (chunk == NULL) {
		g_warning("Failed to allocate silence buffer");
		return false;
	}

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

362
	chunk->times = -1.0; /* undefined time stamp */
363 364 365 366 367 368 369 370 371 372 373
	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;
}

374 375
/**
 * This is the handler for the #PLAYER_COMMAND_SEEK command.
376 377
 *
 * The player lock is not held.
378
 */
Max Kellermann's avatar
Max Kellermann committed
379
static bool player_seek_decoder(struct player *player)
380
{
381
	struct song *song = pc.next_song;
382
	struct decoder_control *dc = player->dc;
Max Kellermann's avatar
Max Kellermann committed
383
	double where;
384
	bool ret;
385

386 387
	assert(pc.next_song != NULL);

388
	if (decoder_current_song(dc) != song) {
389 390 391
		/* the decoder is already decoding the "next" song -
		   stop it and start the previous song again */

392 393
		player_dc_stop(player);

394 395
		/* clear music chunks which might still reside in the
		   pipe */
396
		music_pipe_clear(player->pipe, player_buffer);
397

398
		/* re-start the decoder */
399
		player_dc_start(player, player->pipe);
400
		ret = player_wait_for_decoder(player);
401
		if (!ret) {
402
			/* decoder failure */
403
			player_command_finished();
404
			return false;
405
		}
406 407 408
	} else {
		pc.next_song = NULL;
		player->queued = false;
409
	}
Max Kellermann's avatar
Max Kellermann committed
410

411 412 413 414 415 416 417 418 419 420 421
	/* wait for the decoder to complete initialization */

	while (player->decoder_starting) {
		ret = player_check_decoder_startup(player);
		if (!ret) {
			/* decoder failure */
			player_command_finished();
			return false;
		}
	}

422 423
	/* send the SEEK command */

Max Kellermann's avatar
Max Kellermann committed
424 425 426
	where = pc.seek_where;
	if (where > pc.total_time)
		where = pc.total_time - 0.1;
Max Kellermann's avatar
Max Kellermann committed
427 428 429
	if (where < 0.0)
		where = 0.0;

430
	ret = dc_seek(dc, where + song->start_ms / 1000.0);
431
	if (!ret) {
432
		/* decoder failure */
433 434 435
		player_command_finished();
		return false;
	}
436

437 438
	player->elapsed_time = where;

439 440
	player_command_finished();

441 442
	player->xfade = XFADE_UNKNOWN;

443 444
	/* re-fill the buffer after seeking */
	player->buffering = true;
445 446 447 448

	audio_output_all_cancel();

	return true;
449 450
}

451 452 453
/**
 * Player lock must be held before calling.
 */
Max Kellermann's avatar
Max Kellermann committed
454
static void player_process_command(struct player *player)
455
{
456
	G_GNUC_UNUSED struct decoder_control *dc = player->dc;
457

458 459 460
	switch (pc.command) {
	case PLAYER_COMMAND_NONE:
	case PLAYER_COMMAND_STOP:
Max Kellermann's avatar
Max Kellermann committed
461
	case PLAYER_COMMAND_EXIT:
462 463 464
	case PLAYER_COMMAND_CLOSE_AUDIO:
		break;

465
	case PLAYER_COMMAND_UPDATE_AUDIO:
466
		player_unlock();
467
		audio_output_all_enable_disable();
468 469
		player_lock();
		player_command_finished_locked();
470 471
		break;

472 473
	case PLAYER_COMMAND_QUEUE:
		assert(pc.next_song != NULL);
474
		assert(!player->queued);
475
		assert(dc->pipe == NULL || dc->pipe == player->pipe);
476

477
		player->queued = true;
478
		player_command_finished_locked();
479 480 481
		break;

	case PLAYER_COMMAND_PAUSE:
482 483
		player_unlock();

484 485
		player->paused = !player->paused;
		if (player->paused) {
486
			audio_output_all_pause();
487 488
			player_lock();

489
			pc.state = PLAYER_STATE_PAUSE;
490 491 492
		} 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 */
493
			player_lock();
494 495 496

			pc.state = PLAYER_STATE_PLAY;
		} else if (audio_output_all_open(&player->play_audio_format, player_buffer)) {
497
			/* unpaused, continue playing */
498 499
			player_lock();

500
			pc.state = PLAYER_STATE_PLAY;
501
		} else {
502 503
			/* the audio device has failed - rollback to
			   pause mode */
504 505 506
			pc.error = PLAYER_ERROR_AUDIO;

			player->paused = true;
507 508

			player_lock();
509
		}
510

511
		player_command_finished_locked();
512 513 514
		break;

	case PLAYER_COMMAND_SEEK:
515
		player_unlock();
516
		player_seek_decoder(player);
517
		player_lock();
518
		break;
519 520 521

	case PLAYER_COMMAND_CANCEL:
		if (pc.next_song == NULL) {
522
			/* the cancel request arrived too late, we're
523 524 525 526 527 528
			   already playing the queued song...  stop
			   everything now */
			pc.command = PLAYER_COMMAND_STOP;
			return;
		}

529
		if (decoding_next_song(player)) {
530 531
			/* the decoder is already decoding the song -
			   stop it and reset the position */
532
			player_unlock();
533
			player_dc_stop(player);
534 535
			player_lock();
		}
536 537 538

		pc.next_song = NULL;
		player->queued = false;
539
		player_command_finished_locked();
540
		break;
541 542

	case PLAYER_COMMAND_REFRESH:
543
		if (audio_format_defined(&player->play_audio_format) &&
544 545
		    !player->paused) {
			player_unlock();
546
			audio_output_all_check();
547 548
			player_lock();
		}
549 550

		pc.elapsed_time = audio_output_all_get_elapsed_time();
551 552 553
		if (pc.elapsed_time < 0.0)
			pc.elapsed_time = player->elapsed_time;

554
		player_command_finished_locked();
555
		break;
556 557 558
	}
}

559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583
static void
update_song_tag(struct song *song, const struct tag *new_tag)
{
	struct tag *old_tag;

	if (song_is_file(song))
		/* don't update tags of local files, only remote
		   streams may change tags dynamically */
		return;

	old_tag = song->tag;
	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);
}

584 585 586 587
/**
 * 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.
588 589
 *
 * Player lock is not held.
590
 */
591
static bool
Max Kellermann's avatar
Max Kellermann committed
592
play_chunk(struct song *song, struct music_chunk *chunk,
593
	   const struct audio_format *format)
594
{
595 596
	assert(music_chunk_check_format(chunk, format));

597 598
	if (chunk->tag != NULL)
		update_song_tag(song, chunk->tag);
599

600 601
	if (chunk->length == 0) {
		music_buffer_return(player_buffer, chunk);
602
		return true;
603
	}
604 605 606

	pc.bit_rate = chunk->bit_rate;

607 608
	/* send the chunk to the audio outputs */

609
	if (!audio_output_all_play(chunk))
610
		return false;
611

612 613
	pc.total_play_time += (double)chunk->length /
		audio_format_time_to_size(format);
614
	return true;
615 616
}

617 618 619 620 621 622 623 624 625
/**
 * 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)
{
626
	struct decoder_control *dc = player->dc;
627 628 629 630
	struct music_chunk *chunk = NULL;
	unsigned cross_fade_position;
	bool success;

631
	if (!audio_output_all_wait(64))
632 633
		/* the output pipe is still large enough, don't send
		   another chunk */
634 635
		return true;

636
	if (player->xfade == XFADE_ENABLED &&
637
	    decoding_next_song(player) &&
638 639 640 641
	    (cross_fade_position = music_pipe_size(player->pipe))
	    <= player->cross_fade_chunks) {
		/* perform cross fade */
		struct music_chunk *other_chunk =
642
			music_pipe_shift(dc->pipe);
643 644

		if (!player->cross_fading) {
645 646 647 648
			/* beginning of the cross fade - adjust
			   crossFadeChunks which might be bigger than
			   the remaining number of chunks in the old
			   song */
649 650 651 652 653 654 655
			player->cross_fade_chunks = cross_fade_position;
			player->cross_fading = true;
		}

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

658 659 660 661 662 663 664 665
			/* 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;

666
			if (isnan(pc.mixramp_delay_seconds)) {
667
				chunk->mix_ratio = ((float)cross_fade_position)
668 669
					     / player->cross_fade_chunks;
			} else {
670
				chunk->mix_ratio = nan("");
671 672
			}

673
			chunk->other = other_chunk;
674
		} else {
675
			/* there are not enough decoded chunks yet */
676

677
			decoder_lock(dc);
678

679
			if (decoder_is_idle(dc)) {
680
				/* the decoder isn't running, abort
681
				   cross fading */
682
				decoder_unlock(dc);
683

684 685
				player->xfade = XFADE_DISABLED;
			} else {
686
				/* wait for the decoder */
687 688 689
				decoder_signal(dc);
				player_wait_decoder(dc);
				decoder_unlock(dc);
690

691 692 693 694 695 696 697 698 699 700
				return true;
			}
		}
	}

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

	assert(chunk != NULL);

701 702 703 704 705 706 707 708
	/* 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;
	}

709 710
	/* play the current chunk */

711
	success = play_chunk(player->song, chunk, &player->play_audio_format);
712

713 714
	if (!success) {
		music_buffer_return(player_buffer, chunk);
715

716 717
		player_lock();

718 719
		pc.error = PLAYER_ERROR_AUDIO;

720 721 722 723 724
		/* pause: the user may resume playback as soon as an
		   audio output becomes available */
		pc.state = PLAYER_STATE_PAUSE;
		player->paused = true;

725 726
		player_unlock();

727
		return false;
728
	}
729

730 731
	/* this formula should prevent that the decoder gets woken up
	   with each chunk; it is more efficient to make it decode a
732
	   larger block at a time */
733 734 735
	decoder_lock(dc);
	if (!decoder_is_idle(dc) &&
	    music_pipe_size(dc->pipe) <= (pc.buffered_before_play +
736
					 music_buffer_size(player_buffer) * 3) / 4)
737 738
		decoder_signal(dc);
	decoder_unlock(dc);
739 740 741 742

	return true;
}

743 744 745 746 747
/**
 * 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.
 *
748 749
 * The player lock is not held.
 *
750 751 752 753 754
 * @return true on success, false on error (playback will be stopped)
 */
static bool
player_song_border(struct player *player)
{
755 756
	char *uri;

757 758
	player->xfade = XFADE_UNKNOWN;

759 760 761 762
	uri = song_get_uri(player->song);
	g_message("played \"%s\"", uri);
	g_free(uri);

763
	music_pipe_free(player->pipe);
764
	player->pipe = player->dc->pipe;
765

766 767
	audio_output_all_song_border();

768 769 770 771
	if (!player_wait_for_decoder(player))
		return false;

	return true;
772 773
}

774 775 776 777 778
/*
 * 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.
 */
779
static void do_play(struct decoder_control *dc)
780
{
781
	struct player player = {
782
		.dc = dc,
783
		.buffering = true,
784 785
		.decoder_starting = false,
		.paused = false,
786
		.queued = true,
787
		.song = NULL,
788
		.xfade = XFADE_UNKNOWN,
789 790
		.cross_fading = false,
		.cross_fade_chunks = 0,
791
		.cross_fade_tag = NULL,
792
		.elapsed_time = 0.0,
793
	};
794

795 796
	player_unlock();

797
	player.pipe = music_pipe_new();
798

799
	player_dc_start(&player, player.pipe);
800
	if (!player_wait_for_decoder(&player)) {
801
		player_dc_stop(&player);
802
		player_command_finished();
803
		music_pipe_free(player.pipe);
804
		event_pipe_emit(PIPE_EVENT_PLAYLIST);
805
		player_lock();
806
		return;
807
	}
808

809
	player_lock();
810
	pc.state = PLAYER_STATE_PLAY;
811
	player_command_finished_locked();
812

813
	while (true) {
Max Kellermann's avatar
Max Kellermann committed
814
		player_process_command(&player);
815
		if (pc.command == PLAYER_COMMAND_STOP ||
Max Kellermann's avatar
Max Kellermann committed
816
		    pc.command == PLAYER_COMMAND_EXIT ||
817
		    pc.command == PLAYER_COMMAND_CLOSE_AUDIO) {
818
			player_unlock();
819
			audio_output_all_cancel();
820 821 822
			break;
		}

823 824
		player_unlock();

825
		if (player.buffering) {
826 827 828 829
			/* buffering at the start of the song - wait
			   until the buffer is large enough, to
			   prevent stuttering on slow machines */

830
			if (music_pipe_size(player.pipe) < pc.buffered_before_play &&
831
			    !decoder_lock_is_idle(dc)) {
832
				/* not enough decoded buffer space yet */
833 834 835 836 837 838 839

				if (!player.paused &&
				    audio_format_defined(&player.play_audio_format) &&
				    audio_output_all_check() < 4 &&
				    !player_send_silence(&player))
					break;

840
				decoder_lock(dc);
841
				/* XXX race condition: check decoder again */
842 843
				player_wait_decoder(dc);
				decoder_unlock(dc);
844
				player_lock();
845 846 847
				continue;
			} else {
				/* buffering is complete */
848
				player.buffering = false;
849 850 851
			}
		}

852
		if (player.decoder_starting) {
853
			/* wait until the decoder is initialized completely */
854
			bool success;
855
			const struct song *song;
856

857 858 859
			success = player_check_decoder_startup(&player);
			if (!success)
				break;
860

861 862 863 864 865 866
			/* seek to the beginning of the range */
			song = decoder_current_song(dc);
			if (song != NULL && song->start_ms > 0 &&
			    !dc_seek(dc, song->start_ms / 1000.0))
				player_dc_stop(&player);

867
			player_lock();
868
			continue;
869 870
		}

871
#ifndef NDEBUG
872
		/*
873 874
		music_pipe_check_format(&play_audio_format,
					player.next_song_chunk,
875
					&dc->out_audio_format);
876
		*/
877 878
#endif

879 880
		if (decoder_lock_is_idle(dc) && player.queued &&
		    dc->pipe == player.pipe) {
881 882
			/* the decoder has finished the current song;
			   make it decode the next song */
883
			assert(dc->pipe == NULL || dc->pipe == player.pipe);
884

885
			player_dc_start(&player, music_pipe_new());
886
		}
887

888
		if (decoding_next_song(&player) &&
889
		    player.xfade == XFADE_UNKNOWN &&
890
		    !decoder_lock_is_starting(dc)) {
891 892 893
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
894
			player.cross_fade_chunks =
895
				cross_fade_calc(pc.cross_fade_seconds, dc->total_time,
896 897
						pc.mixramp_db,
						pc.mixramp_delay_seconds,
898 899
						dc->replay_gain_db,
						dc->replay_gain_prev_db,
900 901
						dc->mixramp_start,
						dc->mixramp_prev_end,
902
						&dc->out_audio_format,
903
						&player.play_audio_format,
904
						music_buffer_size(player_buffer) -
905
						pc.buffered_before_play);
906
			if (player.cross_fade_chunks > 0) {
907
				player.xfade = XFADE_ENABLED;
908
				player.cross_fading = false;
909 910 911
			} else
				/* cross fading is disabled or the
				   next song is too short */
912
				player.xfade = XFADE_DISABLED;
913 914
		}

915 916
		if (player.paused) {
			player_lock();
917 918 919

			if (pc.command == PLAYER_COMMAND_NONE)
				player_wait();
920 921
			continue;
		} else if (music_pipe_size(player.pipe) > 0) {
922 923
			/* at least one music chunk is ready - send it
			   to the audio output */
924

925
			play_next_chunk(&player);
926 927 928 929 930 931 932
		} 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);
933
		} else if (decoding_next_song(&player)) {
934 935
			/* at the beginning of a new song */

936
			if (!player_song_border(&player))
937
				break;
938
		} else if (decoder_lock_is_idle(dc)) {
939 940 941
			/* check the size of the pipe again, because
			   the decoder thread may have added something
			   since we last checked */
942 943 944 945
			if (music_pipe_size(player.pipe) == 0) {
				/* wait for the hardware to finish
				   playback */
				audio_output_all_drain();
946
				break;
947
			}
948
		} else {
949 950 951
			/* the decoder is too busy and hasn't provided
			   new PCM data in time: send silence (if the
			   output pipe is empty) */
952
			if (!player_send_silence(&player))
953 954
				break;
		}
955 956

		player_lock();
957 958
	}

959
	player_dc_stop(&player);
960

961
	music_pipe_clear(player.pipe, player_buffer);
962
	music_pipe_free(player.pipe);
963

964 965 966
	if (player.cross_fade_tag != NULL)
		tag_free(player.cross_fade_tag);

967
	player_lock();
968 969 970 971 972 973

	if (player.queued) {
		assert(pc.next_song != NULL);
		pc.next_song = NULL;
	}

974
	pc.state = PLAYER_STATE_STOP;
975

976 977
	player_unlock();

978
	event_pipe_emit(PIPE_EVENT_PLAYLIST);
979 980

	player_lock();
981 982
}

983
static gpointer player_task(G_GNUC_UNUSED gpointer arg)
984
{
985 986 987 988
	struct decoder_control dc;

	dc_init(&dc);
	decoder_thread_start(&dc);
989

990 991
	player_buffer = music_buffer_new(pc.buffer_chunks);

992 993
	player_lock();

994 995
	while (1) {
		switch (pc.command) {
996
		case PLAYER_COMMAND_QUEUE:
997 998
			assert(pc.next_song != NULL);

999
			do_play(&dc);
1000 1001 1002
			break;

		case PLAYER_COMMAND_STOP:
1003
			player_unlock();
1004
			audio_output_all_cancel();
1005 1006
			player_lock();

1007 1008
			/* fall through */

1009 1010
		case PLAYER_COMMAND_SEEK:
		case PLAYER_COMMAND_PAUSE:
1011
			pc.next_song = NULL;
1012
			player_command_finished_locked();
1013 1014 1015
			break;

		case PLAYER_COMMAND_CLOSE_AUDIO:
1016 1017
			player_unlock();

1018
			audio_output_all_release();
1019 1020 1021

			player_lock();
			player_command_finished_locked();
1022 1023 1024 1025 1026 1027 1028 1029 1030

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

1031 1032
			break;

1033
		case PLAYER_COMMAND_UPDATE_AUDIO:
1034
			player_unlock();
1035
			audio_output_all_enable_disable();
1036 1037
			player_lock();
			player_command_finished_locked();
1038 1039
			break;

Max Kellermann's avatar
Max Kellermann committed
1040
		case PLAYER_COMMAND_EXIT:
1041 1042
			player_unlock();

1043 1044
			dc_quit(&dc);
			dc_deinit(&dc);
1045
			audio_output_all_close();
1046
			music_buffer_free(player_buffer);
1047

Max Kellermann's avatar
Max Kellermann committed
1048
			player_command_finished();
1049
			return NULL;
Max Kellermann's avatar
Max Kellermann committed
1050

1051 1052
		case PLAYER_COMMAND_CANCEL:
			pc.next_song = NULL;
1053
			player_command_finished_locked();
1054 1055
			break;

1056 1057
		case PLAYER_COMMAND_REFRESH:
			/* no-op when not playing */
1058
			player_command_finished_locked();
1059 1060
			break;

1061
		case PLAYER_COMMAND_NONE:
1062
			player_wait();
1063 1064 1065 1066 1067 1068 1069
			break;
		}
	}
}

void player_create(void)
{
1070
	GError *e = NULL;
1071

1072 1073 1074 1075
	assert(pc.thread == NULL);

	pc.thread = g_thread_create(player_task, NULL, true, &e);
	if (pc.thread == NULL)
1076
		g_error("Failed to spawn player task: %s", e->message);
1077
}