player_thread.c 10.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
/* the Music Player Daemon (MPD)
 * Copyright (C) 2003-2007 by Warren Dukes (warren.dukes@gmail.com)
 * This project's homepage is: http://www.musicpd.org
 *
 * 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.
 * 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */

#include "player_thread.h"
20
#include "player_control.h"
21
#include "decoder_control.h"
22 23 24 25 26 27 28 29 30 31 32 33 34
#include "audio.h"
#include "pcm_utils.h"
#include "path.h"
#include "log.h"
#include "main_notify.h"
#include "crossfade.h"

enum xfade_state {
	XFADE_DISABLED = -1,
	XFADE_UNKNOWN = 0,
	XFADE_ENABLED = 1
};

35 36 37 38 39 40 41 42
static void player_command_finished(void)
{
	assert(pc.command != PLAYER_COMMAND_NONE);

	pc.command = PLAYER_COMMAND_NONE;
	wakeup_main_task();
}

43 44
static void quitDecode(void)
{
Max Kellermann's avatar
Max Kellermann committed
45
	dc_stop(&pc.notify);
46 47 48 49 50 51 52
	pc.state = PLAYER_STATE_STOP;
	pc.command = PLAYER_COMMAND_NONE;
	wakeup_main_task();
}

static int waitOnDecode(int *decodeWaitedOn)
{
Max Kellermann's avatar
Max Kellermann committed
53
	dc_command_wait(&pc.notify);
54 55

	if (dc.error != DECODE_ERROR_NOERROR) {
56
		assert(dc.next_song == NULL || dc.next_song->url != NULL);
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
		pc.errored_song = dc.next_song;
		pc.error = PLAYER_ERROR_FILE;
		return -1;
	}

	pc.totalTime = pc.fileTime;
	pc.bitRate = 0;
	pc.sampleRate = 0;
	pc.bits = 0;
	pc.channels = 0;
	*decodeWaitedOn = 1;

	return 0;
}

static int decodeSeek(int *decodeWaitedOn, int *next)
{
	int ret = -1;
Max Kellermann's avatar
Max Kellermann committed
75
	double where;
76

77
	if (decoder_current_song() != pc.next_song) {
Max Kellermann's avatar
Max Kellermann committed
78
		dc_stop(&pc.notify);
79 80
		*next = -1;
		ob_clear();
Max Kellermann's avatar
Max Kellermann committed
81
		dc_start_async(pc.next_song);
82 83
		waitOnDecode(decodeWaitedOn);
	}
Max Kellermann's avatar
Max Kellermann committed
84 85 86 87 88 89 90 91 92 93

	where = pc.seekWhere;
	if (where > pc.totalTime)
		where = pc.totalTime - 0.1;
	if (where < 0.0)
		where = 0.0;

	ret = dc_seek(&pc.notify, where);
	if (ret == 0)
		pc.elapsedTime = where;
94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

	player_command_finished();

	return ret;
}

static void processDecodeInput(int *pause_r, unsigned int *bbp_r,
			       enum xfade_state *do_xfade_r,
			       int *decodeWaitedOn_r,
			       int *next_r)
{
	switch (pc.command) {
	case PLAYER_COMMAND_NONE:
	case PLAYER_COMMAND_PLAY:
	case PLAYER_COMMAND_STOP:
Max Kellermann's avatar
Max Kellermann committed
109
	case PLAYER_COMMAND_EXIT:
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
	case PLAYER_COMMAND_CLOSE_AUDIO:
		break;

	case PLAYER_COMMAND_LOCK_QUEUE:
		pc.queueLockState = PLAYER_QUEUE_LOCKED;
		player_command_finished();
		break;

	case PLAYER_COMMAND_UNLOCK_QUEUE:
		pc.queueLockState = PLAYER_QUEUE_UNLOCKED;
		player_command_finished();
		break;

	case PLAYER_COMMAND_PAUSE:
		*pause_r = !*pause_r;
		if (*pause_r) {
			pc.state = PLAYER_STATE_PAUSE;
		} else {
			if (openAudioDevice(NULL) >= 0) {
				pc.state = PLAYER_STATE_PLAY;
			} else {
				char tmp[MPD_PATH_MAX];
132
				assert(dc.next_song == NULL || dc.next_song->url != NULL);
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176
				pc.errored_song = dc.next_song;
				pc.error = PLAYER_ERROR_AUDIO;
				ERROR("problems opening audio device "
				      "while playing \"%s\"\n",
				      get_song_url(tmp, dc.next_song));
				*pause_r = -1;
			}
		}
		player_command_finished();
		if (*pause_r == -1) {
			*pause_r = 1;
		} else if (*pause_r) {
			dropBufferedAudio();
			closeAudioDevice();
		}
		break;

	case PLAYER_COMMAND_SEEK:
		dropBufferedAudio();
		if (decodeSeek(decodeWaitedOn_r, next_r) == 0) {
			*do_xfade_r = XFADE_UNKNOWN;
			*bbp_r = 0;
		}
		break;
	}
}

static int playChunk(ob_chunk * chunk,
		     const AudioFormat * format, double sizeToTime)
{
	pc.elapsedTime = chunk->times;
	pc.bitRate = chunk->bitRate;

	pcm_volumeChange(chunk->data, chunk->chunkSize,
			 format, pc.softwareVolume);

	if (playAudio(chunk->data,
		      chunk->chunkSize) < 0)
		return -1;

	pc.totalPlayTime += sizeToTime * chunk->chunkSize;
	return 0;
}

177
static void do_play(void)
178 179 180
{
	int do_pause = 0;
	int buffering = 1;
181
	unsigned int bbp = pc.buffered_before_play;
182 183 184 185 186 187 188 189 190 191 192
	enum xfade_state do_xfade = XFADE_UNKNOWN;
	unsigned int crossFadeChunks = 0;
	/** the position of the next cross-faded chunk in the next
	    song */
	int nextChunk = 0;
	int decodeWaitedOn = 0;
	static const char silence[CHUNK_SIZE];
	double sizeToTime = 0.0;
	/** the position of the first chunk in the next song */
	int next = -1;

193
	ob_clear();
194 195
	ob_set_lazy(0);

196
	dc_start(&pc.notify, pc.next_song);
197 198
	if (waitOnDecode(&decodeWaitedOn) < 0) {
		quitDecode();
199
		return;
200
	}
201 202 203 204 205 206 207 208

	pc.elapsedTime = 0;
	pc.state = PLAYER_STATE_PLAY;
	player_command_finished();

	while (1) {
		processDecodeInput(&do_pause, &bbp, &do_xfade,
				   &decodeWaitedOn, &next);
209
		if (pc.command == PLAYER_COMMAND_STOP ||
Max Kellermann's avatar
Max Kellermann committed
210
		    pc.command == PLAYER_COMMAND_EXIT ||
211
		    pc.command == PLAYER_COMMAND_CLOSE_AUDIO) {
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
			dropBufferedAudio();
			break;
		}

		if (buffering) {
			if (ob_available() < bbp) {
				/* not enough decoded buffer space yet */
				notify_wait(&pc.notify);
				continue;
			} else {
				/* buffering is complete */
				buffering = 0;
				ob_set_lazy(1);
			}
		}

		if (decodeWaitedOn) {
229 230 231 232 233 234 235
			if (dc.error != DECODE_ERROR_NOERROR) {
				/* the decoder failed */
				assert(dc.next_song == NULL || dc.next_song->url != NULL);
				pc.errored_song = dc.next_song;
				pc.error = PLAYER_ERROR_FILE;
				break;
			}
236
			else if (!decoder_is_starting()) {
237 238 239 240
				/* the decoder is ready and ok */
				decodeWaitedOn = 0;
				if(openAudioDevice(&(ob.audioFormat))<0) {
					char tmp[MPD_PATH_MAX];
241
					assert(dc.next_song == NULL || dc.next_song->url != NULL);
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
					pc.errored_song = dc.next_song;
					pc.error = PLAYER_ERROR_AUDIO;
					ERROR("problems opening audio device "
					      "while playing \"%s\"\n",
					      get_song_url(tmp, dc.next_song));
					break;
				}

				if (do_pause) {
					dropBufferedAudio();
					closeAudioDevice();
				}
				pc.totalTime = dc.totalTime;
				pc.sampleRate = dc.audioFormat.sampleRate;
				pc.bits = dc.audioFormat.bits;
				pc.channels = dc.audioFormat.channels;
				sizeToTime = audioFormatSizeToTime(&ob.audioFormat);
			}
			else {
				/* the decoder is not yet ready; wait
				   some more */
				notify_wait(&pc.notify);
				continue;
			}
		}

268
		if (decoder_is_idle() &&
269 270 271 272 273
		    pc.queueState == PLAYER_QUEUE_FULL &&
		    pc.queueLockState == PLAYER_QUEUE_UNLOCKED) {
			/* the decoder has finished the current song;
			   make it decode the next song */
			next = ob.end;
Max Kellermann's avatar
Max Kellermann committed
274
			dc_start_async(pc.next_song);
275 276 277 278
			pc.queueState = PLAYER_QUEUE_DECODE;
			wakeup_main_task();
		}
		if (next >= 0 && do_xfade == XFADE_UNKNOWN &&
279
		    !decoder_is_starting()) {
280 281 282 283 284 285 286
			/* enable cross fading in this song?  if yes,
			   calculate how many chunks will be required
			   for it */
			crossFadeChunks =
				cross_fade_calc(pc.crossFade, dc.totalTime,
						&(ob.audioFormat),
						ob.size -
287
						pc.buffered_before_play);
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
			if (crossFadeChunks > 0) {
				do_xfade = XFADE_ENABLED;
				nextChunk = -1;
			} else
				/* cross fading is disabled or the
				   next song is too short */
				do_xfade = XFADE_DISABLED;
		}

		if (do_pause)
			notify_wait(&pc.notify);
		else if (!ob_is_empty() && (int)ob.begin != next) {
			ob_chunk *beginChunk = ob_get_chunk(ob.begin);
			unsigned int fadePosition;
			if (do_xfade == XFADE_ENABLED && next >= 0 &&
			    (fadePosition = ob_relative(next))
			    <= crossFadeChunks) {
				/* perform cross fade */
				if (nextChunk < 0) {
					/* beginning of the cross fade
					   - adjust crossFadeChunks
					   which might be bigger than
					   the remaining number of
					   chunks in the old song */
					crossFadeChunks = fadePosition;
				}
				nextChunk = ob_absolute(crossFadeChunks);
				if (nextChunk >= 0) {
					ob_set_lazy(1);
					cross_fade_apply(beginChunk,
							 ob_get_chunk(nextChunk),
							 &(ob.audioFormat),
							 fadePosition,
							 crossFadeChunks);
				} else {
					/* there are not enough
					   decoded chunks yet */
325
					if (decoder_is_idle()) {
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357
						/* the decoder isn't
						   running, abort
						   cross fading */
						do_xfade = XFADE_DISABLED;
					} else {
						/* wait for the
						   decoder */
						ob_set_lazy(0);
						notify_wait(&pc.notify);
						continue;
					}
				}
			}

			/* play the current chunk */
			if (playChunk(beginChunk, &(ob.audioFormat),
				      sizeToTime) < 0)
				break;
			ob_shift();
			notify_signal(&dc.notify);
		} else if (!ob_is_empty() && (int)ob.begin == next) {
			/* at the beginning of a new song */

			if (do_xfade == XFADE_ENABLED && nextChunk >= 0) {
				/* the cross-fade is finished; skip
				   the section which was cross-faded
				   (and thus already played) */
				ob_skip(crossFadeChunks);
			}

			do_xfade = XFADE_UNKNOWN;

358
			/* wait for a signal from the playlist */
359 360 361 362 363 364 365 366 367 368 369 370 371 372
			if (pc.queueState == PLAYER_QUEUE_DECODE ||
			    pc.queueLockState == PLAYER_QUEUE_LOCKED) {
				notify_wait(&pc.notify);
				continue;
			}
			if (pc.queueState != PLAYER_QUEUE_PLAY)
				break;

			next = -1;
			if (waitOnDecode(&decodeWaitedOn) < 0)
				return;

			pc.queueState = PLAYER_QUEUE_EMPTY;
			wakeup_main_task();
373
		} else if (decoder_is_idle()) {
374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391
			break;
		} else {
			/*DEBUG("waiting for decoded audio, play silence\n");*/
			if (playAudio(silence, CHUNK_SIZE) < 0)
				break;
		}
	}

	quitDecode();
}

static void * player_task(mpd_unused void *arg)
{
	notify_enter(&pc.notify);

	while (1) {
		switch (pc.command) {
		case PLAYER_COMMAND_PLAY:
392
			do_play();
393 394 395 396 397 398 399 400 401 402 403 404 405
			break;

		case PLAYER_COMMAND_STOP:
		case PLAYER_COMMAND_SEEK:
		case PLAYER_COMMAND_PAUSE:
			player_command_finished();
			break;

		case PLAYER_COMMAND_CLOSE_AUDIO:
			closeAudioDevice();
			player_command_finished();
			break;

Max Kellermann's avatar
Max Kellermann committed
406 407 408 409 410 411
		case PLAYER_COMMAND_EXIT:
			closeAudioDevice();
			player_command_finished();
			pthread_exit(NULL);
			break;

412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
		case PLAYER_COMMAND_LOCK_QUEUE:
			pc.queueLockState = PLAYER_QUEUE_LOCKED;
			player_command_finished();
			break;

		case PLAYER_COMMAND_UNLOCK_QUEUE:
			pc.queueLockState = PLAYER_QUEUE_UNLOCKED;
			player_command_finished();
			break;

		case PLAYER_COMMAND_NONE:
			notify_wait(&pc.notify);
			break;
		}
	}
	return NULL;
}

void player_create(void)
{
	pthread_attr_t attr;
	pthread_t player_thread;

	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
	if (pthread_create(&player_thread, &attr, player_task, NULL))
		FATAL("Failed to spawn player task: %s\n", strerror(errno));
}