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
			dup2(fd, fileno(stderr));
297
			close(fd);
298
299
300
301
302
303
304
		}

		fflush(NULL);
		errno = 0;
		if ((filep = popen(pCommandString, "r")) == NULL) {
			/* popen() does not set errno reliably ... */
			if (errno)
305
306
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
307
			else
308
309
				log_error("execution error: %s",
				    pCommandString);
310
311
312
313
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
314

315
		if (cfg_get_program_quiet_stderr())
316
			dup2(stderr_fd, fileno(stderr));
317

318
		if (stderr_fd != -1)
319
			close(stderr_fd);
320

321
		return (filep);
322
	}
323

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

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

	return (filep);
335
336
}

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

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

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

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

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

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

	return (-1);
372
373
}

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

	if (seconds < 0)
		return (NULL);

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

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

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

404
	clock_gettime(CLOCK_MONOTONIC, &callTime);
405

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

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

421
		stream_sync(stream);
422

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

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

442
		clock_gettime(CLOCK_MONOTONIC, &currentTime);
443
444

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

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

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

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

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

510
	return (ret);
511
512
513
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	return (exitval);
}

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

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

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

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

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

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

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

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

787
	stream_disconnect(stream);
788

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

796
	log_info("exiting");
797

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

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