ezstream.c 18.2 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
char *		_build_reencode_cmd(const char *, const char *, mdata_t);
FILE *		openResource(stream_t, const char *, int *, mdata_t *,
58
			     int *, long *);
59
int		reconnect(stream_t);
60
const char *	getTimeString(long);
61
int		sendStream(stream_t, FILE *, const char *, int, const char *,
62
			   struct timespec *);
63
64
int		streamFile(stream_t, const char *);
int		streamPlaylist(stream_t);
65
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
66

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

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

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

118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
	tmp = util_utf82char(mdata_get_artist(md));
	artist = util_shellquote(tmp);
	xfree(tmp);

	tmp = util_utf82char(mdata_get_album(md));
	album = util_shellquote(tmp);
	xfree(tmp);

	tmp = util_utf82char(mdata_get_title(md));
	title = util_shellquote(tmp);
	xfree(tmp);

	tmp = util_utf82char(mdata_get_songinfo(md));
	songinfo = util_shellquote(tmp);
	xfree(tmp);
Moritz Grimm's avatar
Moritz Grimm committed
133

134
	filename_quoted = util_shellquote(filename);
Moritz Grimm's avatar
Moritz Grimm committed
135

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

150
		mdata_strformat(md, buf, sizeof(buf),
Moritz Grimm's avatar
Moritz Grimm committed
151
		    cfg_get_metadata_format_str());
152
		unquoted = util_utf82char(buf);
Moritz Grimm's avatar
Moritz Grimm committed
153
154
155
156
157
158
159
		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("");
160
		} else {
Moritz Grimm's avatar
Moritz Grimm committed
161
			custom_songinfo = xstrdup(songinfo);
162
163
		}
	}
Moritz Grimm's avatar
Moritz Grimm committed
164
	xfree(songinfo);
165

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

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

Moritz Grimm's avatar
Moritz Grimm committed
189
190
191
	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);
192
193
	xfree(dec_str);
	xfree(enc_str);
194

Moritz Grimm's avatar
Moritz Grimm committed
195
196
197
198
199
200
201
	xfree(artist);
	xfree(album);
	xfree(title);
	xfree(filename_quoted);
	xfree(custom_songinfo);

	return (cmd_str);
202
}
oddsock's avatar
oddsock committed
203

204
FILE *
205
206
openResource(stream_t stream, const char *filename, int *popenFlag,
	     mdata_t *md_p, int *isStdin, long *songLen)
207
{
208
209
210
211
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
212
	mdata_t 	 md;
oddsock's avatar
oddsock committed
213

214
215
	if (md_p != NULL)
		*md_p = NULL;
216
217
	if (songLen != NULL)
		*songLen = 0;
218

219
	if ((isStdin && *isStdin) ||
220
	    strcasecmp(filename, "stdin") == 0) {
221
		if (cfg_get_metadata_program()) {
222
223
224
225
			md = mdata_create();

			if (0 > mdata_run_program(md, cfg_get_metadata_program()) ||
			    0 > stream_set_metadata(stream, md, NULL)) {
226
				mdata_destroy(&md);
227
228
				return (NULL);
			}
229

230
231
			if (md_p != NULL)
				*md_p = md;
232
			else
233
				mdata_destroy(&md);
234
		}
235

236
237
		if (isStdin != NULL)
			*isStdin = 1;
238
		filep = stdin;
239
		return (filep);
oddsock's avatar
oddsock committed
240
	}
241

242
243
244
245
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
246
	p = strrchr(filename, '.');
247
248
249
	if (p != NULL)
		strlcpy(extension, p, sizeof(extension));
	for (p = extension; *p != '\0'; p++)
250
		*p = (char)tolower((int)*p);
251
252

	if (strlen(extension) == 0) {
253
		log_error("%s: cannot determine file type", filename);
254
255
256
		return (filep);
	}

257
	md = mdata_create();
258
	if (cfg_get_metadata_program()) {
259
260
		if (0 > mdata_run_program(md, cfg_get_metadata_program()))
			mdata_destroy(&md);
261
	} else {
262
263
		if (0 > mdata_parse_file(md, filename))
			mdata_destroy(&md);
264
	}
265
266
	if (NULL == md)
		return (NULL);
267
	if (songLen != NULL)
268
		*songLen = mdata_get_length(md);
269
270

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

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

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

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

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

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

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

322
		return (filep);
323
	}
324

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

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

	return (filep);
336
337
}

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

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

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

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

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

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

	return (-1);
373
374
}

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

	if (seconds < 0)
		return (NULL);

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

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

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

405
	clock_gettime(CLOCK_MONOTONIC, &callTime);
406

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

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

422
		stream_sync(stream);
423

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

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

443
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
444
445

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

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

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

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

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

511
	return (ret);
512
513
514
}

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

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

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

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

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

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

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

590
					log_info("running metadata program: %s",
591
					    cfg_get_metadata_program());
592
593
594
595
					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);
596
597
						retval = 0;
						ret = STREAM_DONE;
598
						continue;
599
					}
600
					mdata_destroy(&prog_md);
601
					log_info("new metadata: %s", mdataStr);
602
603
604
					xfree(mdataStr);
				}
			}
605
606
607
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
608
609
610
			}
		} else
			retval = 1;
611
	} while (ret != STREAM_DONE);
612
613

	if (popenFlag)
oddsock's avatar
oddsock committed
614
		pclose(filepstream);
Moritz Grimm's avatar
Moritz Grimm committed
615
	else if (!isStdin)
oddsock's avatar
oddsock committed
616
		fclose(filepstream);
617

618
619
620
	if (songLenStr != NULL)
		xfree(songLenStr);

621
	return (retval);
oddsock's avatar
oddsock committed
622
}
623

624
int
625
streamPlaylist(stream_t stream)
626
627
{
	const char	*song;
moritz's avatar
moritz committed
628
	char		 lastSong[PATH_MAX];
629
630

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

657
658
	if (CFG_MEDIA_PROGRAM != cfg_get_media_type() &&
	    cfg_get_media_shuffle())
659
660
661
662
		playlist_shuffle(playlist);

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

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

687
int
688
ez_shutdown(int exitval)
689
{
690
	stream_exit();
691
692
693
	playlist_exit();
	cfg_encoder_exit();
	cfg_decoder_exit();
Moritz Grimm's avatar
Moritz Grimm committed
694
	log_exit();
695
	cfg_exit();
696
697
698
699

	return (exitval);
}

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

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

722
723
	if (0 > cfg_check(&errstr)) {
		log_error("%s: %s", cfg_get_program_config_file(), errstr);
724
		return (ez_shutdown(2));
oddsock's avatar
oddsock committed
725
	}
726

727
728
	stream = stream_get(STREAM_DEFAULT);
	if (0 > stream_setup(stream))
729
		return (ez_shutdown(1));
oddsock's avatar
oddsock committed
730

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

755
	if (0 > util_write_pid_file(cfg_get_program_pid_file()))
756
757
		log_syserr(WARNING, errno, cfg_get_program_pid_file());

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

775
776
777
778
779
780
781
782
783
784
785
786
	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);
787

788
	stream_disconnect(stream);
789

790
	if (quit) {
791
792
		if (cfg_get_program_quiet_stderr() &&
		    cfg_get_program_verbosity())
793
794
795
			printf("\r");
		log_notice("INT or TERM signal received");
	}
796

797
	log_info("exiting");
798

799
	playlist_free(&playlist);
oddsock's avatar
oddsock committed
800

801
	return (ez_shutdown(0));
oddsock's avatar
oddsock committed
802
}