ezstream.c 20.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        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
25
26
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif
27

oddsock's avatar
oddsock committed
28
#include <shout/shout.h>
29

30
#include "cfg.h"
31
#include "cmdline.h"
32
#include "log.h"
33
#include "metadata.h"
34
#include "playlist.h"
35
#include "stream.h"
36
#include "util.h"
37
#include "xalloc.h"
38

39
40
41
42
#define STREAM_DONE	0
#define STREAM_CONT	1
#define STREAM_SKIP	2
#define STREAM_SERVERR	3
43
#define STREAM_UPDMDATA 4
44

45
46
47
playlist_t		 playlist;
int			 playlistMode;
unsigned int		 resource_errors;
48

49
#ifdef HAVE_SIGNALS
50
51
52
const int		 ezstream_signals[] = {
	SIGTERM, SIGINT, SIGHUP, SIGUSR1, SIGUSR2
};
53

54
55
56
57
58
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;
59
#else
60
61
62
63
64
int			 rereadPlaylist;
int			 rereadPlaylist_notify;
int			 skipTrack;
int			 queryMetadata;
int			 quit;
65
#endif /* HAVE_SIGNALS */
oddsock's avatar
oddsock committed
66
67

typedef struct tag_ID3Tag {
68
69
70
71
72
73
74
	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
75
76
} ID3Tag;

77
78
79
char *		buildReencodeCommand(const char *, const char *, metadata_t);
metadata_t	getMetadata(const char *);
FILE *		openResource(stream_t, const char *, int *, metadata_t *,
80
			     int *, long *);
81
int		reconnectServer(shout_t *, int);
82
const char *	getTimeString(long);
83
int		sendStream(stream_t, FILE *, const char *, int, const char *,
84
			   struct timespec *);
85
86
int		streamFile(stream_t, const char *);
int		streamPlaylist(stream_t);
87
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
88

89
#ifdef HAVE_SIGNALS
90
91
92
93
94
void		sig_handler(int);

# ifndef SIG_IGN
#  define SIG_IGN	 (void (*)(int))1
# endif /* !SIG_IGN */
95

96
97
98
99
void
sig_handler(int sig)
{
	switch (sig) {
100
101
102
103
	case SIGTERM:
	case SIGINT:
		quit = 1;
		break;
104
105
106
107
108
109
110
	case SIGHUP:
		rereadPlaylist = 1;
		rereadPlaylist_notify = 1;
		break;
	case SIGUSR1:
		skipTrack = 1;
		break;
111
112
113
	case SIGUSR2:
		queryMetadata = 1;
		break;
114
115
116
117
	default:
		break;
	}
}
118
#endif /* HAVE_SIGNALS */
119

120
char *
121
buildReencodeCommand(const char *extension, const char *fileName,
122
    metadata_t mdata)
123
{
124
125
126
127
128
129
130
131
132
133
	cfg_decoder_t	 decoder;
	cfg_encoder_t	 encoder;
	char		*dec_str, *enc_str;
	char		*commandString;
	size_t		 commandStringLen;
	char		*localTitle, *localArtist, *localMetaString;

	decoder = cfg_decoder_find(extension);
	if (!decoder) {
		log_error("cannot decode: %s: unsupported file extension %s",
134
		    fileName, extension);
135
		return (NULL);
136
	}
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
	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);
	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,
153
		    localArtist);
154
155
		xfree(dec_str);
		dec_str = tmpStr;
156
	}
157
158
	if (strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
		char *tmpStr = replaceString(dec_str, PLACEHOLDER_TITLE,
159
		    localTitle);
160
161
		xfree(dec_str);
		dec_str = tmpStr;
162
	}
163
164
165
166
167
168
169
170
171
172
	/*
	 * if meta
	 *   if (prog && format)
	 *      metatoformat
	 *   else
	 *     if (!prog && title)
	 *       emptymeta
	 *     else
	 *       replacemeta
	 */
173
174
175
	if (strstr(dec_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
176
			char *mdataString = stream_get_metadata_str(cfg_get_metadata_format_str(),
177
178
179
180
			    mdata);
			char *tmpStr = replaceString(dec_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(dec_str);
181
			xfree(mdataString);
182
			dec_str = tmpStr;
183
		} else {
184
185
186
187
188
189
			if (!cfg_get_metadata_program() &&
			    strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, "");
				xfree(dec_str);
				dec_str = tmpStr;
190
			} else {
191
192
193
194
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(dec_str);
				dec_str = tmpStr;
195
196
197
			}
		}
	}
198

199
200
201
	if (!cfg_encoder_get_program(encoder))
		return (dec_str);

202
203
204
205
	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,
206
		    localTitle);
207
208
		xfree(enc_str);
		enc_str = tmpStr;
209
	}
210
211
212
	if (strstr(enc_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
213
			char *mdataString = stream_get_metadata_str(cfg_get_metadata_format_str(),
214
215
216
217
			    mdata);
			char *tmpStr = replaceString(enc_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(enc_str);
218
			xfree(mdataString);
219
			enc_str = tmpStr;
220
		} else {
221
222
223
224
225
226
			if (!cfg_get_metadata_program() &&
			    strstr(enc_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(enc_str,
				    PLACEHOLDER_METADATA, "");
				xfree(enc_str);
				enc_str = tmpStr;
227
			} else {
228
229
230
231
				char *tmpStr = replaceString(enc_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(enc_str);
				enc_str = tmpStr;
232
233
234
			}
		}
	}
235

236
237
	commandStringLen = strlen(dec_str) + strlen(" | ") +
	    strlen(enc_str) + 1;
238
	commandString = xcalloc(commandStringLen, sizeof(char));
239
240
	snprintf(commandString, commandStringLen, "%s | %s", dec_str,
	    enc_str);
241

242
243
244
	xfree(localTitle);
	xfree(localArtist);
	xfree(localMetaString);
245
246
	xfree(dec_str);
	xfree(enc_str);
247
248

	return (commandString);
249
}
oddsock's avatar
oddsock committed
250

251
metadata_t
252
getMetadata(const char *fileName)
moritz's avatar
moritz committed
253
{
254
	metadata_t	mdata;
255

256
257
258
	if (cfg_get_metadata_program()) {
		if (NULL == (mdata = metadata_program(fileName,
		    cfg_get_metadata_normalize_strings())))
259
260
			return (NULL);

261
		if (!metadata_program_update(mdata, METADATA_ALL)) {
262
			metadata_free(&mdata);
263
			return (NULL);
264
265
		}
	} else {
266
267
		if (NULL == (mdata = metadata_file(fileName,
		    cfg_get_metadata_normalize_strings())))
268
			return (NULL);
moritz's avatar
moritz committed
269

270
271
		if (!metadata_file_update(mdata)) {
			metadata_free(&mdata);
272
			return (NULL);
273
		}
274
	}
275

276
277
278
	return (mdata);
}

279
FILE *
280
281
openResource(stream_t stream, const char *fileName, int *popenFlag,
	     metadata_t *mdata_p, int *isStdin, long *songLen)
282
{
283
284
285
286
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
287
	metadata_t	 mdata;
oddsock's avatar
oddsock committed
288

289
290
	if (mdata_p != NULL)
		*mdata_p = NULL;
291
292
	if (songLen != NULL)
		*songLen = 0;
293

294
	if (strcmp(fileName, "stdin") == 0) {
295
296
		if (cfg_get_metadata_program()) {
			if ((mdata = getMetadata(cfg_get_metadata_program())) == NULL)
297
				return (NULL);
298
			if (0 > stream_set_metadata(stream, mdata, NULL)) {
299
300
301
				metadata_free(&mdata);
				return (NULL);
			}
302
303
304
305
			if (mdata_p != NULL)
				*mdata_p = mdata;
			else
				metadata_free(&mdata);
306
		}
307

308
309
		if (isStdin != NULL)
			*isStdin = 1;
310
		filep = stdin;
311
		return (filep);
oddsock's avatar
oddsock committed
312
	}
313

314
315
316
317
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
318
319
320
321
322
323
324
	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) {
325
		log_error("%s: cannot determine file type", fileName);
326
327
328
		return (filep);
	}

329
330
	if (cfg_get_metadata_program()) {
		if ((mdata = getMetadata(cfg_get_metadata_program())) == NULL)
331
332
333
334
335
			return (NULL);
	} else {
		if ((mdata = getMetadata(fileName)) == NULL)
			return (NULL);
	}
336
337
	if (songLen != NULL)
		*songLen = metadata_get_length(mdata);
338
339

	*popenFlag = 0;
340
	if (cfg_get_stream_encoder()) {
341
		int	stderr_fd = -1;
342

343
344
		pCommandString = buildReencodeCommand(extension, fileName,
		    mdata);
345
346
347
348
		if (mdata_p != NULL)
			*mdata_p = mdata;
		else
			metadata_free(&mdata);
349
		log_info("running command: %s", pCommandString);
350

351
		if (cfg_get_program_quiet_stderr()) {
352
353
			int fd;

354
			stderr_fd = dup(fileno(stderr));
355
			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
356
357
				log_alert("%s: %s", _PATH_DEVNULL,
				    strerror(errno));
358
				exit(1);
359
360
			}

361
362
363
364
365
366
367
368
369
370
			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)
371
372
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
373
			else
374
375
				log_error("execution error: %s",
				    pCommandString);
376
377
378
379
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
380

381
		if (cfg_get_program_quiet_stderr())
382
			dup2(stderr_fd, fileno(stderr));
383
384
385

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

387
		return (filep);
388
	}
389

390
391
392
393
	if (mdata_p != NULL)
		*mdata_p = mdata;
	else
		metadata_free(&mdata);
394

395
396
397
398
	if ((filep = fopen(fileName, "rb")) == NULL) {
		log_error("%s: %s", fileName, strerror(errno));
		return (NULL);
	}
399
400

	return (filep);
401
402
}

403
404
405
406
407
408
int
reconnectServer(shout_t *shout, int closeConn)
{
	unsigned int	i;
	int		close_conn = closeConn;

409
	log_warning("%s: connection lost", cfg_get_server_hostname());
410
411
412

	i = 0;
	while (++i) {
413
		if (cfg_get_server_reconnect_attempts() > 0)
414
			log_notice("reconnect: %s: attempt #%u/%u ...",
415
416
			    cfg_get_server_hostname(), i,
			    cfg_get_server_reconnect_attempts());
417
		else
418
			log_notice("reconnect: %s: attempt #%u ...",
419
			    cfg_get_server_hostname(), i);
420
421
422
423
424
425

		if (close_conn == 0)
			close_conn = 1;
		else
			shout_close(shout);
		if (shout_open(shout) == SHOUTERR_SUCCESS) {
426
			log_notice("reconnect: %s: success",
427
			    cfg_get_server_hostname());
428
429
430
			return (1);
		}

431
		log_warning("reconnect failed: %s: %s",
432
		    cfg_get_server_hostname(), shout_get_error(shout));
433

434
435
		if (cfg_get_server_reconnect_attempts() > 0 &&
		    i >= cfg_get_server_reconnect_attempts())
436
437
			break;

438
439
440
441
		if (quit)
			return (0);
		else
			sleep(5);
442
443
	};

444
	log_warning("reconnect failed: giving up");
445
446
447
	return (0);
}

448
const char *
449
getTimeString(long seconds)
450
451
{
	static char	str[20];
452
	long		secs, mins, hours;
453
454
455
456
457
458
459
460
461
462

	if (seconds < 0)
		return (NULL);

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

463
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
464
465
466
	return ((const char *)str);
}

467
int
468
sendStream(stream_t stream, FILE *filepstream, const char *fileName,
469
	   int isStdin, const char *songLenStr, struct timespec *tv)
470
{
471
472
473
474
475
476
477
	unsigned char	  buff[4096];
	size_t		  bytes_read, total, oldTotal;
	int		  ret;
	double		  kbps = -1.0;
	struct timespec	  timeStamp, *startTime = tv;
	struct timespec	  callTime, currentTime;
	shout_t 	 *shout = stream_get_shout(stream);
478

479
	clock_gettime(CLOCK_MONOTONIC, &callTime);
480

481
	timeStamp.tv_sec = startTime->tv_sec;
482
	timeStamp.tv_nsec = startTime->tv_nsec;
483
484

	total = oldTotal = 0;
485
	ret = STREAM_DONE;
486
	while ((bytes_read = fread(buff, 1UL, sizeof(buff), filepstream)) > 0) {
487
488
489
490
491
492
		if (shout_get_connected(shout) != SHOUTERR_CONNECTED &&
		    reconnectServer(shout, 0) == 0) {
			ret = STREAM_SERVERR;
			break;
		}

493
494
		shout_sync(shout);

495
		if (shout_send(shout, buff, bytes_read) != SHOUTERR_SUCCESS) {
496
			log_error("shout_send: %s", shout_get_error(shout));
497
498
499
500
501
502
503
504
			if (reconnectServer(shout, 1))
				break;
			else {
				ret = STREAM_SERVERR;
				break;
			}
		}

505
506
		if (quit)
			break;
507
508
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
509
			if (CFG_MEDIA_PLAYLIST == cfg_get_media_type())
510
				log_notice("HUP signal received: playlist re-read scheduled");
511
512
513
		}
		if (skipTrack) {
			skipTrack = 0;
514
			ret = STREAM_SKIP;
515
516
			break;
		}
517

518
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
519
520

		if (queryMetadata ||
521
		    (0 <= cfg_get_metadata_refresh_interval() &&
522
523
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
524
			queryMetadata = 0;
525
			if (cfg_get_metadata_program()) {
526
				ret = STREAM_UPDMDATA;
527
				break;
oddsock's avatar
oddsock committed
528
			}
529
530
		}

531
		total += bytes_read;
532
		if (cfg_get_program_rtstatus_output()) {
533
			double	oldTime, newTime;
534

535
			if (!isStdin && playlistMode) {
536
537
				if (CFG_MEDIA_PROGRAM == cfg_get_media_type()) {
					char *tmp = xstrdup(cfg_get_media_filename());
538
					printf("  [%s]", basename(tmp));
539
540
541
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
542
543
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
544
			}
545
546

			oldTime = (double)timeStamp.tv_sec
547
			    + (double)timeStamp.tv_nsec / 1000000000.0;
548
			newTime = (double)currentTime.tv_sec
549
			    + (double)currentTime.tv_nsec / 1000000000.0;
550
551
			if (songLenStr == NULL)
				printf("  [ %s]",
552
553
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec));
554
555
			else
				printf("  [ %s/%s]",
556
557
558
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec),
				    songLenStr);
559
			if (newTime - oldTime >= 1.0) {
560
				kbps = (((double)(total - oldTotal)
561
				    / (newTime - oldTime)) * 8.0) / 1000.0;
562
				timeStamp.tv_sec = currentTime.tv_sec;
563
				timeStamp.tv_nsec = currentTime.tv_nsec;
564
565
566
567
568
569
570
571
572
573
				oldTotal = total;
			}
			if (kbps < 0)
				printf("                 ");
			else
				printf("  [%8.2f kbps]", kbps);

			printf("  \r");
			fflush(stdout);
		}
oddsock's avatar
oddsock committed
574
	}
575
576
577
	if (ferror(filepstream)) {
		if (errno == EINTR) {
			clearerr(filepstream);
578
			ret = STREAM_CONT;
579
		} else if (errno == EBADF && isStdin)
580
			log_notice("no (more) data available on standard input");
581
		else
582
583
			log_error("sendStream: %s: %s", fileName,
			    strerror(errno));
584
585
	}

586
	return (ret);
587
588
589
}

int
590
streamFile(stream_t stream, const char *fileName)
591
592
593
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
594
	char		*songLenStr = NULL;
595
	int		 isStdin = 0;
596
597
	int		 ret, retval = 0;
	long		 songLen;
598
	metadata_t	 mdata;
599
	struct timespec	 startTime;
600

601
	if ((filepstream = openResource(stream, fileName, &popenFlag, &mdata, &isStdin, &songLen))
602
603
	    == NULL) {
		if (++resource_errors > 100) {
604
			log_error("too many errors; giving up");
605
606
			return (0);
		}
607
608
		/* Continue with next resource on failure: */
		return (1);
609
610
	}
	resource_errors = 0;
611

612
	if (mdata != NULL) {
613
		char	*tmp, *metaData;
614

615
		tmp = metadata_assemble_string(mdata);
616
617
		if ((metaData = UTF8toCHAR(tmp, ICONV_REPLACE)) == NULL)
			metaData = xstrdup("(unknown title)");
618
		xfree(tmp);
619
		log_notice("streaming: %s (%s)", metaData, fileName);
620
		xfree(metaData);
621
622

		/* MP3 streams are special, so set the metadata explicitly: */
623
		if (CFG_STREAM_MP3 == cfg_get_stream_format())
624
			stream_set_metadata(stream, mdata, NULL);
625
626

		metadata_free(&mdata);
627
	} else if (isStdin)
628
		log_notice("streaming: standard input");
629

moritz's avatar
moritz committed
630
	if (songLen > 0)
631
		songLenStr = xstrdup(getTimeString(songLen));
632
	clock_gettime(CLOCK_MONOTONIC, &startTime);
633
	do {
634
		ret = sendStream(stream, filepstream, fileName, isStdin,
635
		    songLenStr, &startTime);
636
637
		if (quit)
			break;
638
		if (ret != STREAM_DONE) {
639
640
			if ((skipTrack && rereadPlaylist) ||
			    (skipTrack && queryMetadata)) {
641
				skipTrack = 0;
642
643
644
645
646
				ret = STREAM_CONT;
			}
			if (queryMetadata && rereadPlaylist) {
				queryMetadata = 0;
				ret = STREAM_CONT;
647
			}
648
			if (ret == STREAM_SKIP || skipTrack) {
649
				skipTrack = 0;
650
651
				if (!isStdin)
					log_notice("USR1 signal received: skipping current track");
652
				retval = 1;
653
654
				ret = STREAM_DONE;
			}
655
656
			if (ret == STREAM_UPDMDATA || queryMetadata) {
				queryMetadata = 0;
657
				if (cfg_get_metadata_no_updates())
658
					continue;
659
				if (cfg_get_metadata_program()) {
660
					char		*mdataStr = NULL;
661
					metadata_t	 prog_mdata;
662

663
					log_info("running metadata program: %s",
664
665
					    cfg_get_metadata_program());
					if ((prog_mdata = getMetadata(cfg_get_metadata_program())) == NULL) {
666
667
668
669
						retval = 0;
						ret = STREAM_DONE;
						continue;
					}
670
					if (0> stream_set_metadata(stream, prog_mdata, &mdataStr)) {
671
672
						retval = 0;
						ret = STREAM_DONE;
673
						continue;
674
					}
675
					metadata_free(&prog_mdata);
676
					log_info("new metadata: %s", mdataStr);
677
678
679
					xfree(mdataStr);
				}
			}
680
681
682
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
683
684
685
			}
		} else
			retval = 1;
686
	} while (ret != STREAM_DONE);
687
688

	if (popenFlag)
oddsock's avatar
oddsock committed
689
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
690
	else if (!isStdin)
oddsock's avatar
oddsock committed
691
		fclose(filepstream);
692

693
694
695
	if (songLenStr != NULL)
		xfree(songLenStr);

696
	return (retval);
oddsock's avatar
oddsock committed
697
}
698

699
int
700
streamPlaylist(stream_t stream)
701
702
{
	const char	*song;
moritz's avatar
moritz committed
703
	char		 lastSong[PATH_MAX];
704
705

	if (playlist == NULL) {
706
707
		switch (cfg_get_media_type()) {
		case CFG_MEDIA_PROGRAM:
708
			if ((playlist = playlist_program(cfg_get_media_filename())) == NULL)
709
				return (0);
710
711
712
713
714
715
			break;
		case CFG_MEDIA_STDIN:
			if ((playlist = playlist_read(NULL)) == NULL)
				return (0);
			break;
		default:
716
			if ((playlist = playlist_read(cfg_get_media_filename())) == NULL)
717
				return (0);
718
			if (playlist_get_num_items(playlist) == 0)
719
				log_warning("%s: playlist empty",
720
				    cfg_get_media_filename());
721
			break;
722
		}
723
	} else {
724
725
726
727
728
		/*
		 * XXX: This preserves traditional behavior, however,
		 *      rereading the playlist after each walkthrough seems a
		 *      bit more logical.
		 */
729
		playlist_rewind(playlist);
730
	}
731

732
733
	if (CFG_MEDIA_PROGRAM != cfg_get_media_type() &&
	    cfg_get_media_shuffle())
734
735
736
737
		playlist_shuffle(playlist);

	while ((song = playlist_get_next(playlist)) != NULL) {
		strlcpy(lastSong, song, sizeof(lastSong));
738
		if (!streamFile(stream, song))
739
			return (0);
740
741
		if (quit)
			break;
742
743
		if (rereadPlaylist) {
			rereadPlaylist = rereadPlaylist_notify = 0;
744
			if (CFG_MEDIA_PROGRAM == cfg_get_media_type())
745
				continue;
746
			log_notice("rereading playlist");
747
748
			if (!playlist_reread(&playlist))
				return (0);
749
			if (cfg_get_media_shuffle())
750
751
752
753
				playlist_shuffle(playlist);
			else {
				playlist_goto_entry(playlist, lastSong);
				playlist_skip_next(playlist);
oddsock's avatar
oddsock committed
754
			}
755
			continue;
756
		}
oddsock's avatar
oddsock committed
757
	}
758

759
	return (1);
oddsock's avatar
oddsock committed
760
761
}

762
int
763
ez_shutdown(int exitval)
764
{
765
	stream_exit();
766
767
768
	playlist_exit();
	cfg_encoder_exit();
	cfg_decoder_exit();
Moritz Grimm's avatar
Moritz Grimm committed
769
	log_exit();
770
	cfg_exit();
771
772
773
774

	return (exitval);
}

775
int
776
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
777
{
Moritz Grimm's avatar
Moritz Grimm committed
778
	int		 ret;
779
	const char	*errstr;
780
	stream_t	 stream;
781
782
783
	shout_t 	*shout;
	extern char	*optarg;
	extern int	 optind;
784
785
#ifdef HAVE_SIGNALS
	struct sigaction act;
moritz's avatar
moritz committed
786
	unsigned int	 i;
787
#endif
788

Moritz Grimm's avatar
Moritz Grimm committed
789
	ret = 1;
790
791
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
792
793
794
795
	    0 > log_init() ||
	    0 > cfg_decoder_init() ||
	    0 > cfg_encoder_init() ||
	    0 > playlist_init() ||
796
797
	    0 > cfg_reload() ||
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
798
		return (ez_shutdown(ret));
799

800
801
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
802
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
803
	}
804

805
806
	stream = stream_get(STREAM_DEFAULT);
	if (0 > stream_setup(stream))
807
		return (ez_shutdown(1));
808
	shout = stream_get_shout(stream);
oddsock's avatar
oddsock committed
809

810
#ifdef HAVE_SIGNALS
811
812
813
814
815
	memset(&act, 0, sizeof(act));
	act.sa_handler = sig_handler;
# ifdef SA_RESTART
	act.sa_flags = SA_RESTART;
# endif
moritz's avatar
moritz committed
816
817
	for (i = 0; i < sizeof(ezstream_signals) / sizeof(int); i++) {
		if (sigaction(ezstream_signals[i], &act, NULL) == -1) {
818
			log_syserr(ERROR, errno, "sigaction");
819
			return (ez_shutdown(1));
moritz's avatar
moritz committed
820
821
		}
	}
822
823
824
825
826
827
	/*
	 * Ignore SIGPIPE, which has been seen to give a long-running ezstream
	 * process trouble. EOF and/or EPIPE are also easier to handle.
	 */
	act.sa_handler = SIG_IGN;
	if (sigaction(SIGPIPE, &act, NULL) == -1) {
828
		log_syserr(ERROR, errno, "sigaction");
829
830
		return (ez_shutdown(1));
	}
831
832
833
#endif /* HAVE_SIGNALS */

	if (shout_open(shout) == SHOUTERR_SUCCESS) {
Moritz Grimm's avatar
Moritz Grimm committed
834
		int	cont;
835

836
837
838
		log_notice("connected: %s://%s:%u%s",
		    cfg_get_server_protocol_str(), cfg_get_server_hostname(),
		    cfg_get_server_port(), cfg_get_stream_mountpoint());
839

840
841
842
843
844
		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)))
845
846
847
848
849
			playlistMode = 1;
		else
			playlistMode = 0;

		do {
850
			if (playlistMode) {
851
				cont = streamPlaylist(stream);
852
			} else {
853
				cont = streamFile(stream,
854
				    cfg_get_media_filename());
855
			}
856
857
			if (quit)
				break;