ezstream.c 19.4 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, 2017  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 "mdata.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
stream_t		 main_stream;
42
43
44
playlist_t		 playlist;
int			 playlistMode;
unsigned int		 resource_errors;
45

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

50
51
52
53
54
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
55

56
void		sig_handler(int);
57
58
59
60

static char *	_build_reencode_cmd(const char *, const char *, cfg_stream_t,
				    mdata_t);
static FILE *	openResource(stream_t, const char *, int *, mdata_t *,
61
			     int *, long *);
62
int		reconnect(stream_t);
63
const char *	getTimeString(long);
64
int		sendStream(stream_t, FILE *, const char *, int, const char *,
65
			   struct timespec *);
66
67
int		streamFile(stream_t, const char *);
int		streamPlaylist(stream_t);
68
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
69

70
71
72
73
void
sig_handler(int sig)
{
	switch (sig) {
74
75
76
77
	case SIGTERM:
	case SIGINT:
		quit = 1;
		break;
78
79
80
81
82
83
84
	case SIGHUP:
		rereadPlaylist = 1;
		rereadPlaylist_notify = 1;
		break;
	case SIGUSR1:
		skipTrack = 1;
		break;
85
86
87
	case SIGUSR2:
		queryMetadata = 1;
		break;
88
89
90
91
92
	default:
		break;
	}
}

93
static char *
94
_build_reencode_cmd(const char *extension, const char *filename,
95
    cfg_stream_t cfg_stream, mdata_t md)
96
{
Moritz Grimm's avatar
Moritz Grimm committed
97
98
	cfg_decoder_t		 decoder;
	cfg_encoder_t		 encoder;
99
	char			*artist, *album, *title, *songinfo, *tmp;
Moritz Grimm's avatar
Moritz Grimm committed
100
101
102
103
104
105
106
	char			*filename_quoted;
	char			*custom_songinfo;
	struct util_dict	 dicts[6];
	char			*dec_str;
	char			*enc_str;
	char			*cmd_str;
	size_t			 cmd_str_size;
107

108
	decoder = cfg_decoder_list_findext(cfg_get_decoders(), extension);
109
110
	if (!decoder) {
		log_error("cannot decode: %s: unsupported file extension %s",
111
		    filename, extension);
112
		return (NULL);
113
	}
114
115
	encoder = cfg_encoder_list_get(cfg_get_encoders(),
	    cfg_stream_get_encoder(cfg_stream));
116
117
	if (!encoder) {
		log_error("cannot encode: %s: unknown encoder",
118
		    cfg_stream_get_encoder(cfg_stream));
119
120
121
		return (NULL);
	}

122
	tmp = util_utf82char(mdata_get_artist(md));
123
	artist = util_shellquote(tmp, 0);
124
125
126
	xfree(tmp);

	tmp = util_utf82char(mdata_get_album(md));
127
	album = util_shellquote(tmp, 0);
128
129
130
	xfree(tmp);

	tmp = util_utf82char(mdata_get_title(md));
131
	title = util_shellquote(tmp, 0);
132
133
134
	xfree(tmp);

	tmp = util_utf82char(mdata_get_songinfo(md));
135
	songinfo = util_shellquote(tmp, 0);
136
	xfree(tmp);
Moritz Grimm's avatar
Moritz Grimm committed
137

138
	filename_quoted = util_shellquote(filename, 0);
Moritz Grimm's avatar
Moritz Grimm committed
139

140
	/*
Moritz Grimm's avatar
Moritz Grimm committed
141
142
143
144
145
	 * if (prog && format)
	 *    metatoformat
	 * else
	 *   if (!prog && title)
	 *     emptymeta
146
	 *   else
Moritz Grimm's avatar
Moritz Grimm committed
147
	 *     replacemeta
148
	 */
Moritz Grimm's avatar
Moritz Grimm committed
149
150
	if (cfg_get_metadata_program() &&
	    cfg_get_metadata_format_str()) {
151
152
		char	 buf[BUFSIZ];
		char	*unquoted;
Moritz Grimm's avatar
Moritz Grimm committed
153

154
		mdata_strformat(md, buf, sizeof(buf),
Moritz Grimm's avatar
Moritz Grimm committed
155
		    cfg_get_metadata_format_str());
156
		unquoted = util_utf82char(buf);
157
		custom_songinfo = util_shellquote(unquoted, 0);
Moritz Grimm's avatar
Moritz Grimm committed
158
159
160
161
162
163
		xfree(unquoted);
	} else {
		if (!cfg_get_metadata_program() &&
		    strstr(cfg_decoder_get_program(decoder),
			PLACEHOLDER_TITLE) != NULL) {
			custom_songinfo = xstrdup("");
164
		} else {
Moritz Grimm's avatar
Moritz Grimm committed
165
			custom_songinfo = xstrdup(songinfo);
166
167
		}
	}
Moritz Grimm's avatar
Moritz Grimm committed
168
	xfree(songinfo);
169

Moritz Grimm's avatar
Moritz Grimm committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
	memset(dicts, 0, sizeof(dicts));
	dicts[0].from = PLACEHOLDER_ARTIST;
	dicts[0].to = artist;
	dicts[1].from = PLACEHOLDER_ALBUM;
	dicts[1].to = album;
	dicts[2].from = PLACEHOLDER_TITLE;
	dicts[2].to = title;
	dicts[3].from = PLACEHOLDER_TRACK;
	dicts[3].to = filename_quoted;
	dicts[4].from = PLACEHOLDER_METADATA;
	dicts[4].to = custom_songinfo;

	dec_str = util_expand_words(cfg_decoder_get_program(decoder), dicts);

	if (!cfg_get_metadata_program() &&
	    strstr(cfg_encoder_get_program(encoder),
		PLACEHOLDER_TITLE) != NULL) {
		xfree(custom_songinfo);
		dicts[4].to = custom_songinfo = xstrdup("");
189
	}
190

Moritz Grimm's avatar
Moritz Grimm committed
191
	enc_str = util_expand_words(cfg_encoder_get_program(encoder), dicts);
192

Moritz Grimm's avatar
Moritz Grimm committed
193
194
195
	cmd_str_size = strlen(dec_str) + strlen(" | ") + strlen(enc_str) + 1;
	cmd_str = xcalloc(cmd_str_size, sizeof(char));
	snprintf(cmd_str, cmd_str_size, "%s | %s", dec_str, enc_str);
196
197
	xfree(dec_str);
	xfree(enc_str);
198

Moritz Grimm's avatar
Moritz Grimm committed
199
200
201
202
203
204
205
	xfree(artist);
	xfree(album);
	xfree(title);
	xfree(filename_quoted);
	xfree(custom_songinfo);

	return (cmd_str);
206
}
oddsock's avatar
oddsock committed
207

208
static FILE *
209
210
openResource(stream_t stream, const char *filename, int *popenFlag,
	     mdata_t *md_p, int *isStdin, long *songLen)
211
{
212
213
214
215
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
216
	mdata_t 	 md;
217
	cfg_stream_t	 cfg_stream = stream_get_cfg_stream(stream);
oddsock's avatar
oddsock committed
218

219
220
	if (md_p != NULL)
		*md_p = NULL;
221
222
	if (songLen != NULL)
		*songLen = 0;
223

224
	if ((isStdin && *isStdin) ||
225
	    strcasecmp(filename, "stdin") == 0) {
226
		if (cfg_get_metadata_program()) {
227
228
229
230
			md = mdata_create();

			if (0 > mdata_run_program(md, cfg_get_metadata_program()) ||
			    0 > stream_set_metadata(stream, md, NULL)) {
231
				mdata_destroy(&md);
232
233
				return (NULL);
			}
234

235
236
			if (md_p != NULL)
				*md_p = md;
237
			else
238
				mdata_destroy(&md);
239
		}
240

241
242
		if (isStdin != NULL)
			*isStdin = 1;
243
		filep = stdin;
244
		return (filep);
oddsock's avatar
oddsock committed
245
	}
246

247
248
249
250
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
251
	p = strrchr(filename, '.');
252
253
254
	if (p != NULL)
		strlcpy(extension, p, sizeof(extension));
	for (p = extension; *p != '\0'; p++)
255
		*p = (char)tolower((int)*p);
256
257

	if (strlen(extension) == 0) {
258
		log_error("%s: cannot determine file type", filename);
259
260
261
		return (filep);
	}

262
	md = mdata_create();
263
	if (cfg_get_metadata_program()) {
264
265
		if (0 > mdata_run_program(md, cfg_get_metadata_program()))
			mdata_destroy(&md);
266
	} else {
267
268
		if (0 > mdata_parse_file(md, filename))
			mdata_destroy(&md);
269
	}
270
271
	if (NULL == md)
		return (NULL);
272
	if (songLen != NULL)
273
		*songLen = mdata_get_length(md);
274
275

	*popenFlag = 0;
276
	if (cfg_stream_get_encoder(cfg_stream)) {
277
		int	stderr_fd = -1;
278

279
		pCommandString = _build_reencode_cmd(extension, filename,
280
		    cfg_stream, md);
281
282
		if (md_p != NULL)
			*md_p = md;
283
		else
284
			mdata_destroy(&md);
285
		log_info("running command: %s", pCommandString);
286

287
		if (cfg_get_program_quiet_stderr()) {
288
289
			int fd;

290
			stderr_fd = dup(fileno(stderr));
291
292
293
294
			if (0 > stderr_fd) {
				log_alert("dup: %s", strerror(errno));
				exit(1);
			}
295
			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
296
297
				log_alert("%s: %s", _PATH_DEVNULL,
				    strerror(errno));
298
				exit(1);
299
300
			}

301
			dup2(fd, fileno(stderr));
302
			close(fd);
303
304
305
306
307
308
309
		}

		fflush(NULL);
		errno = 0;
		if ((filep = popen(pCommandString, "r")) == NULL) {
			/* popen() does not set errno reliably ... */
			if (errno)
310
311
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
312
			else
313
314
				log_error("execution error: %s",
				    pCommandString);
315
316
317
318
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
319

320
		if (cfg_get_program_quiet_stderr())
321
			dup2(stderr_fd, fileno(stderr));
322

323
		if (stderr_fd != -1)
324
			close(stderr_fd);
325

326
		return (filep);
327
	}
328

329
330
	if (md_p != NULL)
		*md_p = md;
331
	else
332
		mdata_destroy(&md);
333

334
335
	if ((filep = fopen(filename, "rb")) == NULL) {
		log_error("%s: %s", filename, strerror(errno));
336
337
		return (NULL);
	}
338
339

	return (filep);
340
341
}

342
int
343
reconnect(stream_t stream)
344
345
{
	unsigned int	i;
346
	cfg_server_t	cfg_server = stream_get_cfg_server(stream);
347
348
349

	i = 0;
	while (++i) {
350
		if (cfg_server_get_reconnect_attempts(cfg_server) > 0)
351
			log_notice("reconnect: %s: attempt #%u/%u ...",
352
353
			    cfg_server_get_hostname(cfg_server), i,
			    cfg_server_get_reconnect_attempts(cfg_server));
354
		else
355
			log_notice("reconnect: %s: attempt #%u ...",
356
			    cfg_server_get_hostname(cfg_server), i);
357

358
359
		stream_disconnect(stream);
		if (0 == stream_connect(stream)) {
360
			log_notice("reconnect: %s: success",
361
			    cfg_server_get_hostname(cfg_server));
362
			return (0);
363
364
		}

365
366
		if (cfg_server_get_reconnect_attempts(cfg_server) > 0 &&
		    i >= cfg_server_get_reconnect_attempts(cfg_server))
367
368
			break;

369
		if (quit)
370
			return (-1);
371
372
		else
			sleep(5);
373
374
	};

375
	log_warning("reconnect failed: giving up");
376
377

	return (-1);
378
379
}

380
const char *
381
getTimeString(long seconds)
382
383
{
	static char	str[20];
384
	long		secs, mins, hours;
385
386
387
388
389
390
391
392
393
394

	if (seconds < 0)
		return (NULL);

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

395
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
396
397
398
	return ((const char *)str);
}

399
int
400
sendStream(stream_t stream, FILE *filepstream, const char *fileName,
401
	   int isStdin, const char *songLenStr, struct timespec *tv)
402
{
403
	char		  buff[4096];
404
405
406
407
408
	size_t		  bytes_read, total, oldTotal;
	int		  ret;
	double		  kbps = -1.0;
	struct timespec	  timeStamp, *startTime = tv;
	struct timespec	  callTime, currentTime;
409
	cfg_server_t	  cfg_server = stream_get_cfg_server(stream);
410
	cfg_intake_t	  cfg_intake = stream_get_cfg_intake(stream);
411

412
	clock_gettime(CLOCK_MONOTONIC, &callTime);
413

414
	timeStamp.tv_sec = startTime->tv_sec;
415
	timeStamp.tv_nsec = startTime->tv_nsec;
416
417

	total = oldTotal = 0;
418
	ret = STREAM_DONE;
419
420
421
	while ((bytes_read = fread(buff, 1, sizeof(buff), filepstream)) > 0) {
		if (!stream_get_connected(stream)) {
			log_warning("%s: connection lost",
422
			    cfg_server_get_hostname(cfg_server));
423
424
425
426
			if (0 > reconnect(stream)) {
				ret = STREAM_SERVERR;
				break;
			}
427
428
		}

429
		stream_sync(stream);
430

431
432
		if (0 > stream_send(stream, buff, bytes_read)) {
			if (0 > reconnect(stream))
433
				ret = STREAM_SERVERR;
434
			break;
435
436
		}

437
438
		if (quit)
			break;
439
440
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
441
			if (CFG_INTAKE_PLAYLIST == cfg_intake_get_type(cfg_intake))
442
				log_notice("HUP signal received: playlist re-read scheduled");
443
444
445
		}
		if (skipTrack) {
			skipTrack = 0;
446
			ret = STREAM_SKIP;
447
448
			break;
		}
449

450
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
451
452

		if (queryMetadata ||
453
		    (0 <= cfg_get_metadata_refresh_interval() &&
454
455
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
456
			queryMetadata = 0;
457
			if (cfg_get_metadata_program()) {
458
				ret = STREAM_UPDMDATA;
459
				break;
oddsock's avatar
oddsock committed
460
			}
461
462
		}

463
		total += bytes_read;
464
		if (cfg_get_program_rtstatus_output()) {
465
			double	oldTime, newTime;
466

467
			if (!isStdin && playlistMode) {
468
469
				if (CFG_INTAKE_PROGRAM == cfg_intake_get_type(cfg_intake)) {
					char *tmp = xstrdup(cfg_intake_get_filename(cfg_intake));
470
					printf("  [%s]", basename(tmp));
471
472
473
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
474
475
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
476
			}
477
478

			oldTime = (double)timeStamp.tv_sec
479
			    + (double)timeStamp.tv_nsec / 1000000000.0;
480
			newTime = (double)currentTime.tv_sec
481
			    + (double)currentTime.tv_nsec / 1000000000.0;
482
483
			if (songLenStr == NULL)
				printf("  [ %s]",
484
485
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec));
486
487
			else
				printf("  [ %s/%s]",
488
489
490
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec),
				    songLenStr);
491
			if (newTime - oldTime >= 1.0) {
492
				kbps = (((double)(total - oldTotal)
493
				    / (newTime - oldTime)) * 8.0) / 1000.0;
494
				timeStamp.tv_sec = currentTime.tv_sec;
495
				timeStamp.tv_nsec = currentTime.tv_nsec;
496
497
498
499
500
501
502
503
504
505
				oldTotal = total;
			}
			if (kbps < 0)
				printf("                 ");
			else
				printf("  [%8.2f kbps]", kbps);

			printf("  \r");
			fflush(stdout);
		}
oddsock's avatar
oddsock committed
506
	}
507
508
509
	if (ferror(filepstream)) {
		if (errno == EINTR) {
			clearerr(filepstream);
510
			ret = STREAM_CONT;
511
		} else if (errno == EBADF && isStdin)
512
			log_notice("no (more) data available on standard input");
513
		else
514
515
			log_error("sendStream: %s: %s", fileName,
			    strerror(errno));
516
517
	}

518
	return (ret);
519
520
521
}

int
522
streamFile(stream_t stream, const char *fileName)
523
524
525
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
526
	char		*songLenStr = NULL;
527
528
	int		 ret, retval = 0;
	long		 songLen;
529
	mdata_t 	 md = NULL;
530
	struct timespec	 startTime;
531
	cfg_stream_t	 cfg_stream = stream_get_cfg_stream(stream);
532
533
	cfg_intake_t	 cfg_intake = stream_get_cfg_intake(stream);
	int		 isStdin = cfg_intake_get_type(cfg_intake) == CFG_INTAKE_STDIN;
534

535
	if ((filepstream = openResource(stream, fileName, &popenFlag, &md, &isStdin, &songLen))
536
	    == NULL) {
537
		mdata_destroy(&md);
538
		if (++resource_errors > 100) {
539
			log_error("too many errors; giving up");
540
541
			return (0);
		}
542
543
		/* Continue with next resource on failure: */
		return (1);
544
545
	}
	resource_errors = 0;
546

547
548
549
	if (md != NULL) {
		const char	*tmp;
		char		*metaData;
550

551
552
553
		tmp = mdata_get_songinfo(md) ?
		    mdata_get_songinfo(md) : mdata_get_name(md);
		metaData = util_utf82char(tmp);
554
555
		log_notice("streaming: %s (%s)", metaData,
		    isStdin ? "stdin" : fileName);
556
		xfree(metaData);
557
558

		/* MP3 streams are special, so set the metadata explicitly: */
559
		if (CFG_STREAM_MP3 == cfg_stream_get_format(cfg_stream))
560
			stream_set_metadata(stream, md, NULL);
561

562
		mdata_destroy(&md);
563
	} else if (isStdin)
564
		log_notice("streaming: standard input");
565

moritz's avatar
moritz committed
566
	if (songLen > 0)
567
		songLenStr = xstrdup(getTimeString(songLen));
568
	clock_gettime(CLOCK_MONOTONIC, &startTime);
569
	do {
570
		ret = sendStream(stream, filepstream, fileName, isStdin,
571
		    songLenStr, &startTime);
572
573
		if (quit)
			break;
574
		if (ret != STREAM_DONE) {
575
576
			if ((skipTrack && rereadPlaylist) ||
			    (skipTrack && queryMetadata)) {
577
				skipTrack = 0;
578
579
580
581
582
				ret = STREAM_CONT;
			}
			if (queryMetadata && rereadPlaylist) {
				queryMetadata = 0;
				ret = STREAM_CONT;
583
			}
584
			if (ret == STREAM_SKIP || skipTrack) {
585
				skipTrack = 0;
586
587
				if (!isStdin)
					log_notice("USR1 signal received: skipping current track");
588
				retval = 1;
589
590
				ret = STREAM_DONE;
			}
591
592
			if (ret == STREAM_UPDMDATA || queryMetadata) {
				queryMetadata = 0;
593
				if (cfg_get_metadata_no_updates())
594
					continue;
595
				if (cfg_get_metadata_program()) {
596
					char		*mdataStr = NULL;
597
					mdata_t 	 prog_md;
598

599
					log_info("running metadata program: %s",
600
					    cfg_get_metadata_program());
601
602
603
604
					prog_md = mdata_create();
					if (0 > mdata_run_program(md, cfg_get_metadata_program()) ||
					    0 > stream_set_metadata(stream, prog_md, &mdataStr)) {
						mdata_destroy(&prog_md);
605
606
						retval = 0;
						ret = STREAM_DONE;
607
						continue;
608
					}
609
					mdata_destroy(&prog_md);
610
					log_info("new metadata: %s", mdataStr);
611
612
613
					xfree(mdataStr);
				}
			}
614
615
616
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
617
618
619
			}
		} else
			retval = 1;
620
	} while (ret != STREAM_DONE);
621
622

	if (popenFlag)
oddsock's avatar
oddsock committed
623
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
624
	else if (!isStdin)
oddsock's avatar
oddsock committed
625
		fclose(filepstream);
626

627
628
629
	if (songLenStr != NULL)
		xfree(songLenStr);

630
	return (retval);
oddsock's avatar
oddsock committed
631
}
632

633
int
634
streamPlaylist(stream_t stream)
635
636
{
	const char	*song;
moritz's avatar
moritz committed
637
	char		 lastSong[PATH_MAX];
638
	cfg_intake_t	 cfg_intake = stream_get_cfg_intake(stream);
639
640

	if (playlist == NULL) {
641
642
643
		switch (cfg_intake_get_type(cfg_intake)) {
		case CFG_INTAKE_PROGRAM:
			if ((playlist = playlist_program(cfg_intake_get_filename(cfg_intake))) == NULL)
644
				return (0);
645
			break;
646
		case CFG_INTAKE_STDIN:
647
648
649
650
			if ((playlist = playlist_read(NULL)) == NULL)
				return (0);
			break;
		default:
651
			if ((playlist = playlist_read(cfg_intake_get_filename(cfg_intake))) == NULL)
652
				return (0);
653
			if (playlist_get_num_items(playlist) == 0)
654
				log_warning("%s: playlist empty",
655
				    cfg_intake_get_filename(cfg_intake));
656
			break;
657
		}
658
	} else {
659
660
661
662
663
		/*
		 * XXX: This preserves traditional behavior, however,
		 *      rereading the playlist after each walkthrough seems a
		 *      bit more logical.
		 */
664
		playlist_rewind(playlist);
665
	}
666

667
668
	if (CFG_INTAKE_PROGRAM != cfg_intake_get_type(cfg_intake) &&
	    cfg_intake_get_shuffle(cfg_intake))
669
670
671
672
		playlist_shuffle(playlist);

	while ((song = playlist_get_next(playlist)) != NULL) {
		strlcpy(lastSong, song, sizeof(lastSong));
673
		if (!streamFile(stream, song))
674
			return (0);
675
676
		if (quit)
			break;
677
678
		if (rereadPlaylist) {
			rereadPlaylist = rereadPlaylist_notify = 0;
679
			if (CFG_INTAKE_PROGRAM == cfg_intake_get_type(cfg_intake))
680
				continue;
681
			log_notice("rereading playlist");
682
683
			if (!playlist_reread(&playlist))
				return (0);
684
			if (cfg_intake_get_shuffle(cfg_intake))
685
686
687
688
				playlist_shuffle(playlist);
			else {
				playlist_goto_entry(playlist, lastSong);
				playlist_skip_next(playlist);
oddsock's avatar
oddsock committed
689
			}
690
			continue;
691
		}
oddsock's avatar
oddsock committed
692
	}
693

694
	return (1);
oddsock's avatar
oddsock committed
695
696
}

697
int
698
ez_shutdown(int exitval)
699
{
700
701
702
	if (main_stream)
		stream_destroy(&main_stream);

703
	stream_exit();
704
	playlist_exit();
Moritz Grimm's avatar
Moritz Grimm committed
705
	log_exit();
706
	cfg_exit();
707
708
709
710

	return (exitval);
}

711
int
712
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
713
{
714
	int		 ret, cont;
715
	const char	*errstr;
716
717
	extern char	*optarg;
	extern int	 optind;
718
	struct sigaction act;
moritz's avatar
moritz committed
719
	unsigned int	 i;
720
721
	cfg_server_t	 cfg_server;
	cfg_stream_t	 cfg_stream;
722
	cfg_intake_t	 cfg_intake;
723

Moritz Grimm's avatar
Moritz Grimm committed
724
	ret = 1;
725
726
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
727
728
	    0 > log_init() ||
	    0 > playlist_init() ||
729
	    0 > cfg_file_reload() ||
730
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
731
		return (ez_shutdown(ret));
732

733
734
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
735
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
736
	}
737

738
739
	main_stream = stream_create(CFG_DEFAULT);
	if (0 > stream_configure(main_stream))
740
		return (ez_shutdown(1));
741
742
	cfg_server = stream_get_cfg_server(main_stream);
	cfg_stream = stream_get_cfg_stream(main_stream);
743
	cfg_intake = stream_get_cfg_intake(main_stream);
oddsock's avatar
oddsock committed
744

745
746
	memset(&act, 0, sizeof(act));
	act.sa_handler = sig_handler;
747
#ifdef SA_RESTART
748
	act.sa_flags = SA_RESTART;
749
#endif
moritz's avatar
moritz committed
750
751
	for (i = 0; i < sizeof(ezstream_signals) / sizeof(int); i++) {
		if (sigaction(ezstream_signals[i], &act, NULL) == -1) {
752
			log_syserr(ERROR, errno, "sigaction");
753
			return (ez_shutdown(1));
moritz's avatar
moritz committed
754
755
		}
	}
756
757
758
759
	/*
	 * Ignore SIGPIPE, which has been seen to give a long-running ezstream
	 * process trouble. EOF and/or EPIPE are also easier to handle.
	 */
760
761
762
#ifndef SIG_IGN
# define SIG_IGN	 (void (*)(int))1
#endif /* !SIG_IGN */
763
764
	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, NULL) == -1) {
765
		log_syserr(ERROR, errno, "sigaction");
766
767
		return (ez_shutdown(1));
	}
768

769
	if (0 > util_write_pid_file(cfg_get_program_pid_file()))
770
771
		log_syserr(WARNING, errno, cfg_get_program_pid_file());

772
	if (0 > stream_connect(main_stream)) {
773
774
775
776
		log_error("initial server connection failed");
		return (ez_shutdown(1));
	}
	log_notice("connected: %s://%s:%u%s",
777
778
779
780
	    cfg_server_get_protocol_str(cfg_server),
	    cfg_server_get_hostname(cfg_server),
	    cfg_server_get_port(cfg_server),
	    cfg_stream_get_mountpoint(cfg_stream));
781

782
783
784
785
786
	if (CFG_INTAKE_PROGRAM == cfg_intake_get_type(cfg_intake) ||
	    CFG_INTAKE_PLAYLIST == cfg_intake_get_type(cfg_intake) ||
	    (CFG_INTAKE_AUTODETECT == cfg_intake_get_type(cfg_intake) &&
		(util_strrcasecmp(cfg_intake_get_filename(cfg_intake), ".m3u") == 0 ||
		    util_strrcasecmp(cfg_intake_get_filename(cfg_intake), ".txt") == 0)))
787