playlist.c 36.8 KB
Newer Older
Warren Dukes's avatar
Warren Dukes committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
/* the Music Player Daemon (MPD)
 * (c)2003-2004 by Warren Dukes (shank@mercury.chem.pitt.edu)
 * 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 "playlist.h"
#include "player.h"
#include "command.h"
#include "ls.h"
#include "tag.h"
#include "conf.h"
#include "directory.h"
#include "log.h"
#include "path.h"
#include "utils.h"
#include "sig_handlers.h"

#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <errno.h>
#include <unistd.h>
#include <time.h>

#define PLAYLIST_COMMENT	'#'

#define PLAYLIST_STATE_STOP		0
#define PLAYLIST_STATE_PLAY		1

#define PLAYLIST_PREV_UNLESS_ELAPSED    10

#define PLAYLIST_STATE_FILE_STATE		"state: "
#define PLAYLIST_STATE_FILE_RANDOM		"random: "
#define PLAYLIST_STATE_FILE_REPEAT		"repeat: "
#define PLAYLIST_STATE_FILE_CURRENT		"current: "
#define PLAYLIST_STATE_FILE_TIME		"time: "
#define PLAYLIST_STATE_FILE_CROSSFADE		"crossfade: "
#define PLAYLIST_STATE_FILE_PLAYLIST_BEGIN	"playlist_begin"
#define PLAYLIST_STATE_FILE_PLAYLIST_END	"playlist_end"

#define PLAYLIST_STATE_FILE_STATE_PLAY		"play"
#define PLAYLIST_STATE_FILE_STATE_PAUSE		"pause"
#define PLAYLIST_STATE_FILE_STATE_STOP		"stop"

#define PLAYLIST_BUFFER_SIZE	2*MAXPATHLEN

Warren Dukes's avatar
Warren Dukes committed
61 62
#define PLAYLIST_HASH_MULT	4

63 64 65
#define DEFAULT_PLAYLIST_MAX_LENGTH		(1024*16)
#define DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS	0

Warren Dukes's avatar
Warren Dukes committed
66 67
typedef struct _Playlist {
	Song ** songs;
68 69
	/* holds version a song was modified on */
	mpd_uint32 * songMod;
Warren Dukes's avatar
Warren Dukes committed
70
	int * order;
71 72
	int * positionToId;
	int * idToPosition;
Warren Dukes's avatar
Warren Dukes committed
73 74 75 76 77
	int length;
	int current;
	int queued;
	int repeat;
	int random;
78
	mpd_uint32 version;
Warren Dukes's avatar
Warren Dukes committed
79 80
} Playlist;

81 82
static Playlist playlist;
static int playlist_state = PLAYLIST_STATE_STOP;
83
static int playlist_max_length = DEFAULT_PLAYLIST_MAX_LENGTH;
84 85 86 87
static int playlist_stopOnError;
static int playlist_errorCount = 0;
static int playlist_queueError;
static int playlist_noGoToNext = 0;
Warren Dukes's avatar
Warren Dukes committed
88

89
static int playlist_saveAbsolutePaths = DEFAULT_PLAYLIST_SAVE_ABSOLUTE_PATHS;
Warren Dukes's avatar
Warren Dukes committed
90

91 92 93
static void swapOrder(int a, int b);
static int playPlaylistOrderNumber(FILE * fp, int orderNum);
static void randomizeOrder(int start, int end);
Warren Dukes's avatar
Warren Dukes committed
94

95
char * getStateFile() {
96 97 98 99 100 101 102
	ConfigParam * param = parseConfigFilePath(CONF_STATE_FILE, 0);
	
	if(!param) return NULL;

	return param->value;
}

103 104
static void incrPlaylistVersion() {
	static unsigned long max = ((mpd_uint32)1<<31)-1;
Warren Dukes's avatar
Warren Dukes committed
105
	playlist.version++;
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
	if(playlist.version>=max) {
		int i;

		for(i=0; i<playlist.length; i++) {
			playlist.songMod[i] = 0;
		}

		playlist.version = 1;
	}
}

void playlistVersionChange() {
	int i = 0;

	for(i=0; i<playlist.length; i++) {
		playlist.songMod[i] = playlist.version;
	}

	incrPlaylistVersion();
Warren Dukes's avatar
Warren Dukes committed
125 126
}

127 128 129 130 131 132 133 134 135 136
static void incrPlaylistCurrent() {
	if(playlist.current < 0) return;

	if(playlist.current >= playlist.length-1) {
		if(playlist.repeat) playlist.current = 0;
		else playlist.current = -1;
	}
	else playlist.current++;
}

Warren Dukes's avatar
Warren Dukes committed
137 138
void initPlaylist() {
	char * test;
Warren Dukes's avatar
Warren Dukes committed
139
	int i;
140
	ConfigParam * param;
Warren Dukes's avatar
Warren Dukes committed
141 142 143

	playlist.length = 0;
	playlist.repeat = 0;
144
	playlist.version = 1;
Warren Dukes's avatar
Warren Dukes committed
145 146
	playlist.random = 0;
	playlist.queued = -1;
147
        playlist.current = -1;
Warren Dukes's avatar
Warren Dukes committed
148

149
	param = getConfigParam(CONF_MAX_PLAYLIST_LENGTH);
Warren Dukes's avatar
Warren Dukes committed
150

151 152 153 154 155 156 157
	if(param) {
		playlist_max_length = strtol(param->value, &test, 10);
		if(*test!='\0') {
			ERROR("max playlist length \"%s\" is not an integer, "
					"line %i\n", param->value, param->line);
			exit(EXIT_FAILURE);
		}
Warren Dukes's avatar
Warren Dukes committed
158
	}
159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174

	param = getConfigParam(CONF_SAVE_ABSOLUTE_PATHS);

	if(param) {
		if(0 == strcmp("yes", param->value) ) {
			playlist_saveAbsolutePaths = 1;
		}
		else if(0 == strcmp("no", param->value) ) {
			playlist_saveAbsolutePaths = 0;
		}
		else {
			ERROR("%s \"%s\" is not yes or no, line %i"
				CONF_SAVE_ABSOLUTE_PATHS,
				param->value, param->line);
			exit(EXIT_FAILURE);
		}
Warren Dukes's avatar
Warren Dukes committed
175 176 177
	}

	playlist.songs = malloc(sizeof(Song *)*playlist_max_length);
178 179
	playlist.songMod = malloc(sizeof(mpd_uint32)*playlist_max_length);
	playlist.order = malloc(sizeof(int)*playlist_max_length);
180
	playlist.idToPosition = malloc(sizeof(int)*playlist_max_length*
Warren Dukes's avatar
Warren Dukes committed
181
					PLAYLIST_HASH_MULT);
182
	playlist.positionToId = malloc(sizeof(int)*playlist_max_length);
Warren Dukes's avatar
Warren Dukes committed
183

Warren Dukes's avatar
Warren Dukes committed
184
	memset(playlist.songs,0,sizeof(char *)*playlist_max_length);
Warren Dukes's avatar
Warren Dukes committed
185

186
	srandom(time(NULL));
Warren Dukes's avatar
Warren Dukes committed
187

Warren Dukes's avatar
Warren Dukes committed
188
	for(i=0; i<playlist_max_length*PLAYLIST_HASH_MULT; i++) {
189
		playlist.idToPosition[i] = -1;
Warren Dukes's avatar
Warren Dukes committed
190 191 192 193
	}
}

static int getNextId() {
194
	static int cur = -1;
Warren Dukes's avatar
Warren Dukes committed
195

196
	do {
Warren Dukes's avatar
Warren Dukes committed
197 198 199 200
		cur++;
		if(cur >= playlist_max_length*PLAYLIST_HASH_MULT) {
			cur = 0;
		}
201
	} while(playlist.idToPosition[cur] != -1);
Warren Dukes's avatar
Warren Dukes committed
202 203

	return cur;
Warren Dukes's avatar
Warren Dukes committed
204 205 206
}

void finishPlaylist() {
207 208 209
        int i;
        for(i=0;i<playlist.length;i++) {
		if(playlist.songs[i]->type == SONG_TYPE_URL) {
210
			freeJustSong(playlist.songs[i]);
211 212
		}
        }
213 214 215

	playlist.length = 0;

Warren Dukes's avatar
Warren Dukes committed
216
	free(playlist.songs);
217
	playlist.songs = NULL;
218 219
	free(playlist.songMod);
	playlist.songMod = NULL;
Warren Dukes's avatar
Warren Dukes committed
220
	free(playlist.order);
221
	playlist.order = NULL;
222 223 224 225
	free(playlist.idToPosition);
	playlist.idToPosition = NULL;
	free(playlist.positionToId);
	playlist.positionToId = NULL;
Warren Dukes's avatar
Warren Dukes committed
226 227 228 229 230 231 232
}

int clearPlaylist(FILE * fp) {
	int i;

	if(stopPlaylist(fp)<0) return -1;

233 234
	for(i=0;i<playlist.length;i++) {
		if(playlist.songs[i]->type == SONG_TYPE_URL) {
235
			freeJustSong(playlist.songs[i]);
236
		}
237
		playlist.idToPosition[playlist.positionToId[i]] = -1;
238 239
		playlist.songs[i] = NULL;
	}
Warren Dukes's avatar
Warren Dukes committed
240
	playlist.length = 0;
241
        playlist.current = -1;
Warren Dukes's avatar
Warren Dukes committed
242 243 244 245 246 247 248 249 250 251

	incrPlaylistVersion();

	return 0;
}

int showPlaylist(FILE * fp) {
	int i;

	for(i=0;i<playlist.length;i++) {
252
		myfprintf(fp,"%i:%s\n", i, getSongUrl(playlist.songs[i]));
Warren Dukes's avatar
Warren Dukes committed
253 254 255 256 257 258
	}

	return 0;
}

void savePlaylistState() {
259 260 261
	char * stateFile = getStateFile();
	
	if(stateFile) {
Warren Dukes's avatar
Warren Dukes committed
262 263
		FILE * fp;

264
		while(!(fp = fopen(stateFile,"w")) && errno==EINTR);
Warren Dukes's avatar
Warren Dukes committed
265 266
		if(!fp) {
			ERROR("problems opening state file \"%s\" for "
267
				"writing: %s\n", stateFile,
268
				strerror(errno));
Warren Dukes's avatar
Warren Dukes committed
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
			return;
		}

		myfprintf(fp,"%s",PLAYLIST_STATE_FILE_STATE);
		switch(playlist_state) {
		case PLAYLIST_STATE_PLAY:
			switch(getPlayerState()) {
			case PLAYER_STATE_PAUSE:
				myfprintf(fp,"%s\n",
					PLAYLIST_STATE_FILE_STATE_PAUSE);
				break;
			default:
				myfprintf(fp,"%s\n",
					PLAYLIST_STATE_FILE_STATE_PLAY);
			}
			myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_CURRENT,
				playlist.order[playlist.current]);
			myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_TIME,
				getPlayerElapsedTime());
			break;
		default:
			myfprintf(fp,"%s\n",PLAYLIST_STATE_FILE_STATE_STOP);
			break;
		}
		myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_RANDOM,
				playlist.random);
		myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_REPEAT,
				playlist.repeat);
		myfprintf(fp,"%s%i\n",PLAYLIST_STATE_FILE_CROSSFADE,
				(int)(getPlayerCrossFade()));
		myfprintf(fp,"%s\n",PLAYLIST_STATE_FILE_PLAYLIST_BEGIN);
		showPlaylist(fp);
		myfprintf(fp,"%s\n",PLAYLIST_STATE_FILE_PLAYLIST_END);

		while(fclose(fp) && errno==EINTR);
	}
}

void loadPlaylistFromStateFile(FILE * fp, char * buffer, int state, int current,
		int time) 
{
	char * temp;
	int song;
312
	char * stateFile = getStateFile();
Warren Dukes's avatar
Warren Dukes committed
313 314

	if(!myFgets(buffer,PLAYLIST_BUFFER_SIZE,fp)) {
315
		ERROR("error parsing state file \"%s\"\n", stateFile);
316
		exit(EXIT_FAILURE);
Warren Dukes's avatar
Warren Dukes committed
317 318 319 320
	}
	while(strcmp(buffer,PLAYLIST_STATE_FILE_PLAYLIST_END)) {
		song = atoi(strtok(buffer,":"));
		if(!(temp = strtok(NULL,""))) {
321
			ERROR("error parsing state file \"%s\"\n", stateFile);
322
			exit(EXIT_FAILURE);
Warren Dukes's avatar
Warren Dukes committed
323
		}
324
		if(addToPlaylist(stderr, temp, 0)==0 && current==song) {
Warren Dukes's avatar
Warren Dukes committed
325 326 327 328 329
			if(state!=PLAYER_STATE_STOP) {
				playPlaylist(stderr,playlist.length-1,0);
			}
			if(state==PLAYER_STATE_PAUSE) {
				playerPause(stderr);
330 331
			}
			if(state!=PLAYER_STATE_STOP) {
Warren Dukes's avatar
Warren Dukes committed
332 333 334 335 336
				seekSongInPlaylist(stderr,playlist.length-1,
						time);
			}
		}
		if(!myFgets(buffer,PLAYLIST_BUFFER_SIZE,fp)) {
337
			ERROR("error parsing state file \"%s\"\n", stateFile);
338
			exit(EXIT_FAILURE);
Warren Dukes's avatar
Warren Dukes committed
339 340 341 342 343
		}
	}
}

void readPlaylistState() {
344 345 346
	char * stateFile = getStateFile();
	
	if(stateFile) {
Warren Dukes's avatar
Warren Dukes committed
347 348 349 350 351 352 353
		FILE * fp;
		struct stat st;
		int current = -1;
		int time = 0;
		int state = PLAYER_STATE_STOP;
		char buffer[PLAYLIST_BUFFER_SIZE];

354 355 356 357
		if(stat(stateFile,&st)<0) {
			DEBUG("failed to stat state file\n");
			return;
		}
Warren Dukes's avatar
Warren Dukes committed
358 359
		if(!S_ISREG(st.st_mode)) {
			ERROR("state file \"%s\" is not a regular "
360
				"file\n",stateFile);
361
			exit(EXIT_FAILURE);
Warren Dukes's avatar
Warren Dukes committed
362 363
		}

364
		fp = fopen(stateFile,"r");
Warren Dukes's avatar
Warren Dukes committed
365 366
		if(!fp) {
			ERROR("problems opening state file \"%s\" for "
367
				"reading: %s\n", stateFile,
368
				strerror(errno));
369
			exit(EXIT_FAILURE);
Warren Dukes's avatar
Warren Dukes committed
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
		}

		while(myFgets(buffer,PLAYLIST_BUFFER_SIZE,fp)) {
			if(strncmp(buffer,PLAYLIST_STATE_FILE_STATE,
				strlen(PLAYLIST_STATE_FILE_STATE))==0) {
				if(strcmp(&(buffer
					[strlen(PLAYLIST_STATE_FILE_STATE)]),
					PLAYLIST_STATE_FILE_STATE_PLAY)==0) {
					state = PLAYER_STATE_PLAY;
				}
				else if(strcmp(&(buffer
					[strlen(PLAYLIST_STATE_FILE_STATE)]),
					PLAYLIST_STATE_FILE_STATE_PAUSE)==0) {
					state = PLAYER_STATE_PAUSE;
				}
			}
			else if(strncmp(buffer,PLAYLIST_STATE_FILE_TIME,
				strlen(PLAYLIST_STATE_FILE_TIME))==0) {
				time = atoi(&(buffer
					[strlen(PLAYLIST_STATE_FILE_TIME)]));
			}
			else if(strncmp(buffer,PLAYLIST_STATE_FILE_REPEAT,
				strlen(PLAYLIST_STATE_FILE_REPEAT))==0) {
				if(strcmp(&(buffer
					[strlen(PLAYLIST_STATE_FILE_REPEAT)]),
					"1")==0) {
					setPlaylistRepeatStatus(stderr,1);
				}
				else setPlaylistRepeatStatus(stderr,0);
			}
			else if(strncmp(buffer,PLAYLIST_STATE_FILE_CROSSFADE,
				strlen(PLAYLIST_STATE_FILE_CROSSFADE))==0) {
				setPlayerCrossFade(atoi(&(buffer[strlen(
                                       	PLAYLIST_STATE_FILE_CROSSFADE)])));
			}
			else if(strncmp(buffer,PLAYLIST_STATE_FILE_RANDOM,
				strlen(PLAYLIST_STATE_FILE_RANDOM))==0) {
				if(strcmp(&(buffer
					[strlen(PLAYLIST_STATE_FILE_RANDOM)]),
					"1")==0) {
					setPlaylistRandomStatus(stderr,1);
				}
				else setPlaylistRandomStatus(stderr,0);
			}
			else if(strncmp(buffer,PLAYLIST_STATE_FILE_CURRENT,
				strlen(PLAYLIST_STATE_FILE_CURRENT))==0) {
				if(strlen(buffer)==
					strlen(PLAYLIST_STATE_FILE_CURRENT)) {
					ERROR("error parsing state "
						"file \"%s\"\n",
420
						stateFile);
421
					exit(EXIT_FAILURE);
Warren Dukes's avatar
Warren Dukes committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439
				}
				current = atoi(&(buffer
					[strlen(PLAYLIST_STATE_FILE_CURRENT)]));
			}
			else if(strncmp(buffer,
				PLAYLIST_STATE_FILE_PLAYLIST_BEGIN,
				strlen(PLAYLIST_STATE_FILE_PLAYLIST_BEGIN)
				)==0) {
				if(state==PLAYER_STATE_STOP) current = -1;
				loadPlaylistFromStateFile(fp,buffer,state,
						current,time);
			}
		}

		fclose(fp);
	}
}

440
void printPlaylistSongInfo(FILE * fp, int song) {
441
	printSongInfo(fp, playlist.songs[song]);
442
	myfprintf(fp, "Pos: %i\n", song);
443
	myfprintf(fp, "Id: %i\n", playlist.positionToId[song]);
444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
}

int playlistChanges(FILE * fp, mpd_uint32 version) {
	int i;
	
	for(i=0; i<playlist.length; i++) {
		if(version > playlist.version ||
				playlist.songMod[i] >= version ||
				playlist.songMod[i] == 0)
		{
			printPlaylistSongInfo(fp, i);
		}
	}

	return 0;
}

461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
int playlistChangesPosId(FILE * fp, mpd_uint32 version) {
	int i;
	
	for(i=0; i<playlist.length; i++) {
		if(version > playlist.version ||
				playlist.songMod[i] >= version ||
				playlist.songMod[i] == 0)
		{
			myfprintf(fp, "cpos: %i\n", i);
			myfprintf(fp, "Id: %i\n", playlist.positionToId[i]);
		}
	}

	return 0;
}





481
int playlistInfo(FILE * fp, int song) {
Warren Dukes's avatar
Warren Dukes committed
482 483 484 485 486 487 488 489 490
	int i;
	int begin = 0;
	int end = playlist.length;

	if(song>=0) {
		begin = song;
		end = song+1;
	}
	if(song>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
491 492
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", song);
Warren Dukes's avatar
Warren Dukes committed
493 494 495
		return -1;
	}

496
	for(i=begin; i<end; i++) printPlaylistSongInfo(fp, i);
Warren Dukes's avatar
Warren Dukes committed
497 498 499 500

	return 0;
}

501 502
# define checkSongId(id) { \
	if(id < 0 || id >= PLAYLIST_HASH_MULT*playlist_max_length || \
503
			playlist.idToPosition[id] == -1 ) \
504 505 506 507 508 509 510 511 512 513 514 515 516 517
	{ \
		commandError(fp, ACK_ERROR_NO_EXIST, \
                                "song id doesn't exist: \"%i\"", id); \
		return -1; \
	} \
}

int playlistId(FILE * fp, int id) {
	int i;
	int begin = 0;
	int end = playlist.length;

	if(id>=0) {
		checkSongId(id);
518
		begin = playlist.idToPosition[id];
519 520 521 522 523 524 525 526
		end = begin+1;
	}

	for(i=begin; i<end; i++) printPlaylistSongInfo(fp, i);

	return 0;
}

Warren Dukes's avatar
Warren Dukes committed
527
void swapSongs(int song1, int song2) {
Warren Dukes's avatar
Warren Dukes committed
528 529
	Song * sTemp;
	int iTemp;
Warren Dukes's avatar
Warren Dukes committed
530
	
Warren Dukes's avatar
Warren Dukes committed
531
	sTemp = playlist.songs[song1];
Warren Dukes's avatar
Warren Dukes committed
532
	playlist.songs[song1] = playlist.songs[song2];
Warren Dukes's avatar
Warren Dukes committed
533 534
	playlist.songs[song2] = sTemp;

535 536
	playlist.songMod[song1] = playlist.version;
	playlist.songMod[song2] = playlist.version;
Warren Dukes's avatar
Warren Dukes committed
537

538 539
	playlist.idToPosition[playlist.positionToId[song1]] = song2;
	playlist.idToPosition[playlist.positionToId[song2]] = song1;
Warren Dukes's avatar
Warren Dukes committed
540

541 542 543
	iTemp = playlist.positionToId[song1];
	playlist.positionToId[song1] = playlist.positionToId[song2];
	playlist.positionToId[song2] = iTemp;
Warren Dukes's avatar
Warren Dukes committed
544 545 546 547 548 549 550
}

void queueNextSongInPlaylist() {
	if(playlist.current<playlist.length-1) {
		playlist.queued = playlist.current+1;
		DEBUG("playlist: queue song %i:\"%s\"\n",
				playlist.queued,
551 552
				getSongUrl(playlist.songs[playlist.order[
					playlist.queued]]));
Warren Dukes's avatar
Warren Dukes committed
553 554 555
		if(queueSong(playlist.songs[playlist.order[playlist.queued]]) <
                                0) 
                {
Warren Dukes's avatar
Warren Dukes committed
556 557 558 559 560 561
			playlist.queued = -1;
			playlist_queueError = 1;
		}
	}
	else if(playlist.length && playlist.repeat) {
		if(playlist.length>1 && playlist.random) {
562
			randomizeOrder(0,playlist.length-1);
Warren Dukes's avatar
Warren Dukes committed
563 564 565 566
		}
		playlist.queued = 0;
		DEBUG("playlist: queue song %i:\"%s\"\n",
				playlist.queued,
567 568
				getSongUrl(playlist.songs[playlist.order[
					playlist.queued]]));
Warren Dukes's avatar
Warren Dukes committed
569 570 571
		if(queueSong(playlist.songs[playlist.order[playlist.queued]]) <
				0) 
                {
Warren Dukes's avatar
Warren Dukes committed
572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622
			playlist.queued = -1;
			playlist_queueError = 1;
		}
	}
}

void syncPlaylistWithQueue(int queue) {
	if(queue && getPlayerQueueState()==PLAYER_QUEUE_BLANK) {
		queueNextSongInPlaylist();
	}
	else if(getPlayerQueueState()==PLAYER_QUEUE_DECODE) {
		if(playlist.queued!=-1) setQueueState(PLAYER_QUEUE_PLAY);
		else setQueueState(PLAYER_QUEUE_STOP);
	}
	else if(getPlayerQueueState()==PLAYER_QUEUE_EMPTY) {
		setQueueState(PLAYER_QUEUE_BLANK);
		if(playlist.queued>=0) {
			DEBUG("playlist: now playing queued song\n");
			playlist.current = playlist.queued;
		}
		playlist.queued = -1;
		if(queue) queueNextSongInPlaylist();
	}
}

void lockPlaylistInteraction() {
	if(getPlayerQueueState()==PLAYER_QUEUE_PLAY || 
		getPlayerQueueState()==PLAYER_QUEUE_FULL) {
		playerQueueLock();
		syncPlaylistWithQueue(0);
	}
}

void unlockPlaylistInteraction() {
	playerQueueUnlock();
}

void clearPlayerQueue() {
	playlist.queued = -1;
	switch(getPlayerQueueState()) {
	case PLAYER_QUEUE_FULL:
		DEBUG("playlist: dequeue song\n");
		setQueueState(PLAYER_QUEUE_BLANK);
		break;
	case PLAYER_QUEUE_PLAY:
		DEBUG("playlist: stop decoding queued song\n");
		setQueueState(PLAYER_QUEUE_STOP);
		break;
	}
}

623
int addToPlaylist(FILE * fp, char * url, int printId) {
Warren Dukes's avatar
Warren Dukes committed
624 625
	Song * song;

626
	DEBUG("add to playlist: %s\n",url);
Warren Dukes's avatar
Warren Dukes committed
627
	
628 629
	if((song = getSongFromDB(url))) {
	}
630
	else if(isValidRemoteUtf8Url(url) && 
631
                        (song = newSong(url, SONG_TYPE_URL, NULL))) 
632
        {
633 634
	}
	else {
Warren Dukes's avatar
Warren Dukes committed
635
		commandError(fp, ACK_ERROR_NO_EXIST,
Warren Dukes's avatar
Warren Dukes committed
636
                                "\"%s\" is not in the music db or is "
637
                                "not a valid url\n", url);
Warren Dukes's avatar
Warren Dukes committed
638 639 640
		return -1;
	}

641
	return addSongToPlaylist(fp,song, printId);
Warren Dukes's avatar
Warren Dukes committed
642 643
}

644 645 646
int addSongToPlaylist(FILE * fp, Song * song, int printId) {
	int id;

Warren Dukes's avatar
Warren Dukes committed
647
	if(playlist.length==playlist_max_length) {
Warren Dukes's avatar
Warren Dukes committed
648
		commandError(fp, ACK_ERROR_PLAYLIST_MAX,
649
                                "playlist is at the max size", NULL);
Warren Dukes's avatar
Warren Dukes committed
650 651 652 653 654 655 656 657 658 659 660
		return -1;
	}

	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=0 && playlist.current==playlist.length-1) {
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}

661 662
	id = getNextId();

Warren Dukes's avatar
Warren Dukes committed
663
	playlist.songs[playlist.length] = song;
664
	playlist.songMod[playlist.length] = playlist.version;
Warren Dukes's avatar
Warren Dukes committed
665
	playlist.order[playlist.length] = playlist.length;
666
	playlist.positionToId[playlist.length] = id;
667
	playlist.idToPosition[playlist.positionToId[playlist.length]] = playlist.length;
Warren Dukes's avatar
Warren Dukes committed
668 669 670 671 672
	playlist.length++;

	if(playlist.random) {
		int swap;
		int start;
673 674
		/*if(playlist_state==PLAYLIST_STATE_STOP) start = 0;
		else */if(playlist.queued>=0) start = playlist.queued+1;
Warren Dukes's avatar
Warren Dukes committed
675
		else start = playlist.current+1;
676
                if(start < playlist.length) {
677
		        swap = random()%(playlist.length-start);
678 679 680
		        swap+=start;
		        swapOrder(playlist.length-1,swap);
                }
Warren Dukes's avatar
Warren Dukes committed
681 682 683 684
	}
	
	incrPlaylistVersion();

685 686
	if(printId) myfprintf(fp, "Id: %i\n", id);

Warren Dukes's avatar
Warren Dukes committed
687 688 689 690 691 692 693 694
	return 0;
}

int swapSongsInPlaylist(FILE * fp, int song1, int song2) {
	int queuedSong = -1;
	int currentSong = -1;

	if(song1<0 || song1>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
695 696
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", song1);
Warren Dukes's avatar
Warren Dukes committed
697 698 699
		return -1;
	}
	if(song2<0 || song2>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
700 701
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", song2);
Warren Dukes's avatar
Warren Dukes committed
702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741
		return -1;
	}
	
	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=0) {
			queuedSong = playlist.order[playlist.queued];
		}
		currentSong = playlist.order[playlist.current];

		if(queuedSong==song1 || queuedSong==song2 || currentSong==song1 
				|| currentSong==song2)	
		{
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}

	swapSongs(song1,song2);
	if(playlist.random) {
		int i;
		int k;
		int j = -1;
		for(i=0;playlist.order[i]!=song1;i++) {
			if(playlist.order[i]==song2) j = i;
		}
		k = i;
		for(;j==-1;i++) if(playlist.order[i]==song2) j = i;
		swapOrder(k,j);
	}
	else {
		if(playlist.current==song1) playlist.current = song2;
		else if(playlist.current==song2) playlist.current = song1;
	}

	incrPlaylistVersion();

	return 0;
}

742 743 744 745
int swapSongsInPlaylistById(FILE * fp, int id1, int id2) {
	checkSongId(id1);
	checkSongId(id2);

746 747
	return swapSongsInPlaylist(fp, playlist.idToPosition[id1], 
					playlist.idToPosition[id2]);
748 749
}

Warren Dukes's avatar
Warren Dukes committed
750
#define moveSongFromTo(from, to) { \
751 752
	playlist.idToPosition[playlist.positionToId[from]] = to; \
	playlist.positionToId[to] = playlist.positionToId[from]; \
Warren Dukes's avatar
Warren Dukes committed
753 754 755 756
	playlist.songs[to] = playlist.songs[from]; \
	playlist.songMod[to] = playlist.version; \
}

Warren Dukes's avatar
Warren Dukes committed
757 758 759 760
int deleteFromPlaylist(FILE * fp, int song) {
	int i;
	int songOrder;

Warren Dukes's avatar
Warren Dukes committed
761
	if(song<0 || song>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
762 763
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", song);
Warren Dukes's avatar
Warren Dukes committed
764 765 766 767 768 769 770 771 772 773 774 775 776
		return -1;
	}

	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=0 && (playlist.order[playlist.queued]==song
			|| playlist.order[playlist.current]==song)) 
		{
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();	
		}
	}

777 778 779 780
	if(playlist.songs[song]->type == SONG_TYPE_URL) {
		freeJustSong(playlist.songs[song]);
	}

781
	playlist.idToPosition[playlist.positionToId[song]] = -1;
Warren Dukes's avatar
Warren Dukes committed
782

Warren Dukes's avatar
Warren Dukes committed
783 784
	/* delete song from songs array */
	for(i=song;i<playlist.length-1;i++) {
Warren Dukes's avatar
Warren Dukes committed
785
		moveSongFromTo(i+1, i);
Warren Dukes's avatar
Warren Dukes committed
786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
	}
	/* now find it in the order array */
	for(i=0;i<playlist.length-1;i++) {
		if(playlist.order[i]==song) break;
	}
	songOrder = i;
	/* delete the entry from the order array */
	for(;i<playlist.length-1;i++) playlist.order[i] = playlist.order[i+1];
	/* readjust values in the order array */
	for(i=0;i<playlist.length-1;i++) {
		if(playlist.order[i]>song) playlist.order[i]--;
	}
	/* now take care of other misc stuff */
	playlist.songs[playlist.length-1] = NULL;
	playlist.length--;

	incrPlaylistVersion();

	if(playlist_state!=PLAYLIST_STATE_STOP && playlist.current==songOrder) {
		/*if(playlist.current>=playlist.length) return playerStop(fp);
		else return playPlaylistOrderNumber(fp,playlist.current);*/
		playerStop(stderr);
		playlist_noGoToNext = 1;
	}
810

811
	if(playlist.current>songOrder) {
Warren Dukes's avatar
Warren Dukes committed
812 813
		playlist.current--;
	}
814 815 816
	else if(playlist.current>=playlist.length) {
		incrPlaylistCurrent();
	}
Warren Dukes's avatar
Warren Dukes committed
817

818
	if(playlist.queued>songOrder) {
Warren Dukes's avatar
Warren Dukes committed
819 820 821 822 823 824
		playlist.queued--;
	}

	return 0;
}

825 826 827
int deleteFromPlaylistById(FILE * fp, int id) {
	checkSongId(id);

828
	return deleteFromPlaylist(fp, playlist.idToPosition[id]);
829 830
}

Warren Dukes's avatar
Warren Dukes committed
831 832
void deleteASongFromPlaylist(Song * song) {
	int i;
833 834

	if(NULL==playlist.songs) return;
Warren Dukes's avatar
Warren Dukes committed
835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
	
	for(i=0;i<playlist.length;i++) {
		if(song==playlist.songs[i]) {
			deleteFromPlaylist(stderr,i);
		}
	}
}

int stopPlaylist(FILE * fp) {
	DEBUG("playlist: stop\n");
	if(playerStop(fp)<0) return -1;
	playerCloseAudio();
	playlist.queued = -1;
	playlist_state = PLAYLIST_STATE_STOP;
	playlist_noGoToNext = 0;
	if(playlist.random) randomizeOrder(0,playlist.length-1);
	return 0;
}

int playPlaylistOrderNumber(FILE * fp, int orderNum) {

	if(playerStop(fp)<0) return -1;

	playlist_state = PLAYLIST_STATE_PLAY;
	playlist_noGoToNext = 0;
	playlist.queued = -1;
	playlist_queueError = 0;

	DEBUG("playlist: play %i:\"%s\"\n",orderNum,
864
			getSongUrl(playlist.songs[playlist.order[orderNum]]));
Warren Dukes's avatar
Warren Dukes committed
865

Warren Dukes's avatar
Warren Dukes committed
866
	if(playerPlay(fp,(playlist.songs[playlist.order[orderNum]])) < 0) {
Warren Dukes's avatar
Warren Dukes committed
867 868 869
		stopPlaylist(fp);
		return -1;
	}
870 871 872
	else playlist.current++;

	playlist.current = orderNum;
Warren Dukes's avatar
Warren Dukes committed
873 874 875 876 877 878 879 880 881

	return 0;
}

int playPlaylist(FILE * fp, int song, int stopOnError) {
	int i = song;

	clearPlayerError();

882
	if(song==-1) {
Warren Dukes's avatar
Warren Dukes committed
883 884
		if(playlist.length == 0) return 0;

885 886 887
                if(playlist_state == PLAYLIST_STATE_PLAY) {
                        return playerSetPause(fp, 0);
                }
888 889 890 891 892 893 894 895
                if(playlist.current >= 0 && playlist.current < playlist.length)
                {
                        i = playlist.current;
                }
                else {
                        i = 0;
                }
        }
Warren Dukes's avatar
Warren Dukes committed
896
	else if(song<0 || song>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
897 898
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", song);
Warren Dukes's avatar
Warren Dukes committed
899 900 901 902
		return -1;
	}

	if(playlist.random) {
903
		if(song == -1 && playlist_state==PLAYLIST_STATE_PLAY) {
Warren Dukes's avatar
Warren Dukes committed
904 905
			randomizeOrder(0,playlist.length-1);
		}
906
		else {
Warren Dukes's avatar
Warren Dukes committed
907 908 909 910 911 912
			if(song>=0) for(i=0;song!=playlist.order[i];i++);
			if(playlist_state==PLAYLIST_STATE_STOP) {
				playlist.current = 0;
			}
			swapOrder(i,playlist.current);
			i = playlist.current;
913
		}
Warren Dukes's avatar
Warren Dukes committed
914 915 916 917 918 919 920 921
	}

	playlist_stopOnError = stopOnError;
	playlist_errorCount = 0;

	return playPlaylistOrderNumber(fp,i);
}

922 923 924 925 926 927 928
int playPlaylistById(FILE * fp, int id, int stopOnError) {
	if(id == -1) {
		return playPlaylist(fp, id, stopOnError);
	}

	checkSongId(id);

929
	return playPlaylist(fp, playlist.idToPosition[id], stopOnError);
930 931
}

932 933 934
void syncCurrentPlayerDecodeMetadata() {
        Song * songPlayer = playerCurrentDecodeSong();
        Song * song;
935
	int songNum;
936 937 938

        if(!songPlayer) return;

939
	if(playlist_state!=PLAYLIST_STATE_PLAY) return;
940

941 942
	songNum = playlist.order[playlist.current];
        song = playlist.songs[songNum];
943 944

        if(song->type == SONG_TYPE_URL &&
945
                        0 == strcmp(getSongUrl(song), songPlayer->url) &&
946 947 948 949
                        !mpdTagsAreEqual(song->tag, songPlayer->tag))
        {
                if(song->tag) freeMpdTag(song->tag);
                song->tag = mpdTagDup(songPlayer->tag);
950
		playlist.songMod[songNum] = playlist.version;
951
                incrPlaylistVersion();
952 953 954
        }
}

Warren Dukes's avatar
Warren Dukes committed
955 956 957 958 959
void syncPlayerAndPlaylist() {
	if(playlist_state!=PLAYLIST_STATE_PLAY) return;

	if(getPlayerState()==PLAYER_STATE_STOP) playPlaylistIfPlayerStopped();
	else syncPlaylistWithQueue(!playlist_queueError);
960 961

        syncCurrentPlayerDecodeMetadata();
Warren Dukes's avatar
Warren Dukes committed
962 963 964 965 966 967 968 969 970
}

int currentSongInPlaylist(FILE * fp) {
	if(playlist_state!=PLAYLIST_STATE_PLAY) return 0;

	playlist_stopOnError = 0;

	syncPlaylistWithQueue(0);

971
	if(playlist.current>= 0 && playlist.current<playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993
		return playPlaylistOrderNumber(fp,playlist.current);
	}
	else return stopPlaylist(fp);;

	return 0;
}

int nextSongInPlaylist(FILE * fp) {
	if(playlist_state!=PLAYLIST_STATE_PLAY) return 0;

	syncPlaylistWithQueue(0);
	
	playlist_stopOnError = 0;

	if(playlist.current<playlist.length-1) {
		return playPlaylistOrderNumber(fp,playlist.current+1);
	}
	else if(playlist.length && playlist.repeat) {
		if(playlist.random) randomizeOrder(0,playlist.length-1);
		return playPlaylistOrderNumber(fp,0);
	}
	else {
994
                incrPlaylistCurrent();
Warren Dukes's avatar
Warren Dukes committed
995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030
		return stopPlaylist(fp);;
	}

	return 0;
}

void playPlaylistIfPlayerStopped() {
	if(getPlayerState()==PLAYER_STATE_STOP) {
		int error = getPlayerError();

		if(error==PLAYER_ERROR_NOERROR) playlist_errorCount = 0;
		else playlist_errorCount++;

		if(playlist_state==PLAYLIST_STATE_PLAY && (
				(playlist_stopOnError && 
				error!=PLAYER_ERROR_NOERROR) ||
				error==PLAYER_ERROR_AUDIO ||
				error==PLAYER_ERROR_SYSTEM ||
				playlist_errorCount>=playlist.length)) {
			stopPlaylist(stderr);
		}
		else if(playlist_noGoToNext) currentSongInPlaylist(stderr);
		else nextSongInPlaylist(stderr);
	}
}

int getPlaylistRepeatStatus() {
	return playlist.repeat;
}

int getPlaylistRandomStatus() {
	return playlist.random;
}

int setPlaylistRepeatStatus(FILE * fp, int status) {
	if(status!=0 && status!=1) {
Warren Dukes's avatar
Warren Dukes committed
1031
		commandError(fp, ACK_ERROR_ARG, "\"%i\" is not 0 or 1", status);
Warren Dukes's avatar
Warren Dukes committed
1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
		return -1;
	}

	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.repeat && !status && playlist.queued==0) {
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}

	playlist.repeat = status;

	return 0;
}

int moveSongInPlaylist(FILE * fp, int from, int to) {
	int i;
	Song * tmpSong;
Warren Dukes's avatar
Warren Dukes committed
1051
	int tmpId;
Warren Dukes's avatar
Warren Dukes committed
1052 1053 1054 1055
	int queuedSong = -1;
	int currentSong = -1;

	if(from<0 || from>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
1056 1057
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", from);
Warren Dukes's avatar
Warren Dukes committed
1058 1059 1060 1061
		return -1;
	}

	if(to<0 || to>=playlist.length) {
Warren Dukes's avatar
Warren Dukes committed
1062 1063
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", to);
Warren Dukes's avatar
Warren Dukes committed
1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082
		return -1;
	}

	
	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=0) {
			queuedSong = playlist.order[playlist.queued];
		}
		currentSong = playlist.order[playlist.current];
		if(queuedSong==from || queuedSong==to || currentSong==from ||
				currentSong==to)
		{
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}

	tmpSong = playlist.songs[from];
1083
	tmpId = playlist.positionToId[from];
Warren Dukes's avatar
Warren Dukes committed
1084
	/* move songs to one less in from->to */
1085
	for(i=from;i<to;i++) {
Warren Dukes's avatar
Warren Dukes committed
1086
		moveSongFromTo(i+1, i);
1087
	}
Warren Dukes's avatar
Warren Dukes committed
1088
	/* move songs to one more in to->from */
1089
	for(i=from;i>to;i--) {
Warren Dukes's avatar
Warren Dukes committed
1090
		moveSongFromTo(i-1, i);
1091
	}
Warren Dukes's avatar
Warren Dukes committed
1092
	/* put song at _to_ */
1093 1094
	playlist.idToPosition[tmpId] = to;
	playlist.positionToId[to] = tmpId;
Warren Dukes's avatar
Warren Dukes committed
1095
	playlist.songs[to] = tmpSong;
1096
	playlist.songMod[to] = playlist.version;
Warren Dukes's avatar
Warren Dukes committed
1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124
	/* now deal with order */
	if(playlist.random) {
		for(i=0;i<playlist.length;i++) {
			if(playlist.order[i]>from && playlist.order[i]<=to) {
				playlist.order[i]--;
			}
			else if(playlist.order[i]<from && 
					playlist.order[i]>=to) {
				playlist.order[i]++;
			}
			else if(from==playlist.order[i]) {
				playlist.order[i] = to;
			}
		}
	}
	else if(playlist.current==from) playlist.current = to;
	else if(playlist.current>from && playlist.current<=to) {
		playlist.current--;
	}
	else if(playlist.current>=to && playlist.current<from) {
		playlist.current++;
	}

	incrPlaylistVersion();

	return 0;
}

1125
int moveSongInPlaylistById(FILE * fp, int id1, int to) {
1126 1127
	checkSongId(id1);

1128
	return moveSongInPlaylist(fp, playlist.idToPosition[id1], to);
1129 1130
}

Warren Dukes's avatar
Warren Dukes committed
1131 1132 1133
void orderPlaylist() {
	int i;

1134 1135 1136
	if(playlist.current >= 0 && playlist.current < playlist.length) {
		playlist.current = playlist.order[playlist.current];
	}
Warren Dukes's avatar
Warren Dukes committed
1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=0) {
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}

	for(i=0;i<playlist.length;i++) {
		playlist.order[i] = i;
	}

}

void swapOrder(int a, int b) {
	int bak = playlist.order[a];
	playlist.order[a] = playlist.order[b];
	playlist.order[b] = bak;
}

void randomizeOrder(int start,int end) {
	int i;
	int ri;

	DEBUG("playlist: randomize from %i to %i\n",start,end);

	if(playlist_state==PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=start && playlist.queued<=end) {
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}

	for(i=start;i<=end;i++) {
1173
		ri = random()%(end-start+1)+start;
Warren Dukes's avatar
Warren Dukes committed
1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184
		if(ri==playlist.current) playlist.current = i;
		else if(i==playlist.current) playlist.current = ri;
		swapOrder(i,ri);
	}

}

int setPlaylistRandomStatus(FILE * fp, int status) {
	int statusWas = playlist.random;

	if(status!=0 && status!=1) {
Warren Dukes's avatar
Warren Dukes committed
1185
		commandError(fp, ACK_ERROR_ARG, "\"%i\" is not 0 or 1", status);
Warren Dukes's avatar
Warren Dukes committed
1186 1187 1188 1189 1190 1191 1192
		return -1;
	}

	playlist.random = status;

	if(status!=statusWas) {
		if(playlist.random) {
1193
			/*if(playlist_state==PLAYLIST_STATE_PLAY) {
Warren Dukes's avatar
Warren Dukes committed
1194 1195 1196
				randomizeOrder(playlist.current+1,
						playlist.length-1);
			}
1197
			else */randomizeOrder(0,playlist.length-1);
1198 1199 1200 1201
			if(playlist.current >= 0 && 
					playlist.current < playlist.length)
			{
				swapOrder(playlist.current, 0);
1202
				playlist.current = 0;
1203
			}
Warren Dukes's avatar
Warren Dukes committed
1204 1205 1206 1207 1208 1209 1210 1211
		}
		else orderPlaylist();
	}

	return 0;
}

int previousSongInPlaylist(FILE * fp) {
1212 1213 1214 1215 1216
	static time_t lastTime = 0;
	time_t diff = time(NULL) - lastTime;

	lastTime += diff;

Warren Dukes's avatar
Warren Dukes committed
1217 1218 1219 1220
	if(playlist_state!=PLAYLIST_STATE_PLAY) return 0;

	syncPlaylistWithQueue(0);

1221
   	if (diff && getPlayerElapsedTime() > PLAYLIST_PREV_UNLESS_ELAPSED) {
Warren Dukes's avatar
Warren Dukes committed
1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257
		return playPlaylistOrderNumber(fp,playlist.current);
   	}
   	else {
      		if(playlist.current>0) {
			return playPlaylistOrderNumber(fp,playlist.current-1);
      		}
		else if(playlist.repeat) {
			return playPlaylistOrderNumber(fp,playlist.length-1);
		}
      		else {
         		return playPlaylistOrderNumber(fp,playlist.current);
      		}
	}

	return 0;
}

int shufflePlaylist(FILE * fp) {
	int i;
	int ri;

	if(playlist.length>1) {
		if(playlist_state==PLAYLIST_STATE_PLAY) {
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
			/* put current playing song first */
			swapSongs(0,playlist.order[playlist.current]);
			if(playlist.random) {
				int j;
				for(j=0;0!=playlist.order[j];j++);
				playlist.current = j;
			}
			else playlist.current = 0;
			i = 1;
		}
1258 1259 1260 1261
		else {
                        i = 0;
                        playlist.current = -1;
                }
Warren Dukes's avatar
Warren Dukes committed
1262 1263
		/* shuffle the rest of the list */
		for(;i<playlist.length;i++) {
1264
			ri = random()%(playlist.length-1)+1;
Warren Dukes's avatar
Warren Dukes committed
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
			swapSongs(i,ri);
		}

		incrPlaylistVersion();
	}

	return 0;
}

int deletePlaylist(FILE * fp, char * utf8file) {
	char * file = utf8ToFsCharset(utf8file);
	char * rfile = malloc(strlen(file)+strlen(".")+
			strlen(PLAYLIST_FILE_SUFFIX)+1);
	char * actualFile;

	strcpy(rfile,file);
	strcat(rfile,".");
	strcat(rfile,PLAYLIST_FILE_SUFFIX);

	if((actualFile = rpp2app(rfile)) && isPlaylist(actualFile)) free(rfile);
	else {
		free(rfile);
Warren Dukes's avatar
Warren Dukes committed
1287 1288
		commandError(fp, ACK_ERROR_NO_EXIST, 
                                "playlist \"%s\" not found", utf8file);
Warren Dukes's avatar
Warren Dukes committed
1289 1290 1291 1292
		return -1;
	}

	if(unlink(actualFile)<0) {
Warren Dukes's avatar
Warren Dukes committed
1293
		commandError(fp, ACK_ERROR_SYSTEM,
1294
                                "problems deleting file", NULL);
Warren Dukes's avatar
Warren Dukes committed
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
		return -1;
	}

	return 0;
}

int savePlaylist(FILE * fp, char * utf8file) {
	FILE * fileP;
	int i;
	struct stat st;
	char * file;
	char * rfile;
	char * actualFile;

	if(strstr(utf8file,"/")) {
Warren Dukes's avatar
Warren Dukes committed
1310 1311
		commandError(fp, ACK_ERROR_ARG,
                                "cannot save \"%s\", saving playlists to "
1312
				"subdirectories is not supported", utf8file);
Warren Dukes's avatar
Warren Dukes committed
1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331
		return -1;
	}

	file = strdup(utf8ToFsCharset(utf8file));

	rfile = malloc(strlen(file)+strlen(".")+
			strlen(PLAYLIST_FILE_SUFFIX)+1);

	strcpy(rfile,file);
	strcat(rfile,".");
	strcat(rfile,PLAYLIST_FILE_SUFFIX);

	free(file);

	actualFile = rpp2app(rfile);

	free(rfile);

	if(0==stat(actualFile,&st)) {
1332 1333
		commandError(fp, ACK_ERROR_EXIST, "a file or directory already " 
                                "exists with the name \"%s\"", utf8file);
Warren Dukes's avatar
Warren Dukes committed
1334 1335 1336 1337 1338
		return -1;
	}

	while(!(fileP = fopen(actualFile,"w")) && errno==EINTR);
	if(fileP==NULL) {
1339 1340
		commandError(fp, ACK_ERROR_SYSTEM, "problems opening file", 
				NULL);
Warren Dukes's avatar
Warren Dukes committed
1341 1342 1343 1344
		return -1;
	}

	for(i=0;i<playlist.length;i++) {
1345 1346 1347
		if(playlist_saveAbsolutePaths && 
				playlist.songs[i]->type==SONG_TYPE_FILE) 
		{
1348
			myfprintf(fileP,"%s\n",rmp2amp(utf8ToFsCharset((
1349
				        getSongUrl(playlist.songs[i])))));
Warren Dukes's avatar
Warren Dukes committed
1350 1351
		}
		else myfprintf(fileP,"%s\n",
1352
				utf8ToFsCharset(getSongUrl(playlist.songs[i])));
Warren Dukes's avatar
Warren Dukes committed
1353 1354 1355 1356 1357 1358 1359
	}

	while(fclose(fileP) && errno==EINTR);

	return 0;
}

1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417
int getPlaylistCurrentSong() {
	if(playlist.current >= 0 && playlist.current < playlist.length) {
                return playlist.order[playlist.current];
        }
        
        return -1;
}

unsigned long getPlaylistVersion() {
	return playlist.version;
}

int getPlaylistLength() {
	return playlist.length;
}

int seekSongInPlaylist(FILE * fp, int song, float time) {
	int i = song;

	if(song<0 || song>=playlist.length) {
		commandError(fp, ACK_ERROR_NO_EXIST,
                                "song doesn't exist: \"%i\"", song);
		return -1;
	}

	if(playlist.random) for(i=0;song!=playlist.order[i];i++);

	clearPlayerError();
	playlist_stopOnError = 1;
	playlist_errorCount = 0;

	if(playlist_state == PLAYLIST_STATE_PLAY) {
		if(playlist.queued>=0) {
			lockPlaylistInteraction();
			clearPlayerQueue();
			unlockPlaylistInteraction();
		}
	}
	else if(playPlaylistOrderNumber(fp,i)<0) return -1;

	if(playlist.current!=i) {
		if(playPlaylistOrderNumber(fp,i)<0) return -1;
	}

	return playerSeek(fp, playlist.songs[playlist.order[i]], time);
}

int seekSongInPlaylistById(FILE * fp, int id, float time) {
	checkSongId(id);

	return seekSongInPlaylist(fp, playlist.idToPosition[id], time);
}

int getPlaylistSongId(int song) {
	return playlist.positionToId[song];
}

static int PlaylistIterFunc(FILE * fp, char * utf8file, void (*IterFunc)(FILE *fp, char *utf8_file, char **errored_File)) {
Warren Dukes's avatar
Warren Dukes committed
1418
	FILE * fileP;
Warren Dukes's avatar
Warren Dukes committed
1419
	char s[MAXPATHLEN+1];
Warren Dukes's avatar
Warren Dukes committed
1420 1421 1422 1423 1424 1425 1426 1427
	int slength = 0;
	char * temp = strdup(utf8ToFsCharset(utf8file));
	char * rfile = malloc(strlen(temp)+strlen(".")+
			strlen(PLAYLIST_FILE_SUFFIX)+1);
	char * actualFile;
	char * parent = parentPath(temp);
	int parentlen = strlen(parent);
	char * erroredFile = NULL;
1428
	int tempInt;
Warren Dukes's avatar
Warren Dukes committed
1429
	int commentCharFound = 0;
Warren Dukes's avatar
Warren Dukes committed
1430 1431 1432 1433 1434 1435 1436 1437 1438 1439

	strcpy(rfile,temp);
	strcat(rfile,".");
	strcat(rfile,PLAYLIST_FILE_SUFFIX);

	free(temp);

	if((actualFile = rpp2app(rfile)) && isPlaylist(actualFile)) free(rfile);
	else {
		free(rfile);
Warren Dukes's avatar
Warren Dukes committed
1440
		commandError(fp, ACK_ERROR_NO_EXIST,
1441
				"playlist \"%s\" not found", utf8file);
Warren Dukes's avatar
Warren Dukes committed
1442 1443 1444 1445 1446
		return -1;
	}

	while(!(fileP = fopen(actualFile,"r")) && errno==EINTR);
	if(fileP==NULL) {
Warren Dukes's avatar
Warren Dukes committed
1447
		commandError(fp, ACK_ERROR_SYSTEM,
1448
				"problems opening file \"%s\"", utf8file);
Warren Dukes's avatar
Warren Dukes committed
1449 1450 1451
		return -1;
	}

1452 1453
	while((tempInt = fgetc(fileP))!=EOF) {
		s[slength] = tempInt;
Warren Dukes's avatar
Warren Dukes committed
1454
		if(s[slength]=='\n' || s[slength]=='\0') {
Warren Dukes's avatar
Warren Dukes committed
1455
			commentCharFound = 0;
Warren Dukes's avatar
Warren Dukes committed
1456
			s[slength] = '\0';
Warren Dukes's avatar
Warren Dukes committed
1457 1458 1459
			if(s[0]==PLAYLIST_COMMENT) {
				commentCharFound = 1;
			}
Warren Dukes's avatar
Warren Dukes committed
1460 1461 1462 1463 1464 1465 1466 1467 1468 1469
			if(strncmp(s,musicDir,strlen(musicDir))==0) {
				strcpy(s,&(s[strlen(musicDir)]));
			}
			else if(parentlen) {
				temp = strdup(s);
				memset(s,0,MAXPATHLEN+1);
				strcpy(s,parent);
				strncat(s,"/",MAXPATHLEN-parentlen);
				strncat(s,temp,MAXPATHLEN-parentlen-1);
				if(strlen(s)>=MAXPATHLEN) {
Warren Dukes's avatar
Warren Dukes committed
1470
					commandError(fp, 
1471 1472 1473
							ACK_ERROR_PLAYLIST_LOAD,
							"\"%s\" too long",
							temp);
Warren Dukes's avatar
Warren Dukes committed
1474 1475 1476 1477 1478 1479 1480 1481
					free(temp);
					while(fclose(fileP) && errno==EINTR);
					if(erroredFile) free(erroredFile);
					return -1;
				}
				free(temp);
			}
			slength = 0;
1482 1483
			temp = fsCharsetToUtf8(s);
			if(!temp) continue;
1484
			if(!commentCharFound)
1485
			{
1486 1487 1488 1489 1490
				/* using temp directly should be safe,
				 * for our current IterFunction set
				 * but just in case, we copy to s */
				strcpy(s, temp);
				IterFunc(fp, s, &erroredFile);
Warren Dukes's avatar
Warren Dukes committed
1491 1492 1493 1494
			}
		}
		else if(slength==MAXPATHLEN) {
			s[slength] = '\0';
Warren Dukes's avatar
Warren Dukes committed
1495
			commandError(fp, ACK_ERROR_PLAYLIST_LOAD,
1496
					"line in \"%s\" is too long", utf8file);
1497
			ERROR("line \"%s\" in playlist \"%s\" is too long\n",
1498
					s, utf8file);
Warren Dukes's avatar
Warren Dukes committed
1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
			while(fclose(fileP) && errno==EINTR);
			if(erroredFile) free(erroredFile);
			return -1;
		}
		else if(s[slength]!='\r') slength++;
	}

	while(fclose(fileP) && errno==EINTR);

	if(erroredFile) {
Warren Dukes's avatar
Warren Dukes committed
1509
		commandError(fp, ACK_ERROR_PLAYLIST_LOAD,
1510
				"can't add file \"%s\"", erroredFile);
Warren Dukes's avatar
Warren Dukes committed
1511 1512 1513 1514 1515 1516 1517 1518
		free(erroredFile);
		return -1;
	}

	return 0;
}


1519 1520 1521 1522 1523 1524
static void PlaylistInfoPrintInfo(FILE *fp, char *utf8file, char **erroredfile) {
	Song * song = getSongFromDB(utf8file);
	if(song) {
		printSongInfo(fp, song);       	
	}
	else {
1525
		myfprintf(fp,"file: %s\n",utf8file);
1526
	}                                  	
Warren Dukes's avatar
Warren Dukes committed
1527
}
1528
static void PlaylistInfoPrint(FILE *fp, char *utf8file, char **erroredfile) {
1529
	myfprintf(fp,"file: %s\n",utf8file);
Warren Dukes's avatar
Warren Dukes committed
1530 1531
}

1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
static void PlaylistLoadIterFunc(FILE *fp, char *temp, char **erroredFile) {
	if(!getSongFromDB(temp)	&& !isRemoteUrl(temp)) 
	{
		
	}
	else if((addToPlaylist(stderr, temp, 0))<0) {
		/* for windows compatibilit, convert slashes */
		char * temp2 = strdup(temp);
		char * p = temp2;
		while(*p) {
			if(*p=='\\') *p = '/';
			p++;
Warren Dukes's avatar
Warren Dukes committed
1544
		}
1545 1546 1547 1548 1549 1550
		if((addToPlaylist(stderr, temp2, 0))<0) {
			if(!*erroredFile) {
				*erroredFile = strdup(temp);
			}
		}
		free(temp2);
Warren Dukes's avatar
Warren Dukes committed
1551 1552
	}
}
1553

1554 1555 1556 1557 1558
int PlaylistInfo(FILE * fp, char * utf8file, int detail) {
	if(detail) {
		return PlaylistIterFunc(fp, utf8file, PlaylistInfoPrintInfo);
	}
	return PlaylistIterFunc(fp, utf8file, PlaylistInfoPrint) ;
1559
}
1560

1561 1562
int loadPlaylist(FILE * fp, char * utf8file) {
	return PlaylistIterFunc(fp, utf8file, PlaylistLoadIterFunc);
1563
}