ezstream.c 19.9 KB
Newer Older
1
2
3
/*
 *  ezstream - source client for Icecast with external en-/decoder support
 *  Copyright (C) 2003, 2004, 2005, 2006  Ed Zaleski <oddsock@oddsock.org>
4
 *  Copyright (C) 2007, 2009, 2015        Moritz Grimm <mgrimm@mrsserver.net>
5
6
 *
 *  This program is free software; you can redistribute it and/or modify
moritz's avatar
moritz committed
7
8
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
9
10
11
12
13
14
15
16
17
18
 *
 *  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.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
oddsock's avatar
oddsock committed
19

20
21
#include "compat.h"

22
23
#include "ezstream.h"

24
#include <signal.h>
25

26
#include "cfg.h"
27
#include "cmdline.h"
28
#include "log.h"
29
#include "metadata.h"
30
#include "playlist.h"
31
#include "stream.h"
32
#include "util.h"
33
#include "xalloc.h"
34

35
36
37
38
#define STREAM_DONE	0
#define STREAM_CONT	1
#define STREAM_SKIP	2
#define STREAM_SERVERR	3
39
#define STREAM_UPDMDATA 4
40

41
42
43
playlist_t		 playlist;
int			 playlistMode;
unsigned int		 resource_errors;
44

45
46
47
const int		 ezstream_signals[] = {
	SIGTERM, SIGINT, SIGHUP, SIGUSR1, SIGUSR2
};
48

49
50
51
52
53
volatile sig_atomic_t	 rereadPlaylist;
volatile sig_atomic_t	 rereadPlaylist_notify;
volatile sig_atomic_t	 skipTrack;
volatile sig_atomic_t	 queryMetadata;
volatile sig_atomic_t	 quit;
oddsock's avatar
oddsock committed
54
55

typedef struct tag_ID3Tag {
56
57
58
59
60
61
62
	char	tag[3];
	char	trackName[30];
	char	artistName[30];
	char	albumName[30];
	char	year[3];
	char	comment[30];
	char	genre;
oddsock's avatar
oddsock committed
63
64
} ID3Tag;

65
void		sig_handler(int);
66
67
68
char *		buildReencodeCommand(const char *, const char *, metadata_t);
metadata_t	getMetadata(const char *);
FILE *		openResource(stream_t, const char *, int *, metadata_t *,
69
			     int *, long *);
70
int		reconnect(stream_t);
71
const char *	getTimeString(long);
72
int		sendStream(stream_t, FILE *, const char *, int, const char *,
73
			   struct timespec *);
74
75
int		streamFile(stream_t, const char *);
int		streamPlaylist(stream_t);
76
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
77

78
79
80
81
void
sig_handler(int sig)
{
	switch (sig) {
82
83
84
85
	case SIGTERM:
	case SIGINT:
		quit = 1;
		break;
86
87
88
89
90
91
92
	case SIGHUP:
		rereadPlaylist = 1;
		rereadPlaylist_notify = 1;
		break;
	case SIGUSR1:
		skipTrack = 1;
		break;
93
94
95
	case SIGUSR2:
		queryMetadata = 1;
		break;
96
97
98
99
100
	default:
		break;
	}
}

101
char *
102
buildReencodeCommand(const char *extension, const char *fileName,
103
    metadata_t mdata)
104
{
105
106
107
108
109
	cfg_decoder_t	 decoder;
	cfg_encoder_t	 encoder;
	char		*dec_str, *enc_str;
	char		*commandString;
	size_t		 commandStringLen;
110
	char		*localTitle, *localArtist, *localMetaString, *localAlbum;
111
112
113
114

	decoder = cfg_decoder_find(extension);
	if (!decoder) {
		log_error("cannot decode: %s: unsupported file extension %s",
115
		    fileName, extension);
116
		return (NULL);
117
	}
118
119
120
121
122
123
124
125
126
	encoder = cfg_encoder_get(cfg_get_stream_encoder());
	if (!encoder) {
		log_error("cannot encode: %s: unknown encoder",
		    cfg_get_stream_encoder());
		return (NULL);
	}

	localTitle = UTF8toCHAR(metadata_get_title(mdata), ICONV_REPLACE);
	localArtist = UTF8toCHAR(metadata_get_artist(mdata), ICONV_REPLACE);
127
	localAlbum = UTF8toCHAR(metadata_get_album(mdata), ICONV_REPLACE);
128
129
130
131
132
133
134
	localMetaString = UTF8toCHAR(metadata_get_string(mdata),
	    ICONV_REPLACE);

	dec_str = replaceString(cfg_decoder_get_program(decoder),
	    PLACEHOLDER_TRACK, fileName);
	if (strstr(dec_str, PLACEHOLDER_ARTIST) != NULL) {
		char *tmpStr = replaceString(dec_str, PLACEHOLDER_ARTIST,
135
		    localArtist);
136
137
		xfree(dec_str);
		dec_str = tmpStr;
138
	}
139
140
	if (strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
		char *tmpStr = replaceString(dec_str, PLACEHOLDER_TITLE,
141
		    localTitle);
142
143
		xfree(dec_str);
		dec_str = tmpStr;
144
	}
145
	if (strstr(dec_str, PLACEHOLDER_ALBUM) != NULL) {
146
		char *tmpStr = replaceString(dec_str, PLACEHOLDER_ALBUM,
147
148
149
150
		    localAlbum);
		xfree(dec_str);
		dec_str = tmpStr;
	}
151
152
153
154
155
156
157
158
159
160
	/*
	 * if meta
	 *   if (prog && format)
	 *      metatoformat
	 *   else
	 *     if (!prog && title)
	 *       emptymeta
	 *     else
	 *       replacemeta
	 */
161
162
163
	if (strstr(dec_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
164
165
			char *mdataString = metadata_format_string(mdata,
			    cfg_get_metadata_format_str());
166
167
168
			char *tmpStr = replaceString(dec_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(dec_str);
169
			xfree(mdataString);
170
			dec_str = tmpStr;
171
		} else {
172
173
174
175
176
177
			if (!cfg_get_metadata_program() &&
			    strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, "");
				xfree(dec_str);
				dec_str = tmpStr;
178
			} else {
179
180
181
182
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(dec_str);
				dec_str = tmpStr;
183
184
185
			}
		}
	}
186

187
188
189
	if (!cfg_encoder_get_program(encoder))
		return (dec_str);

190
191
192
193
	enc_str = replaceString(cfg_encoder_get_program(encoder),
	    PLACEHOLDER_ARTIST, localArtist);
	if (strstr(enc_str, PLACEHOLDER_TITLE) != NULL) {
		char *tmpStr = replaceString(enc_str, PLACEHOLDER_TITLE,
194
		    localTitle);
195
196
		xfree(enc_str);
		enc_str = tmpStr;
197
	}
198
199
200
201
202
203
	if (strstr(enc_str, PLACEHOLDER_ALBUM) != NULL) {
		char *tmpStr = replaceString(enc_str, PLACEHOLDER_ALBUM,
		    localAlbum);
		xfree(enc_str);
		enc_str = tmpStr;
	}
204
205
206
	if (strstr(enc_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
207
208
			char *mdataString = metadata_format_string(mdata,
			    cfg_get_metadata_format_str());
209
210
211
			char *tmpStr = replaceString(enc_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(enc_str);
212
			xfree(mdataString);
213
			enc_str = tmpStr;
214
		} else {
215
216
217
218
219
220
			if (!cfg_get_metadata_program() &&
			    strstr(enc_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(enc_str,
				    PLACEHOLDER_METADATA, "");
				xfree(enc_str);
				enc_str = tmpStr;
221
			} else {
222
223
224
225
				char *tmpStr = replaceString(enc_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(enc_str);
				enc_str = tmpStr;
226
227
228
			}
		}
	}
229

230
231
	commandStringLen = strlen(dec_str) + strlen(" | ") +
	    strlen(enc_str) + 1;
232
	commandString = xcalloc(commandStringLen, sizeof(char));
233
234
	snprintf(commandString, commandStringLen, "%s | %s", dec_str,
	    enc_str);
235

236
237
238
	xfree(localTitle);
	xfree(localArtist);
	xfree(localMetaString);
239
240
	xfree(dec_str);
	xfree(enc_str);
241
242

	return (commandString);
243
}
oddsock's avatar
oddsock committed
244

245
metadata_t
246
getMetadata(const char *fileName)
moritz's avatar
moritz committed
247
{
248
	metadata_t	mdata;
249

250
251
252
	if (cfg_get_metadata_program()) {
		if (NULL == (mdata = metadata_program(fileName,
		    cfg_get_metadata_normalize_strings())))
253
254
			return (NULL);

255
		if (!metadata_program_update(mdata, METADATA_ALL)) {
256
			metadata_free(&mdata);
257
			return (NULL);
258
259
		}
	} else {
260
261
		if (NULL == (mdata = metadata_file(fileName,
		    cfg_get_metadata_normalize_strings())))
262
			return (NULL);
moritz's avatar
moritz committed
263

264
265
		if (!metadata_file_update(mdata)) {
			metadata_free(&mdata);
266
			return (NULL);
267
		}
268
	}
269

270
271
272
	return (mdata);
}

273
FILE *
274
275
openResource(stream_t stream, const char *fileName, int *popenFlag,
	     metadata_t *mdata_p, int *isStdin, long *songLen)
276
{
277
278
279
280
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
281
	metadata_t	 mdata;
oddsock's avatar
oddsock committed
282

283
284
	if (mdata_p != NULL)
		*mdata_p = NULL;
285
286
	if (songLen != NULL)
		*songLen = 0;
287

288
	if (strcmp(fileName, "stdin") == 0) {
289
290
		if (cfg_get_metadata_program()) {
			if ((mdata = getMetadata(cfg_get_metadata_program())) == NULL)
291
				return (NULL);
292
			if (0 > stream_set_metadata(stream, mdata, NULL)) {
293
294
295
				metadata_free(&mdata);
				return (NULL);
			}
296
297
298
299
			if (mdata_p != NULL)
				*mdata_p = mdata;
			else
				metadata_free(&mdata);
300
		}
301

302
303
		if (isStdin != NULL)
			*isStdin = 1;
304
		filep = stdin;
305
		return (filep);
oddsock's avatar
oddsock committed
306
	}
307

308
309
310
311
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
312
313
314
315
316
317
318
	p = strrchr(fileName, '.');
	if (p != NULL)
		strlcpy(extension, p, sizeof(extension));
	for (p = extension; *p != '\0'; p++)
		*p = tolower((int)*p);

	if (strlen(extension) == 0) {
319
		log_error("%s: cannot determine file type", fileName);
320
321
322
		return (filep);
	}

323
324
	if (cfg_get_metadata_program()) {
		if ((mdata = getMetadata(cfg_get_metadata_program())) == NULL)
325
326
327
328
329
			return (NULL);
	} else {
		if ((mdata = getMetadata(fileName)) == NULL)
			return (NULL);
	}
330
331
	if (songLen != NULL)
		*songLen = metadata_get_length(mdata);
332
333

	*popenFlag = 0;
334
	if (cfg_get_stream_encoder()) {
335
		int	stderr_fd = -1;
336

337
338
		pCommandString = buildReencodeCommand(extension, fileName,
		    mdata);
339
340
341
342
		if (mdata_p != NULL)
			*mdata_p = mdata;
		else
			metadata_free(&mdata);
343
		log_info("running command: %s", pCommandString);
344

345
		if (cfg_get_program_quiet_stderr()) {
346
347
			int fd;

348
			stderr_fd = dup(fileno(stderr));
349
			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
350
351
				log_alert("%s: %s", _PATH_DEVNULL,
				    strerror(errno));
352
				exit(1);
353
354
			}

355
356
357
358
359
360
361
362
363
364
			dup2(fd, fileno(stderr));
			if (fd > 2)
				close(fd);
		}

		fflush(NULL);
		errno = 0;
		if ((filep = popen(pCommandString, "r")) == NULL) {
			/* popen() does not set errno reliably ... */
			if (errno)
365
366
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
367
			else
368
369
				log_error("execution error: %s",
				    pCommandString);
370
371
372
373
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
374

375
		if (cfg_get_program_quiet_stderr())
376
			dup2(stderr_fd, fileno(stderr));
377
378
379

		if (stderr_fd > 2)
			close(stderr_fd);
380

381
		return (filep);
382
	}
383

384
385
386
387
	if (mdata_p != NULL)
		*mdata_p = mdata;
	else
		metadata_free(&mdata);
388

389
390
391
392
	if ((filep = fopen(fileName, "rb")) == NULL) {
		log_error("%s: %s", fileName, strerror(errno));
		return (NULL);
	}
393
394

	return (filep);
395
396
}

397
int
398
reconnect(stream_t stream)
399
400
401
402
403
{
	unsigned int	i;

	i = 0;
	while (++i) {
404
		if (cfg_get_server_reconnect_attempts() > 0)
405
			log_notice("reconnect: %s: attempt #%u/%u ...",
406
407
			    cfg_get_server_hostname(), i,
			    cfg_get_server_reconnect_attempts());
408
		else
409
			log_notice("reconnect: %s: attempt #%u ...",
410
			    cfg_get_server_hostname(), i);
411

412
413
		stream_disconnect(stream);
		if (0 == stream_connect(stream)) {
414
			log_notice("reconnect: %s: success",
415
			    cfg_get_server_hostname());
416
			return (0);
417
418
		}

419
420
		if (cfg_get_server_reconnect_attempts() > 0 &&
		    i >= cfg_get_server_reconnect_attempts())
421
422
			break;

423
		if (quit)
424
			return (-1);
425
426
		else
			sleep(5);
427
428
	};

429
	log_warning("reconnect failed: giving up");
430
431

	return (-1);
432
433
}

434
const char *
435
getTimeString(long seconds)
436
437
{
	static char	str[20];
438
	long		secs, mins, hours;
439
440
441
442
443
444
445
446
447
448

	if (seconds < 0)
		return (NULL);

	secs = seconds;
	hours = secs / 3600;
	secs %= 3600;
	mins = secs / 60;
	secs %= 60;

449
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
450
451
452
	return ((const char *)str);
}

453
int
454
sendStream(stream_t stream, FILE *filepstream, const char *fileName,
455
	   int isStdin, const char *songLenStr, struct timespec *tv)
456
{
457
	char		  buff[4096];
458
459
460
461
462
	size_t		  bytes_read, total, oldTotal;
	int		  ret;
	double		  kbps = -1.0;
	struct timespec	  timeStamp, *startTime = tv;
	struct timespec	  callTime, currentTime;
463

464
	clock_gettime(CLOCK_MONOTONIC, &callTime);
465

466
	timeStamp.tv_sec = startTime->tv_sec;
467
	timeStamp.tv_nsec = startTime->tv_nsec;
468
469

	total = oldTotal = 0;
470
	ret = STREAM_DONE;
471
472
473
474
475
476
477
478
	while ((bytes_read = fread(buff, 1, sizeof(buff), filepstream)) > 0) {
		if (!stream_get_connected(stream)) {
			log_warning("%s: connection lost",
			    cfg_get_server_hostname());
			if (0 > reconnect(stream)) {
				ret = STREAM_SERVERR;
				break;
			}
479
480
		}

481
		stream_sync(stream);
482

483
484
		if (0 > stream_send(stream, buff, bytes_read)) {
			if (0 > reconnect(stream))
485
				ret = STREAM_SERVERR;
486
			break;
487
488
		}

489
490
		if (quit)
			break;
491
492
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
493
			if (CFG_MEDIA_PLAYLIST == cfg_get_media_type())
494
				log_notice("HUP signal received: playlist re-read scheduled");
495
496
497
		}
		if (skipTrack) {
			skipTrack = 0;
498
			ret = STREAM_SKIP;
499
500
			break;
		}
501

502
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
503
504

		if (queryMetadata ||
505
		    (0 <= cfg_get_metadata_refresh_interval() &&
506
507
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
508
			queryMetadata = 0;
509
			if (cfg_get_metadata_program()) {
510
				ret = STREAM_UPDMDATA;
511
				break;
oddsock's avatar
oddsock committed
512
			}
513
514
		}

515
		total += bytes_read;
516
		if (cfg_get_program_rtstatus_output()) {
517
			double	oldTime, newTime;
518

519
			if (!isStdin && playlistMode) {
520
521
				if (CFG_MEDIA_PROGRAM == cfg_get_media_type()) {
					char *tmp = xstrdup(cfg_get_media_filename());
522
					printf("  [%s]", basename(tmp));
523
524
525
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
526
527
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
528
			}
529
530

			oldTime = (double)timeStamp.tv_sec
531
			    + (double)timeStamp.tv_nsec / 1000000000.0;
532
			newTime = (double)currentTime.tv_sec
533
			    + (double)currentTime.tv_nsec / 1000000000.0;
534
535
			if (songLenStr == NULL)
				printf("  [ %s]",
536
537
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec));
538
539
			else
				printf("  [ %s/%s]",
540
541
542
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec),
				    songLenStr);
543
			if (newTime - oldTime >= 1.0) {
544
				kbps = (((double)(total - oldTotal)
545
				    / (newTime - oldTime)) * 8.0) / 1000.0;
546
				timeStamp.tv_sec = currentTime.tv_sec;
547
				timeStamp.tv_nsec = currentTime.tv_nsec;
548
549
550
551
552
553
554
555
556
557
				oldTotal = total;
			}
			if (kbps < 0)
				printf("                 ");
			else
				printf("  [%8.2f kbps]", kbps);

			printf("  \r");
			fflush(stdout);
		}
oddsock's avatar
oddsock committed
558
	}
559
560
561
	if (ferror(filepstream)) {
		if (errno == EINTR) {
			clearerr(filepstream);
562
			ret = STREAM_CONT;
563
		} else if (errno == EBADF && isStdin)
564
			log_notice("no (more) data available on standard input");
565
		else
566
567
			log_error("sendStream: %s: %s", fileName,
			    strerror(errno));
568
569
	}

570
	return (ret);
571
572
573
}

int
574
streamFile(stream_t stream, const char *fileName)
575
576
577
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
578
	char		*songLenStr = NULL;
579
	int		 isStdin = 0;
580
581
	int		 ret, retval = 0;
	long		 songLen;
582
	metadata_t	 mdata;
583
	struct timespec	 startTime;
584

585
	if ((filepstream = openResource(stream, fileName, &popenFlag, &mdata, &isStdin, &songLen))
586
587
	    == NULL) {
		if (++resource_errors > 100) {
588
			log_error("too many errors; giving up");
589
590
			return (0);
		}
591
592
		/* Continue with next resource on failure: */
		return (1);
593
594
	}
	resource_errors = 0;
595

596
	if (mdata != NULL) {
597
		char	*tmp, *metaData;
598

599
		tmp = metadata_assemble_string(mdata);
600
601
		if ((metaData = UTF8toCHAR(tmp, ICONV_REPLACE)) == NULL)
			metaData = xstrdup("(unknown title)");
602
		xfree(tmp);
603
		log_notice("streaming: %s (%s)", metaData, fileName);
604
		xfree(metaData);
605
606

		/* MP3 streams are special, so set the metadata explicitly: */
607
		if (CFG_STREAM_MP3 == cfg_get_stream_format())
608
			stream_set_metadata(stream, mdata, NULL);
609
610

		metadata_free(&mdata);
611
	} else if (isStdin)
612
		log_notice("streaming: standard input");
613

moritz's avatar
moritz committed
614
	if (songLen > 0)
615
		songLenStr = xstrdup(getTimeString(songLen));
616
	clock_gettime(CLOCK_MONOTONIC, &startTime);
617
	do {
618
		ret = sendStream(stream, filepstream, fileName, isStdin,
619
		    songLenStr, &startTime);
620
621
		if (quit)
			break;
622
		if (ret != STREAM_DONE) {
623
624
			if ((skipTrack && rereadPlaylist) ||
			    (skipTrack && queryMetadata)) {
625
				skipTrack = 0;
626
627
628
629
630
				ret = STREAM_CONT;
			}
			if (queryMetadata && rereadPlaylist) {
				queryMetadata = 0;
				ret = STREAM_CONT;
631
			}
632
			if (ret == STREAM_SKIP || skipTrack) {
633
				skipTrack = 0;
634
635
				if (!isStdin)
					log_notice("USR1 signal received: skipping current track");
636
				retval = 1;
637
638
				ret = STREAM_DONE;
			}
639
640
			if (ret == STREAM_UPDMDATA || queryMetadata) {
				queryMetadata = 0;
641
				if (cfg_get_metadata_no_updates())
642
					continue;
643
				if (cfg_get_metadata_program()) {
644
					char		*mdataStr = NULL;
645
					metadata_t	 prog_mdata;
646

647
					log_info("running metadata program: %s",
648
649
					    cfg_get_metadata_program());
					if ((prog_mdata = getMetadata(cfg_get_metadata_program())) == NULL) {
650
651
652
653
						retval = 0;
						ret = STREAM_DONE;
						continue;
					}
654
					if (0> stream_set_metadata(stream, prog_mdata, &mdataStr)) {
655
656
						retval = 0;
						ret = STREAM_DONE;
657
						continue;
658
					}
659
					metadata_free(&prog_mdata);
660
					log_info("new metadata: %s", mdataStr);
661
662
663
					xfree(mdataStr);
				}
			}
664
665
666
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
667
668
669
			}
		} else
			retval = 1;
670
	} while (ret != STREAM_DONE);
671
672

	if (popenFlag)
oddsock's avatar
oddsock committed
673
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
674
	else if (!isStdin)
oddsock's avatar
oddsock committed
675
		fclose(filepstream);
676

677
678
679
	if (songLenStr != NULL)
		xfree(songLenStr);

680
	return (retval);
oddsock's avatar
oddsock committed
681
}
682

683
int
684
streamPlaylist(stream_t stream)
685
686
{
	const char	*song;
moritz's avatar
moritz committed
687
	char		 lastSong[PATH_MAX];
688
689

	if (playlist == NULL) {
690
691
		switch (cfg_get_media_type()) {
		case CFG_MEDIA_PROGRAM:
692
			if ((playlist = playlist_program(cfg_get_media_filename())) == NULL)
693
				return (0);
694
695
696
697
698
699
			break;
		case CFG_MEDIA_STDIN:
			if ((playlist = playlist_read(NULL)) == NULL)
				return (0);
			break;
		default:
700
			if ((playlist = playlist_read(cfg_get_media_filename())) == NULL)
701
				return (0);
702
			if (playlist_get_num_items(playlist) == 0)
703
				log_warning("%s: playlist empty",
704
				    cfg_get_media_filename());
705
			break;
706
		}
707
	} else {
708
709
710
711
712
		/*
		 * XXX: This preserves traditional behavior, however,
		 *      rereading the playlist after each walkthrough seems a
		 *      bit more logical.
		 */
713
		playlist_rewind(playlist);
714
	}
715

716
717
	if (CFG_MEDIA_PROGRAM != cfg_get_media_type() &&
	    cfg_get_media_shuffle())
718
719
720
721
		playlist_shuffle(playlist);

	while ((song = playlist_get_next(playlist)) != NULL) {
		strlcpy(lastSong, song, sizeof(lastSong));
722
		if (!streamFile(stream, song))
723
			return (0);
724
725
		if (quit)
			break;
726
727
		if (rereadPlaylist) {
			rereadPlaylist = rereadPlaylist_notify = 0;
728
			if (CFG_MEDIA_PROGRAM == cfg_get_media_type())
729
				continue;
730
			log_notice("rereading playlist");
731
732
			if (!playlist_reread(&playlist))
				return (0);
733
			if (cfg_get_media_shuffle())
734
735
736
737
				playlist_shuffle(playlist);
			else {
				playlist_goto_entry(playlist, lastSong);
				playlist_skip_next(playlist);
oddsock's avatar
oddsock committed
738
			}
739
			continue;
740
		}
oddsock's avatar
oddsock committed
741
	}
742

743
	return (1);
oddsock's avatar
oddsock committed
744
745
}

746
int
747
ez_shutdown(int exitval)
748
{
749
	stream_exit();
750
751
752
	playlist_exit();
	cfg_encoder_exit();
	cfg_decoder_exit();
Moritz Grimm's avatar
Moritz Grimm committed
753
	log_exit();
754
	cfg_exit();
755
756
757
758

	return (exitval);
}

759
int
760
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
761
{
762
	int		 ret, cont;
763
	const char	*errstr;
764
	stream_t	 stream;
765
766
	extern char	*optarg;
	extern int	 optind;
767
	struct sigaction act;
moritz's avatar
moritz committed
768
	unsigned int	 i;
769

Moritz Grimm's avatar
Moritz Grimm committed
770
	ret = 1;
771
772
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
773
774
775
776
	    0 > log_init() ||
	    0 > cfg_decoder_init() ||
	    0 > cfg_encoder_init() ||
	    0 > playlist_init() ||
777
	    0 > cfg_file_reload() ||
778
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
779
		return (ez_shutdown(ret));
780

781
782
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
783
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
784
	}
785

786
787
	stream = stream_get(STREAM_DEFAULT);
	if (0 > stream_setup(stream))
788
		return (ez_shutdown(1));
oddsock's avatar
oddsock committed
789

790
791
	memset(&act, 0, sizeof(act));
	act.sa_handler = sig_handler;
792
#ifdef SA_RESTART
793
	act.sa_flags = SA_RESTART;
794
#endif
moritz's avatar
moritz committed
795
796
	for (i = 0; i < sizeof(ezstream_signals) / sizeof(int); i++) {
		if (sigaction(ezstream_signals[i], &act, NULL) == -1) {
797
			log_syserr(ERROR, errno, "sigaction");
798
			return (ez_shutdown(1));
moritz's avatar
moritz committed
799
800
		}
	}
801
802
803
804
	/*
	 * Ignore SIGPIPE, which has been seen to give a long-running ezstream
	 * process trouble. EOF and/or EPIPE are also easier to handle.
	 */
805
806
807
#ifndef SIG_IGN
# define SIG_IGN	 (void (*)(int))1
#endif /* !SIG_IGN */
808
809
	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, NULL) == -1) {
810
		log_syserr(ERROR, errno, "sigaction");
811
812
		return (ez_shutdown(1));
	}
813

814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
	if (0 > stream_connect(stream)) {
		log_error("initial server connection failed");
		return (ez_shutdown(1));
	}
	log_notice("connected: %s://%s:%u%s",
	    cfg_get_server_protocol_str(), cfg_get_server_hostname(),
	    cfg_get_server_port(), cfg_get_stream_mountpoint());

	if (CFG_MEDIA_PROGRAM == cfg_get_media_type() ||
	    CFG_MEDIA_PLAYLIST == cfg_get_media_type() ||
	    (CFG_MEDIA_AUTODETECT == cfg_get_media_type() &&
		(strrcasecmp(cfg_get_media_filename(), ".m3u") == 0 ||
		    strrcasecmp(cfg_get_media_filename(), ".txt") == 0)))
		playlistMode = 1;
	else
		playlistMode = 0;
830

831
832
833
834
835
836
837
838
839
840
841
842
	do {
		if (playlistMode) {
			cont = streamPlaylist(stream);
		} else {
			cont = streamFile(stream,
			    cfg_get_media_filename());
		}
		if (quit)
			break;
		if (cfg_get_media_stream_once())
			break;
	} while (cont);
843

844
	stream_disconnect(stream);
845

846
	if (quit) {
847
848
		if (cfg_get_program_quiet_stderr() &&
		    cfg_get_program_verbosity())
849
850
851