ezstream.c 19.6 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
	char			*filename_quoted;
	char			*custom_songinfo;
	struct util_dict	 dicts[6];
	char			*dec_str;
	char			*cmd_str;
	size_t			 cmd_str_size;
106

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

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

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

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

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

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

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

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

Moritz Grimm's avatar
Moritz Grimm committed
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
	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;

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

188
189
190
	dec_str = util_expand_words(cfg_decoder_get_program(decoder), dicts);
	cmd_str_size = strlen(dec_str) + 1;
	if (cfg_encoder_get_program(encoder)) {
Moritz Grimm's avatar
Moritz Grimm committed
191
192
		char	*enc_str;

193
194
195
196
197
198
199
200
201
202
203
204
		enc_str = util_expand_words(cfg_encoder_get_program(encoder),
		    dicts);
		cmd_str_size += strlen(" | ") + strlen(enc_str);
		cmd_str = xcalloc(cmd_str_size, sizeof(char));
		snprintf(cmd_str, cmd_str_size, "%s | %s", dec_str, enc_str);
		xfree(enc_str);
		xfree(dec_str);
	} else {
		cmd_str = xcalloc(cmd_str_size, sizeof(char));
		snprintf(cmd_str, cmd_str_size, "%s", dec_str);
		xfree(dec_str);
	}
205

Moritz Grimm's avatar
Moritz Grimm committed
206
207
208
209
210
211
212
	xfree(artist);
	xfree(album);
	xfree(title);
	xfree(filename_quoted);
	xfree(custom_songinfo);

	return (cmd_str);
213
}
oddsock's avatar
oddsock committed
214

215
static FILE *
216
217
openResource(stream_t stream, const char *filename, int *popenFlag,
	     mdata_t *md_p, int *isStdin, long *songLen)
218
{
219
220
221
222
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
223
	mdata_t 	 md;
224
	cfg_stream_t	 cfg_stream = stream_get_cfg_stream(stream);
oddsock's avatar
oddsock committed
225

226
227
	if (md_p != NULL)
		*md_p = NULL;
228
229
	if (songLen != NULL)
		*songLen = 0;
230

231
	if ((isStdin && *isStdin) ||
232
	    strcasecmp(filename, "stdin") == 0) {
233
		if (cfg_get_metadata_program()) {
234
235
236
237
			md = mdata_create();

			if (0 > mdata_run_program(md, cfg_get_metadata_program()) ||
			    0 > stream_set_metadata(stream, md, NULL)) {
238
				mdata_destroy(&md);
239
240
				return (NULL);
			}
241

242
243
			if (md_p != NULL)
				*md_p = md;
244
			else
245
				mdata_destroy(&md);
246
		}
247

248
249
		if (isStdin != NULL)
			*isStdin = 1;
250
		filep = stdin;
251
		return (filep);
oddsock's avatar
oddsock committed
252
	}
253

254
255
256
257
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
258
	p = strrchr(filename, '.');
259
260
261
	if (p != NULL)
		strlcpy(extension, p, sizeof(extension));
	for (p = extension; *p != '\0'; p++)
262
		*p = (char)tolower((int)*p);
263
264

	if (strlen(extension) == 0) {
265
		log_error("%s: cannot determine file type", filename);
266
267
268
		return (filep);
	}

269
	md = mdata_create();
270
	if (cfg_get_metadata_program()) {
271
272
		if (0 > mdata_run_program(md, cfg_get_metadata_program()))
			mdata_destroy(&md);
273
	} else {
274
275
		if (0 > mdata_parse_file(md, filename))
			mdata_destroy(&md);
276
	}
277
278
	if (NULL == md)
		return (NULL);
279
	if (songLen != NULL)
280
		*songLen = mdata_get_length(md);
281
282

	*popenFlag = 0;
283
	if (cfg_stream_get_encoder(cfg_stream)) {
284
		int	stderr_fd = -1;
285

286
		pCommandString = _build_reencode_cmd(extension, filename,
287
		    cfg_stream, md);
288
289
		if (md_p != NULL)
			*md_p = md;
290
		else
291
			mdata_destroy(&md);
292
		log_info("running command: %s", pCommandString);
293

294
		if (cfg_get_program_quiet_stderr()) {
295
296
			int fd;

297
			stderr_fd = dup(fileno(stderr));
298
299
300
301
			if (0 > stderr_fd) {
				log_alert("dup: %s", strerror(errno));
				exit(1);
			}
302
			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
303
304
				log_alert("%s: %s", _PATH_DEVNULL,
				    strerror(errno));
305
				exit(1);
306
307
			}

308
			dup2(fd, fileno(stderr));
309
			close(fd);
310
311
312
313
314
315
316
		}

		fflush(NULL);
		errno = 0;
		if ((filep = popen(pCommandString, "r")) == NULL) {
			/* popen() does not set errno reliably ... */
			if (errno)
317
318
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
319
			else
320
321
				log_error("execution error: %s",
				    pCommandString);
322
323
324
325
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
326

327
		if (cfg_get_program_quiet_stderr())
328
			dup2(stderr_fd, fileno(stderr));
329

330
		if (stderr_fd != -1)
331
			close(stderr_fd);
332

333
		return (filep);
334
	}
335

336
337
	if (md_p != NULL)
		*md_p = md;
338
	else
339
		mdata_destroy(&md);
340

341
342
	if ((filep = fopen(filename, "rb")) == NULL) {
		log_error("%s: %s", filename, strerror(errno));
343
344
		return (NULL);
	}
345
346

	return (filep);
347
348
}

349
int
350
reconnect(stream_t stream)
351
352
{
	unsigned int	i;
353
	cfg_server_t	cfg_server = stream_get_cfg_server(stream);
354
355
356

	i = 0;
	while (++i) {
357
		if (cfg_server_get_reconnect_attempts(cfg_server) > 0)
358
			log_notice("reconnect: %s: attempt #%u/%u ...",
359
360
			    cfg_server_get_hostname(cfg_server), i,
			    cfg_server_get_reconnect_attempts(cfg_server));
361
		else
362
			log_notice("reconnect: %s: attempt #%u ...",
363
			    cfg_server_get_hostname(cfg_server), i);
364

365
366
		stream_disconnect(stream);
		if (0 == stream_connect(stream)) {
367
			log_notice("reconnect: %s: success",
368
			    cfg_server_get_hostname(cfg_server));
369
			return (0);
370
371
		}

372
373
		if (cfg_server_get_reconnect_attempts(cfg_server) > 0 &&
		    i >= cfg_server_get_reconnect_attempts(cfg_server))
374
375
			break;

376
		if (quit)
377
			return (-1);
378
379
		else
			sleep(5);
380
381
	};

382
	log_warning("reconnect failed: giving up");
383
384

	return (-1);
385
386
}

387
const char *
388
getTimeString(long seconds)
389
{
390
	static char	str[25];
391
	long		secs, mins, hours;
392
393
394
395
396
397
398
399
400
401

	if (seconds < 0)
		return (NULL);

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

402
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
403
404
405
	return ((const char *)str);
}

406
int
407
sendStream(stream_t stream, FILE *filepstream, const char *fileName,
408
	   int isStdin, const char *songLenStr, struct timespec *tv)
409
{
410
	char		  buff[4096];
411
412
413
414
415
	size_t		  bytes_read, total, oldTotal;
	int		  ret;
	double		  kbps = -1.0;
	struct timespec	  timeStamp, *startTime = tv;
	struct timespec	  callTime, currentTime;
416
	cfg_server_t	  cfg_server = stream_get_cfg_server(stream);
417
	cfg_intake_t	  cfg_intake = stream_get_cfg_intake(stream);
418

419
	clock_gettime(CLOCK_MONOTONIC, &callTime);
420

421
	timeStamp.tv_sec = startTime->tv_sec;
422
	timeStamp.tv_nsec = startTime->tv_nsec;
423
424

	total = oldTotal = 0;
425
	ret = STREAM_DONE;
426
427
428
	while ((bytes_read = fread(buff, 1, sizeof(buff), filepstream)) > 0) {
		if (!stream_get_connected(stream)) {
			log_warning("%s: connection lost",
429
			    cfg_server_get_hostname(cfg_server));
430
431
432
433
			if (0 > reconnect(stream)) {
				ret = STREAM_SERVERR;
				break;
			}
434
435
		}

436
		stream_sync(stream);
437

438
439
		if (0 > stream_send(stream, buff, bytes_read)) {
			if (0 > reconnect(stream))
440
				ret = STREAM_SERVERR;
441
			break;
442
443
		}

444
445
		if (quit)
			break;
446
447
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
448
			if (CFG_INTAKE_PLAYLIST == cfg_intake_get_type(cfg_intake))
449
				log_notice("HUP signal received: playlist re-read scheduled");
450
451
452
		}
		if (skipTrack) {
			skipTrack = 0;
453
			ret = STREAM_SKIP;
454
455
			break;
		}
456

457
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
458
459

		if (queryMetadata ||
460
		    (0 <= cfg_get_metadata_refresh_interval() &&
461
462
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
463
			queryMetadata = 0;
464
			if (cfg_get_metadata_program()) {
465
				ret = STREAM_UPDMDATA;
466
				break;
oddsock's avatar
oddsock committed
467
			}
468
469
		}

470
		total += bytes_read;
471
		if (cfg_get_program_rtstatus_output()) {
472
			double	oldTime, newTime;
473

474
			if (!isStdin && playlistMode) {
475
476
				if (CFG_INTAKE_PROGRAM == cfg_intake_get_type(cfg_intake)) {
					char *tmp = xstrdup(cfg_intake_get_filename(cfg_intake));
477
					printf("  [%s]", basename(tmp));
478
479
480
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
481
482
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
483
			}
484
485

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

			printf("  \r");
			fflush(stdout);
		}
oddsock's avatar
oddsock committed
513
	}
514
515
516
	if (ferror(filepstream)) {
		if (errno == EINTR) {
			clearerr(filepstream);
517
			ret = STREAM_CONT;
518
		} else if (errno == EBADF && isStdin)
519
			log_notice("no (more) data available on standard input");
520
		else
521
522
			log_error("sendStream: %s: %s", fileName,
			    strerror(errno));
523
524
	}

525
	return (ret);
526
527
528
}

int
529
streamFile(stream_t stream, const char *fileName)
530
531
532
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
533
	char		*songLenStr = NULL;
534
535
	int		 ret, retval = 0;
	long		 songLen;
536
	mdata_t 	 md = NULL;
537
	struct timespec	 startTime;
538
	cfg_stream_t	 cfg_stream = stream_get_cfg_stream(stream);
539
540
	cfg_intake_t	 cfg_intake = stream_get_cfg_intake(stream);
	int		 isStdin = cfg_intake_get_type(cfg_intake) == CFG_INTAKE_STDIN;
541

542
	if ((filepstream = openResource(stream, fileName, &popenFlag, &md, &isStdin, &songLen))
543
	    == NULL) {
544
		mdata_destroy(&md);
545
		if (++resource_errors > 100) {
546
			log_error("too many errors; giving up");
547
548
			return (0);
		}
549
550
		/* Continue with next resource on failure: */
		return (1);
551
552
	}
	resource_errors = 0;
553

554
555
556
	if (md != NULL) {
		const char	*tmp;
		char		*metaData;
557

558
559
560
		tmp = mdata_get_songinfo(md) ?
		    mdata_get_songinfo(md) : mdata_get_name(md);
		metaData = util_utf82char(tmp);
561
562
		log_notice("streaming: %s (%s)", metaData,
		    isStdin ? "stdin" : fileName);
563
		xfree(metaData);
564
565

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

569
		mdata_destroy(&md);
570
	} else if (isStdin)
571
		log_notice("streaming: standard input");
572

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

606
					log_info("running metadata program: %s",
607
					    cfg_get_metadata_program());
608
609
610
611
					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);
612
613
						retval = 0;
						ret = STREAM_DONE;
614
						continue;
615
					}
616
					mdata_destroy(&prog_md);
617
					log_info("new metadata: %s", mdataStr);
618
619
620
					xfree(mdataStr);
				}
			}
621
622
623
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
624
625
626
			}
		} else
			retval = 1;
627
	} while (ret != STREAM_DONE);
628
629

	if (popenFlag)
oddsock's avatar
oddsock committed
630
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
631
	else if (!isStdin)
oddsock's avatar
oddsock committed
632
		fclose(filepstream);
633

634
635
636
	if (songLenStr != NULL)
		xfree(songLenStr);

637
	return (retval);
oddsock's avatar
oddsock committed
638
}
639

640
int
641
streamPlaylist(stream_t stream)
642
643
{
	const char	*song;
moritz's avatar
moritz committed
644
	char		 lastSong[PATH_MAX];
645
	cfg_intake_t	 cfg_intake = stream_get_cfg_intake(stream);
646
647

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

674
675
	if (CFG_INTAKE_PROGRAM != cfg_intake_get_type(cfg_intake) &&
	    cfg_intake_get_shuffle(cfg_intake))
676
677
678
679
		playlist_shuffle(playlist);

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

701
	return (1);
oddsock's avatar
oddsock committed
702
703
}

704
int
705
ez_shutdown(int exitval)
706
{
707
708
709
	if (main_stream)
		stream_destroy(&main_stream);

710
	stream_exit();
711
	playlist_exit();
Moritz Grimm's avatar
Moritz Grimm committed
712
	log_exit();
713
	cfg_exit();
714
715
716
717

	return (exitval);
}

718
int
719
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
720
{
721
	int		 ret, cont;
722
	const char	*errstr;
723
724
	extern char	*optarg;
	extern int	 optind;
725
	struct sigaction act;
moritz's avatar
moritz committed
726
	unsigned int	 i;
727
728
	cfg_server_t	 cfg_server;
	cfg_stream_t	 cfg_stream;
729
	cfg_intake_t	 cfg_intake;
730

Moritz Grimm's avatar
Moritz Grimm committed
731
	ret = 1;
732
733
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
Moritz Grimm's avatar
Moritz Grimm committed
734
	    0 > log_init(cfg_get_program_name()) ||
735
	    0 > playlist_init() ||
736
	    0 > cfg_file_reload() ||
737
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
738
		return (ez_shutdown(ret));
739

Moritz Grimm's avatar
Moritz Grimm committed
740
741
	log_set_verbosity(cfg_get_program_verbosity());

742
743
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
744
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
745
	}
746

747
748
	main_stream = stream_create(CFG_DEFAULT);
	if (0 > stream_configure(main_stream))
749
		return (ez_shutdown(1));
750
751
	cfg_server = stream_get_cfg_server(main_stream);
	cfg_stream = stream_get_cfg_stream(main_stream);
752
	cfg_intake = stream_get_cfg_intake(main_stream);
oddsock's avatar
oddsock committed
753

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

778
	if (0 > util_write_pid_file(cfg_get_program_pid_file()))
779
780
		log_syserr(WARNING, errno, cfg_get_program_pid_file());

781
	if (0 > stream_connect(main_stream)) {
782
783
784
785
		log_error("initial server connection failed");
		return (ez_shutdown(1));
	}
	log_notice("connected: %s://%s:%u%s",
786
787
788
789
	    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));