ezstream.c 18.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
42
43
playlist_t		 playlist;
int			 playlistMode;
unsigned int		 resource_errors;
44

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

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

55
void		sig_handler(int);
56
57
58
char *		_build_reencode_cmd(const char *, const char *, mdata_t);
mdata_t 	getMetadata(const char *);
FILE *		openResource(stream_t, const char *, int *, mdata_t *,
59
			     int *, long *);
60
int		reconnect(stream_t);
61
const char *	getTimeString(long);
62
int		sendStream(stream_t, FILE *, const char *, int, const char *,
63
			   struct timespec *);
64
65
int		streamFile(stream_t, const char *);
int		streamPlaylist(stream_t);
66
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
67

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

91
char *
92
93
_build_reencode_cmd(const char *extension, const char *filename,
    mdata_t md)
94
{
Moritz Grimm's avatar
Moritz Grimm committed
95
96
	cfg_decoder_t		 decoder;
	cfg_encoder_t		 encoder;
97
	char			*artist, *album, *title, *songinfo;
Moritz Grimm's avatar
Moritz Grimm committed
98
99
100
101
102
103
104
	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;
105
106
107
108

	decoder = cfg_decoder_find(extension);
	if (!decoder) {
		log_error("cannot decode: %s: unsupported file extension %s",
109
		    filename, extension);
110
		return (NULL);
111
	}
112
113
114
115
116
117
118
	encoder = cfg_encoder_get(cfg_get_stream_encoder());
	if (!encoder) {
		log_error("cannot encode: %s: unknown encoder",
		    cfg_get_stream_encoder());
		return (NULL);
	}

119
120
121
122
	artist = util_shellquote(util_utf82char(mdata_get_artist(md)));
	album = util_shellquote(util_utf82char(mdata_get_album(md)));
	title = util_shellquote(util_utf82char(mdata_get_title(md)));
	songinfo = util_shellquote(util_utf82char(mdata_get_songinfo(md)));
Moritz Grimm's avatar
Moritz Grimm committed
123

124
	filename_quoted = util_shellquote(filename);
Moritz Grimm's avatar
Moritz Grimm committed
125

126
	/*
Moritz Grimm's avatar
Moritz Grimm committed
127
128
129
130
131
	 * if (prog && format)
	 *    metatoformat
	 * else
	 *   if (!prog && title)
	 *     emptymeta
132
	 *   else
Moritz Grimm's avatar
Moritz Grimm committed
133
	 *     replacemeta
134
	 */
Moritz Grimm's avatar
Moritz Grimm committed
135
136
	if (cfg_get_metadata_program() &&
	    cfg_get_metadata_format_str()) {
137
138
		char	 buf[BUFSIZ];
		char	*unquoted;
Moritz Grimm's avatar
Moritz Grimm committed
139

140
		mdata_strformat(md, buf, sizeof(buf),
Moritz Grimm's avatar
Moritz Grimm committed
141
		    cfg_get_metadata_format_str());
142
		unquoted = util_utf82char(buf);
Moritz Grimm's avatar
Moritz Grimm committed
143
144
145
146
147
148
149
		custom_songinfo = util_shellquote(unquoted);
		xfree(unquoted);
	} else {
		if (!cfg_get_metadata_program() &&
		    strstr(cfg_decoder_get_program(decoder),
			PLACEHOLDER_TITLE) != NULL) {
			custom_songinfo = xstrdup("");
150
		} else {
Moritz Grimm's avatar
Moritz Grimm committed
151
			custom_songinfo = xstrdup(songinfo);
152
153
		}
	}
Moritz Grimm's avatar
Moritz Grimm committed
154
	xfree(songinfo);
155

Moritz Grimm's avatar
Moritz Grimm committed
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
	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("");
175
	}
176

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

Moritz Grimm's avatar
Moritz Grimm committed
179
180
181
	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);
182
183
	xfree(dec_str);
	xfree(enc_str);
184

Moritz Grimm's avatar
Moritz Grimm committed
185
186
187
188
189
190
191
	xfree(artist);
	xfree(album);
	xfree(title);
	xfree(filename_quoted);
	xfree(custom_songinfo);

	return (cmd_str);
192
}
oddsock's avatar
oddsock committed
193

194
195
mdata_t
getMetadata(const char *filename)
moritz's avatar
moritz committed
196
{
197
	mdata_t md = mdata_create();
198

199
	if (cfg_get_metadata_program()) {
200
201
		if (0 > mdata_run_program(md, filename))
			mdata_destroy(&md);
202
	} else {
203
204
		if (0 > mdata_parse_file(md, filename))
			mdata_destroy(&md);
205
	}
206

207
	return (md);
208
209
}

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

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

225
	if ((isStdin && *isStdin) ||
226
	    strcasecmp(filename, "stdin") == 0) {
227
		if (cfg_get_metadata_program()) {
228
			if ((md = getMetadata(cfg_get_metadata_program())) == NULL)
229
				return (NULL);
230
231
			if (0 > stream_set_metadata(stream, md, NULL)) {
				mdata_destroy(&md);
232
233
				return (NULL);
			}
234
235
			if (md_p != NULL)
				*md_p = md;
236
			else
237
				mdata_destroy(&md);
238
		}
239

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

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

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

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

261
	if (cfg_get_metadata_program()) {
262
		if ((md = getMetadata(cfg_get_metadata_program())) == NULL)
263
264
			return (NULL);
	} else {
265
		if ((md = getMetadata(filename)) == NULL)
266
267
			return (NULL);
	}
268
	if (songLen != NULL)
269
		*songLen = mdata_get_length(md);
270
271

	*popenFlag = 0;
272
	if (cfg_get_stream_encoder()) {
273
		int	stderr_fd = -1;
274

275
276
277
278
		pCommandString = _build_reencode_cmd(extension, filename,
		    md);
		if (md_p != NULL)
			*md_p = md;
279
		else
280
			mdata_destroy(&md);
281
		log_info("running command: %s", pCommandString);
282

283
		if (cfg_get_program_quiet_stderr()) {
284
285
			int fd;

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

297
298
299
300
301
302
303
304
305
306
			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)
307
308
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
309
			else
310
311
				log_error("execution error: %s",
				    pCommandString);
312
313
314
315
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
316

317
		if (cfg_get_program_quiet_stderr())
318
			dup2(stderr_fd, fileno(stderr));
319
320
321

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

323
		return (filep);
324
	}
325

326
327
	if (md_p != NULL)
		*md_p = md;
328
	else
329
		mdata_destroy(&md);
330

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

	return (filep);
337
338
}

339
int
340
reconnect(stream_t stream)
341
342
343
344
345
{
	unsigned int	i;

	i = 0;
	while (++i) {
346
		if (cfg_get_server_reconnect_attempts() > 0)
347
			log_notice("reconnect: %s: attempt #%u/%u ...",
348
349
			    cfg_get_server_hostname(), i,
			    cfg_get_server_reconnect_attempts());
350
		else
351
			log_notice("reconnect: %s: attempt #%u ...",
352
			    cfg_get_server_hostname(), i);
353

354
355
		stream_disconnect(stream);
		if (0 == stream_connect(stream)) {
356
			log_notice("reconnect: %s: success",
357
			    cfg_get_server_hostname());
358
			return (0);
359
360
		}

361
362
		if (cfg_get_server_reconnect_attempts() > 0 &&
		    i >= cfg_get_server_reconnect_attempts())
363
364
			break;

365
		if (quit)
366
			return (-1);
367
368
		else
			sleep(5);
369
370
	};

371
	log_warning("reconnect failed: giving up");
372
373

	return (-1);
374
375
}

376
const char *
377
getTimeString(long seconds)
378
379
{
	static char	str[20];
380
	long		secs, mins, hours;
381
382
383
384
385
386
387
388
389
390

	if (seconds < 0)
		return (NULL);

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

391
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
392
393
394
	return ((const char *)str);
}

395
int
396
sendStream(stream_t stream, FILE *filepstream, const char *fileName,
397
	   int isStdin, const char *songLenStr, struct timespec *tv)
398
{
399
	char		  buff[4096];
400
401
402
403
404
	size_t		  bytes_read, total, oldTotal;
	int		  ret;
	double		  kbps = -1.0;
	struct timespec	  timeStamp, *startTime = tv;
	struct timespec	  callTime, currentTime;
405

406
	clock_gettime(CLOCK_MONOTONIC, &callTime);
407

408
	timeStamp.tv_sec = startTime->tv_sec;
409
	timeStamp.tv_nsec = startTime->tv_nsec;
410
411

	total = oldTotal = 0;
412
	ret = STREAM_DONE;
413
414
415
416
417
418
419
420
	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;
			}
421
422
		}

423
		stream_sync(stream);
424

425
426
		if (0 > stream_send(stream, buff, bytes_read)) {
			if (0 > reconnect(stream))
427
				ret = STREAM_SERVERR;
428
			break;
429
430
		}

431
432
		if (quit)
			break;
433
434
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
435
			if (CFG_MEDIA_PLAYLIST == cfg_get_media_type())
436
				log_notice("HUP signal received: playlist re-read scheduled");
437
438
439
		}
		if (skipTrack) {
			skipTrack = 0;
440
			ret = STREAM_SKIP;
441
442
			break;
		}
443

444
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
445
446

		if (queryMetadata ||
447
		    (0 <= cfg_get_metadata_refresh_interval() &&
448
449
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
450
			queryMetadata = 0;
451
			if (cfg_get_metadata_program()) {
452
				ret = STREAM_UPDMDATA;
453
				break;
oddsock's avatar
oddsock committed
454
			}
455
456
		}

457
		total += bytes_read;
458
		if (cfg_get_program_rtstatus_output()) {
459
			double	oldTime, newTime;
460

461
			if (!isStdin && playlistMode) {
462
463
				if (CFG_MEDIA_PROGRAM == cfg_get_media_type()) {
					char *tmp = xstrdup(cfg_get_media_filename());
464
					printf("  [%s]", basename(tmp));
465
466
467
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
468
469
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
470
			}
471
472

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

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

512
	return (ret);
513
514
515
}

int
516
streamFile(stream_t stream, const char *fileName)
517
518
519
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
520
	char		*songLenStr = NULL;
521
	int		 isStdin = cfg_get_media_type() == CFG_MEDIA_STDIN;
522
523
	int		 ret, retval = 0;
	long		 songLen;
524
	mdata_t 	 md = NULL;
525
	struct timespec	 startTime;
526

527
	if ((filepstream = openResource(stream, fileName, &popenFlag, &md, &isStdin, &songLen))
528
	    == NULL) {
529
		mdata_destroy(&md);
530
		if (++resource_errors > 100) {
531
			log_error("too many errors; giving up");
532
533
			return (0);
		}
534
535
		/* Continue with next resource on failure: */
		return (1);
536
537
	}
	resource_errors = 0;
538

539
540
541
	if (md != NULL) {
		const char	*tmp;
		char		*metaData;
542

543
544
545
		tmp = mdata_get_songinfo(md) ?
		    mdata_get_songinfo(md) : mdata_get_name(md);
		metaData = util_utf82char(tmp);
546
547
		log_notice("streaming: %s (%s)", metaData,
		    isStdin ? "stdin" : fileName);
548
		xfree(metaData);
549
550

		/* MP3 streams are special, so set the metadata explicitly: */
551
		if (CFG_STREAM_MP3 == cfg_get_stream_format())
552
			stream_set_metadata(stream, md, NULL);
553

554
		mdata_destroy(&md);
555
	} else if (isStdin)
556
		log_notice("streaming: standard input");
557

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

591
					log_info("running metadata program: %s",
592
					    cfg_get_metadata_program());
593
					if ((prog_md = getMetadata(cfg_get_metadata_program())) == NULL) {
594
595
596
597
						retval = 0;
						ret = STREAM_DONE;
						continue;
					}
598
					if (0 > stream_set_metadata(stream, prog_md, &mdataStr)) {
599
600
						retval = 0;
						ret = STREAM_DONE;
601
						mdata_destroy(&prog_md);
602
						continue;
603
					}
604
					mdata_destroy(&prog_md);
605
					log_info("new metadata: %s", mdataStr);
606
607
608
					xfree(mdataStr);
				}
			}
609
610
611
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
612
613
614
			}
		} else
			retval = 1;
615
	} while (ret != STREAM_DONE);
616
617

	if (popenFlag)
oddsock's avatar
oddsock committed
618
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
619
	else if (!isStdin)
oddsock's avatar
oddsock committed
620
		fclose(filepstream);
621

622
623
624
	if (songLenStr != NULL)
		xfree(songLenStr);

625
	return (retval);
oddsock's avatar
oddsock committed
626
}
627

628
int
629
streamPlaylist(stream_t stream)
630
631
{
	const char	*song;
moritz's avatar
moritz committed
632
	char		 lastSong[PATH_MAX];
633
634

	if (playlist == NULL) {
635
636
		switch (cfg_get_media_type()) {
		case CFG_MEDIA_PROGRAM:
637
			if ((playlist = playlist_program(cfg_get_media_filename())) == NULL)
638
				return (0);
639
640
641
642
643
644
			break;
		case CFG_MEDIA_STDIN:
			if ((playlist = playlist_read(NULL)) == NULL)
				return (0);
			break;
		default:
645
			if ((playlist = playlist_read(cfg_get_media_filename())) == NULL)
646
				return (0);
647
			if (playlist_get_num_items(playlist) == 0)
648
				log_warning("%s: playlist empty",
649
				    cfg_get_media_filename());
650
			break;
651
		}
652
	} else {
653
654
655
656
657
		/*
		 * XXX: This preserves traditional behavior, however,
		 *      rereading the playlist after each walkthrough seems a
		 *      bit more logical.
		 */
658
		playlist_rewind(playlist);
659
	}
660

661
662
	if (CFG_MEDIA_PROGRAM != cfg_get_media_type() &&
	    cfg_get_media_shuffle())
663
664
665
666
		playlist_shuffle(playlist);

	while ((song = playlist_get_next(playlist)) != NULL) {
		strlcpy(lastSong, song, sizeof(lastSong));
667
		if (!streamFile(stream, song))
668
			return (0);
669
670
		if (quit)
			break;
671
672
		if (rereadPlaylist) {
			rereadPlaylist = rereadPlaylist_notify = 0;
673
			if (CFG_MEDIA_PROGRAM == cfg_get_media_type())
674
				continue;
675
			log_notice("rereading playlist");
676
677
			if (!playlist_reread(&playlist))
				return (0);
678
			if (cfg_get_media_shuffle())
679
680
681
682
				playlist_shuffle(playlist);
			else {
				playlist_goto_entry(playlist, lastSong);
				playlist_skip_next(playlist);
oddsock's avatar
oddsock committed
683
			}
684
			continue;
685
		}
oddsock's avatar
oddsock committed
686
	}
687

688
	return (1);
oddsock's avatar
oddsock committed
689
690
}

691
int
692
ez_shutdown(int exitval)
693
{
694
	stream_exit();
695
696
697
	playlist_exit();
	cfg_encoder_exit();
	cfg_decoder_exit();
Moritz Grimm's avatar
Moritz Grimm committed
698
	log_exit();
699
	cfg_exit();
700
701
702
703

	return (exitval);
}

704
int
705
main(int argc, char *argv[])
oddsock's avatar
oddsock committed
706
{
707
	int		 ret, cont;
708
	const char	*errstr;
709
	stream_t	 stream;
710
711
	extern char	*optarg;
	extern int	 optind;
712
	struct sigaction act;
moritz's avatar
moritz committed
713
	unsigned int	 i;
714

Moritz Grimm's avatar
Moritz Grimm committed
715
	ret = 1;
716
717
	if (0 > cfg_init() ||
	    0 > cmdline_parse(argc, argv, &ret) ||
718
719
720
721
	    0 > log_init() ||
	    0 > cfg_decoder_init() ||
	    0 > cfg_encoder_init() ||
	    0 > playlist_init() ||
722
	    0 > cfg_file_reload() ||
723
	    0 > stream_init())
Moritz Grimm's avatar
Moritz Grimm committed
724
		return (ez_shutdown(ret));
725

726
727
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
728
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
729
	}
730

731
732
	stream = stream_get(STREAM_DEFAULT);
	if (0 > stream_setup(stream))
733
		return (ez_shutdown(1));
oddsock's avatar
oddsock committed
734

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

759
	if (0 > util_write_pid_file(cfg_get_program_pid_file()))
760
761
		log_syserr(WARNING, errno, cfg_get_program_pid_file());

762
763
764
765
766
767
768
769
770
771
772
	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() &&
773
774
		(util_strrcasecmp(cfg_get_media_filename(), ".m3u") == 0 ||
		    util_strrcasecmp(cfg_get_media_filename(), ".txt") == 0)))
775
776
777
		playlistMode = 1;
	else
		playlistMode = 0;
778

779
780
781
782
783
784
785
786
787
788
789
790
	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);
791

792
	stream_disconnect(stream);
793

794
	if (quit) {
795
796
		if (cfg_get_program_quiet_stderr() &&
		    cfg_get_program_verbosity())
797
798
799
			printf("\r");
		log_notice("INT or TERM signal received");
	}
800

801
	log_info("exiting");
802

803
	playlist_free(&playlist);
oddsock's avatar
oddsock committed
804

805
	return (ez_shutdown(0));
oddsock's avatar
oddsock committed
806
}