ezstream.c 19.8 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

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

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

43
44
45
playlist_t		 playlist;
int			 playlistMode;
unsigned int		 resource_errors;
46

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

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

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

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

87
#ifdef HAVE_SIGNALS
88
89
90
91
92
void		sig_handler(int);

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

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

118
char *
119
buildReencodeCommand(const char *extension, const char *fileName,
120
    metadata_t mdata)
121
{
122
123
124
125
126
127
128
129
130
131
	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",
132
		    fileName, extension);
133
		return (NULL);
134
	}
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
	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,
151
		    localArtist);
152
153
		xfree(dec_str);
		dec_str = tmpStr;
154
	}
155
156
	if (strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
		char *tmpStr = replaceString(dec_str, PLACEHOLDER_TITLE,
157
		    localTitle);
158
159
		xfree(dec_str);
		dec_str = tmpStr;
160
	}
161
162
163
164
165
166
167
168
169
170
	/*
	 * if meta
	 *   if (prog && format)
	 *      metatoformat
	 *   else
	 *     if (!prog && title)
	 *       emptymeta
	 *     else
	 *       replacemeta
	 */
171
172
173
	if (strstr(dec_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
174
175
			char *mdataString = metadata_format_string(mdata,
			    cfg_get_metadata_format_str());
176
177
178
			char *tmpStr = replaceString(dec_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(dec_str);
179
			xfree(mdataString);
180
			dec_str = tmpStr;
181
		} else {
182
183
184
185
186
187
			if (!cfg_get_metadata_program() &&
			    strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, "");
				xfree(dec_str);
				dec_str = tmpStr;
188
			} else {
189
190
191
192
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(dec_str);
				dec_str = tmpStr;
193
194
195
			}
		}
	}
196

197
198
199
	if (!cfg_encoder_get_program(encoder))
		return (dec_str);

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

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

240
241
242
	xfree(localTitle);
	xfree(localArtist);
	xfree(localMetaString);
243
244
	xfree(dec_str);
	xfree(enc_str);
245
246

	return (commandString);
247
}
oddsock's avatar
oddsock committed
248

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

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

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

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

274
275
276
	return (mdata);
}

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

287
288
	if (mdata_p != NULL)
		*mdata_p = NULL;
289
290
	if (songLen != NULL)
		*songLen = 0;
291

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

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

312
313
314
315
	if (isStdin != NULL)
		*isStdin = 0;

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

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

	*popenFlag = 0;
338
	if (cfg_get_stream_encoder()) {
339
		int	stderr_fd = -1;
340

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

349
		if (cfg_get_program_quiet_stderr()) {
350
351
			int fd;

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

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

379
		if (cfg_get_program_quiet_stderr())
380
			dup2(stderr_fd, fileno(stderr));
381
382
383

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

385
		return (filep);
386
	}
387

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

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

	return (filep);
399
400
}

401
int
402
reconnect(stream_t stream)
403
404
405
406
407
{
	unsigned int	i;

	i = 0;
	while (++i) {
408
		if (cfg_get_server_reconnect_attempts() > 0)
409
			log_notice("reconnect: %s: attempt #%u/%u ...",
410
411
			    cfg_get_server_hostname(), i,
			    cfg_get_server_reconnect_attempts());
412
		else
413
			log_notice("reconnect: %s: attempt #%u ...",
414
			    cfg_get_server_hostname(), i);
415

416
417
		stream_disconnect(stream);
		if (0 == stream_connect(stream)) {
418
			log_notice("reconnect: %s: success",
419
			    cfg_get_server_hostname());
420
			return (0);
421
422
		}

423
424
		if (cfg_get_server_reconnect_attempts() > 0 &&
		    i >= cfg_get_server_reconnect_attempts())
425
426
			break;

427
		if (quit)
428
			return (-1);
429
430
		else
			sleep(5);
431
432
	};

433
	log_warning("reconnect failed: giving up");
434
435

	return (-1);
436
437
}

438
const char *
439
getTimeString(long seconds)
440
441
{
	static char	str[20];
442
	long		secs, mins, hours;
443
444
445
446
447
448
449
450
451
452

	if (seconds < 0)
		return (NULL);

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

453
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
454
455
456
	return ((const char *)str);
}

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

468
	clock_gettime(CLOCK_MONOTONIC, &callTime);
469

470
	timeStamp.tv_sec = startTime->tv_sec;
471
	timeStamp.tv_nsec = startTime->tv_nsec;
472
473

	total = oldTotal = 0;
474
	ret = STREAM_DONE;
475
476
477
478
479
480
481
482
	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;
			}
483
484
		}

485
		stream_sync(stream);
486

487
488
		if (0 > stream_send(stream, buff, bytes_read)) {
			if (0 > reconnect(stream))
489
				ret = STREAM_SERVERR;
490
			break;
491
492
		}

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

506
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
507
508

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

519
		total += bytes_read;
520
		if (cfg_get_program_rtstatus_output()) {
521
			double	oldTime, newTime;
522

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

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

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

574
	return (ret);
575
576
577
}

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

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

600
	if (mdata != NULL) {
601
		char	*tmp, *metaData;
602

603
		tmp = metadata_assemble_string(mdata);
604
605
		if ((metaData = UTF8toCHAR(tmp, ICONV_REPLACE)) == NULL)
			metaData = xstrdup("(unknown title)");
606
		xfree(tmp);
607
		log_notice("streaming: %s (%s)", metaData, fileName);
608
		xfree(metaData);
609
610

		/* MP3 streams are special, so set the metadata explicitly: */
611
		if (CFG_STREAM_MP3 == cfg_get_stream_format())
612
			stream_set_metadata(stream, mdata, NULL);
613
614

		metadata_free(&mdata);
615
	} else if (isStdin)
616
		log_notice("streaming: standard input");
617

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

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

	if (popenFlag)
oddsock's avatar
oddsock committed
677
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
678
	else if (!isStdin)
oddsock's avatar
oddsock committed
679
		fclose(filepstream);
680

681
682
683
	if (songLenStr != NULL)
		xfree(songLenStr);

684
	return (retval);
oddsock's avatar
oddsock committed
685
}
686

687
int
688
streamPlaylist(stream_t stream)
689
690
{
	const char	*song;
moritz's avatar
moritz committed
691
	char		 lastSong[PATH_MAX];
692
693

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

720
721
	if (CFG_MEDIA_PROGRAM != cfg_get_media_type() &&
	    cfg_get_media_shuffle())
722
723
724
725
		playlist_shuffle(playlist);

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

747
	return (1);
oddsock's avatar
oddsock committed
748
749
}

750
int
751
ez_shutdown(int exitval)
752
{
753
	stream_exit();
754
755
756
	playlist_exit();
	cfg_encoder_exit();
	cfg_decoder_exit();
Moritz Grimm's avatar
Moritz Grimm committed
757
	log_exit();
758
	cfg_exit();
759
760
761
762

	return (exitval);
}

763
int
764
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
765
{
766
	int		 ret, cont;
767
	const char	*errstr;
768
	stream_t	 stream;
769
770
	extern char	*optarg;
	extern int	 optind;
771
772
#ifdef HAVE_SIGNALS
	struct sigaction act;
moritz's avatar
moritz committed
773
	unsigned int	 i;
774
#endif
775

Moritz Grimm's avatar
Moritz Grimm committed
776
	ret = 1;
777
778
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
779
780
781
782
	    0 > log_init() ||
	    0 > cfg_decoder_init() ||
	    0 > cfg_encoder_init() ||
	    0 > playlist_init() ||
783
784
	    0 > cfg_reload() ||
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
785
		return (ez_shutdown(ret));
786

787
788
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
789
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
790
	}
791

792
793
	stream = stream_get(STREAM_DEFAULT);
	if (0 > stream_setup(stream))
794
		return (ez_shutdown(1));
oddsock's avatar
oddsock committed
795

796
#ifdef HAVE_SIGNALS
797
798
799
800
801
	memset(&act, 0, sizeof(act));
	act.sa_handler = sig_handler;
# ifdef SA_RESTART
	act.sa_flags = SA_RESTART;
# endif
moritz's avatar
moritz committed
802
803
	for (i = 0; i < sizeof(ezstream_signals) / sizeof(int); i++) {
		if (sigaction(ezstream_signals[i], &act, NULL) == -1) {
804
			log_syserr(ERROR, errno, "sigaction");
805
			return (ez_shutdown(1));
moritz's avatar
moritz committed
806
807
		}
	}
808
809
810
811
812
813
	/*
	 * 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) {
814
		log_syserr(ERROR, errno, "sigaction");
815
816
		return (ez_shutdown(1));
	}
817
818
#endif /* HAVE_SIGNALS */

819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
	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;
835

836
837
838
839
840
841
842
843
844
845
846
847
	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);
848

849
	stream_disconnect(stream);
850

851
	if (quit) {
852
853
		if (cfg_get_program_quiet_stderr() &&
		    cfg_get_program_verbosity())
854
855
856
			printf("\r");
		log_notice("INT or TERM signal received");
	}
857

858
	log_info("exiting");
859