ezstream.c 26.1 KB
Newer Older
1
2
3
/*
 *  ezstream - source client for Icecast with external en-/decoder support
 *  Copyright (C) 2003, 2004, 2005, 2006  Ed Zaleski <oddsock@oddsock.org>
4
 *  Copyright (C) 2007, 2009, 2015        Moritz Grimm <mgrimm@mrsserver.net>
5
6
 *
 *  This program is free software; you can redistribute it and/or modify
moritz's avatar
moritz committed
7
8
 *  it under the terms of the GNU General Public License version 2 as
 *  published by the Free Software Foundation.
9
10
11
12
13
14
15
16
17
18
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
oddsock's avatar
oddsock committed
19

20
21
#include "compat.h"

22
23
#include "ezstream.h"

24
25
26
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif
27

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

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

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

moritz's avatar
moritz committed
44
45
playlist_t		*playlist = NULL;
int			 playlistMode = 0;
46
unsigned int		 resource_errors = 0;
47

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

volatile sig_atomic_t	 rereadPlaylist = 0;
volatile sig_atomic_t	 rereadPlaylist_notify = 0;
volatile sig_atomic_t	 skipTrack = 0;
56
volatile sig_atomic_t	 queryMetadata = 0;
57
volatile sig_atomic_t	 quit = 0;
58
#else
59
60
61
int			 rereadPlaylist = 0;
int			 rereadPlaylist_notify = 0;
int			 skipTrack = 0;
62
int			 queryMetadata = 0;
63
int			 quit = 0;
64
#endif /* HAVE_SIGNALS */
oddsock's avatar
oddsock committed
65
66

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

76
int		urlParse(const char *, char **, unsigned short *, char **);
77
78
char *		shellQuote(const char *);
char *		replaceString(const char *, const char *, const char *);
79
char *		buildReencodeCommand(const char *, const char *, metadata_t *);
80
char *		getMetadataString(const char *, metadata_t *);
81
82
metadata_t *	getMetadata(const char *);
int		setMetadata(shout_t *, metadata_t *, char **);
83
FILE *		openResource(shout_t *, const char *, int *, metadata_t **,
84
			     int *, long *);
85
int		reconnectServer(shout_t *, int);
86
const char *	getTimeString(long);
87
int		sendStream(shout_t *, FILE *, const char *, int, const char *,
88
			   struct timeval *);
89
int		streamFile(shout_t *, const char *);
90
int		streamPlaylist(shout_t *);
91
int		ez_shutdown(int);
oddsock's avatar
oddsock committed
92

93
#ifdef HAVE_SIGNALS
94
95
96
97
98
void		sig_handler(int);

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

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

124
int
125
126
urlParse(const char *url, char **hostname, unsigned short *port,
	 char **mountname)
oddsock's avatar
oddsock committed
127
{
128
	const char	*p1, *p2, *p3;
129
130
131
	char		 tmpPort[6] = "";
	size_t		 hostsiz, mountsiz;
	const char	*errstr;
oddsock's avatar
oddsock committed
132

133
	if (strncmp(url, "http://", strlen("http://")) != 0) {
134
		log_error("invalid <url>: not an HTTP address");
135
		return (0);
136
	}
137

138
	p1 = url + strlen("http://");
oddsock's avatar
oddsock committed
139
	p2 = strchr(p1, ':');
140
	if (p2 == NULL) {
141
		log_error("invalid <url>: missing port");
142
		return (0);
143
	}
144
	hostsiz = (p2 - p1) + 1;
145
146
147
148
	if (hostsiz <= 1) {
		log_error("invalid <url>: missing host");
		return (0);
	}
149
150
151
	*hostname = xmalloc(hostsiz);
	strlcpy(*hostname, p1, hostsiz);

oddsock's avatar
oddsock committed
152
153
	p2++;
	p3 = strchr(p2, '/');
154
	if (p3 == NULL || p3 - p2 >= (int)sizeof(tmpPort)) {
155
		log_error("invalid <url>: mountpoint missing, or port number too long");
156
		xfree(*hostname);
157
		return (0);
158
	}
159

160
161
	strlcpy(tmpPort, p2, (p3 - p2) + 1UL);
	*port = (unsigned short)strtonum(tmpPort, 1LL, (long long)USHRT_MAX, &errstr);
162
	if (errstr) {
163
		log_error("invalid <url>: port: %s is %s", tmpPort, errstr);
164
165
166
		xfree(*hostname);
		return (0);
	}
167
168
169
170
171
172

	mountsiz = strlen(p3) + 1;
	*mountname = xmalloc(mountsiz);
	strlcpy(*mountname, p3, mountsiz);

	return (1);
oddsock's avatar
oddsock committed
173
174
}

175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#define SHELLQUOTE_INLEN_MAX	8191UL

char *
shellQuote(const char *in)
{
	char		*out, *out_p;
	size_t		 out_len;
	const char	*in_p;

	out_len = (strlen(in) > SHELLQUOTE_INLEN_MAX)
	    ? SHELLQUOTE_INLEN_MAX
	    : strlen(in);
	out_len = out_len * 2 + 2;
	out = xcalloc(out_len + 1, sizeof(char));

	out_p = out;
	in_p = in;

	*out_p++ = '\'';
	out_len--;
	while (*in_p && out_len > 2) {
		switch (*in_p) {
		case '\'':
		case '\\':
			*out_p++ = '\\';
			out_len--;
			break;
		default:
			break;
		}
		*out_p++ = *in_p++;
		out_len--;
	}
	*out_p++ = '\'';

	return (out);
}

char *
replaceString(const char *source, const char *from, const char *to)
215
{
216
217
218
219
220
221
222
	char		*to_quoted, *dest;
	size_t		 dest_size;
	const char	*p1, *p2;

	to_quoted = shellQuote(to);
	dest_size = strlen(source) + strlen(to_quoted) + 1;
	dest = xcalloc(dest_size, sizeof(char));
223

224
	p1 = source;
225
226
	p2 = strstr(p1, from);
	if (p2 != NULL) {
227
		strncat(dest, p1, (size_t)(p2 - p1));
228
		strlcat(dest, to_quoted, dest_size);
229
		p1 = p2 + strlen(from);
230
	}
231
232
233
234
235
	strlcat(dest, p1, dest_size);

	xfree(to_quoted);

	return (dest);
236
237
}

238
char *
239
240
buildReencodeCommand(const char *extension, const char *fileName,
    metadata_t *mdata)
241
{
242
243
244
245
246
247
248
249
250
251
	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",
252
		    fileName, extension);
253
		return (NULL);
254
	}
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
	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,
271
		    localArtist);
272
273
		xfree(dec_str);
		dec_str = tmpStr;
274
	}
275
276
	if (strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
		char *tmpStr = replaceString(dec_str, PLACEHOLDER_TITLE,
277
		    localTitle);
278
279
		xfree(dec_str);
		dec_str = tmpStr;
280
	}
281
282
283
284
285
286
287
288
289
290
	/*
	 * if meta
	 *   if (prog && format)
	 *      metatoformat
	 *   else
	 *     if (!prog && title)
	 *       emptymeta
	 *     else
	 *       replacemeta
	 */
291
292
293
294
295
296
297
298
	if (strstr(dec_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
			char *mdataString = getMetadataString(cfg_get_metadata_format_str(),
			    mdata);
			char *tmpStr = replaceString(dec_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(dec_str);
299
			xfree(mdataString);
300
			dec_str = tmpStr;
301
		} else {
302
303
304
305
306
307
			if (!cfg_get_metadata_program() &&
			    strstr(dec_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, "");
				xfree(dec_str);
				dec_str = tmpStr;
308
			} else {
309
310
311
312
				char *tmpStr = replaceString(dec_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(dec_str);
				dec_str = tmpStr;
313
314
315
			}
		}
	}
316

317
318
319
	if (!cfg_encoder_get_program(encoder))
		return (dec_str);

320
321
322
323
	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,
324
		    localTitle);
325
326
		xfree(enc_str);
		enc_str = tmpStr;
327
	}
328
329
330
331
332
333
334
335
	if (strstr(enc_str, PLACEHOLDER_METADATA) != NULL) {
		if (cfg_get_metadata_program() &&
		    cfg_get_metadata_format_str()) {
			char *mdataString = getMetadataString(cfg_get_metadata_format_str(),
			    mdata);
			char *tmpStr = replaceString(enc_str,
			    PLACEHOLDER_METADATA, mdataString);
			xfree(enc_str);
336
			xfree(mdataString);
337
			enc_str = tmpStr;
338
		} else {
339
340
341
342
343
344
			if (!cfg_get_metadata_program() &&
			    strstr(enc_str, PLACEHOLDER_TITLE) != NULL) {
				char *tmpStr = replaceString(enc_str,
				    PLACEHOLDER_METADATA, "");
				xfree(enc_str);
				enc_str = tmpStr;
345
			} else {
346
347
348
349
				char *tmpStr = replaceString(enc_str,
				    PLACEHOLDER_METADATA, localMetaString);
				xfree(enc_str);
				enc_str = tmpStr;
350
351
352
			}
		}
	}
353

354
355
	commandStringLen = strlen(dec_str) + strlen(" | ") +
	    strlen(enc_str) + 1;
356
	commandString = xcalloc(commandStringLen, sizeof(char));
357
358
	snprintf(commandString, commandStringLen, "%s | %s", dec_str,
	    enc_str);
359

360
361
362
	xfree(localTitle);
	xfree(localArtist);
	xfree(localMetaString);
363
364
	xfree(dec_str);
	xfree(enc_str);
365
366

	return (commandString);
367
}
oddsock's avatar
oddsock committed
368

369
370
371
372
373
374
375
376
377
378
char *
getMetadataString(const char *format, metadata_t *mdata)
{
	char	*tmp, *str;

	if (format == NULL)
		return (NULL);

	str = xstrdup(format);

379
380
	if (strstr(format, PLACEHOLDER_ARTIST) != NULL) {
		tmp = replaceString(str, PLACEHOLDER_ARTIST,
381
		    metadata_get_artist(mdata));
382
383
384
		xfree(str);
		str = tmp;
	}
385
386
	if (strstr(format, PLACEHOLDER_TITLE) != NULL) {
		tmp = replaceString(str, PLACEHOLDER_TITLE,
387
		    metadata_get_title(mdata));
388
389
390
		xfree(str);
		str = tmp;
	}
391
392
	if (strstr(format, PLACEHOLDER_STRING) != NULL) {
		tmp = replaceString(str, PLACEHOLDER_STRING,
393
		    metadata_get_string(mdata));
394
395
396
		xfree(str);
		str = tmp;
	}
397
398
	if (strstr(format, PLACEHOLDER_TRACK) != NULL) {
		tmp = replaceString(str, PLACEHOLDER_TRACK,
399
		    metadata_get_filename(mdata));
400
401
402
403
404
405
406
		xfree(str);
		str = tmp;
	}

	return (str);
}

407
408
metadata_t *
getMetadata(const char *fileName)
moritz's avatar
moritz committed
409
{
410
	metadata_t	*mdata;
411

412
413
414
	if (cfg_get_metadata_program()) {
		if (NULL == (mdata = metadata_program(fileName,
		    cfg_get_metadata_normalize_strings())))
415
416
			return (NULL);

417
		if (!metadata_program_update(mdata, METADATA_ALL)) {
418
			metadata_free(&mdata);
419
			return (NULL);
420
421
		}
	} else {
422
423
		if (NULL == (mdata = metadata_file(fileName,
		    cfg_get_metadata_normalize_strings())))
424
			return (NULL);
moritz's avatar
moritz committed
425

426
427
		if (!metadata_file_update(mdata)) {
			metadata_free(&mdata);
428
			return (NULL);
429
		}
430
	}
431

432
433
434
435
436
437
438
	return (mdata);
}

int
setMetadata(shout_t *shout, metadata_t *mdata, char **mdata_copy)
{
	shout_metadata_t	*shout_mdata = NULL;
moritz's avatar
moritz committed
439
440
	char			*songInfo;
	const char		*artist, *title;
441
442
	int			 ret = SHOUTERR_SUCCESS;

443
	if (cfg_get_metadata_no_updates())
444
445
		return (SHOUTERR_SUCCESS);

446
447
	if (mdata == NULL)
		return 1;
448

449
	if ((shout_mdata = shout_metadata_new()) == NULL) {
450
		log_syserr(ALERT, ENOMEM, "shout_metadata_new");
moritz's avatar
moritz committed
451
		exit(1);
452
	}
453

moritz's avatar
moritz committed
454
455
456
457
458
459
460
461
462
463
464
	artist = metadata_get_artist(mdata);
	title = metadata_get_title(mdata);

	/*
	 * We can do this, because we know how libshout works. This adds
	 * "charset=UTF-8" to the HTTP metadata update request and has the
	 * desired effect of letting newer-than-2.3.1 versions of Icecast know
	 * which encoding we're using.
	 */
	if (shout_metadata_add(shout_mdata, "charset", "UTF-8") != SHOUTERR_SUCCESS) {
		/* Assume SHOUTERR_MALLOC */
465
		log_syserr(ALERT, ENOMEM, "shout_metadata_add");
moritz's avatar
moritz committed
466
467
468
		exit(1);
	}

469
470
	songInfo = getMetadataString(cfg_get_metadata_format_str(), mdata);
	if (songInfo == NULL) {
moritz's avatar
moritz committed
471
		if (artist[0] == '\0' && title[0] == '\0')
472
473
474
			songInfo = xstrdup(metadata_get_string(mdata));
		else
			songInfo = metadata_assemble_string(mdata);
moritz's avatar
moritz committed
475
476
		if (artist[0] != '\0' && title[0] != '\0') {
			if (shout_metadata_add(shout_mdata, "artist", artist) != SHOUTERR_SUCCESS) {
477
478
				log_syserr(ALERT, ENOMEM,
				    "shout_metadata_add");
moritz's avatar
moritz committed
479
480
481
				exit(1);
			}
			if (shout_metadata_add(shout_mdata, "title", title) != SHOUTERR_SUCCESS) {
482
483
				log_syserr(ALERT, ENOMEM,
				    "shout_metadata_add");
moritz's avatar
moritz committed
484
485
486
487
				exit(1);
			}
		} else {
			if (shout_metadata_add(shout_mdata, "song", songInfo) != SHOUTERR_SUCCESS) {
488
489
				log_syserr(ALERT, ENOMEM,
				    "shout_metadata_add");
moritz's avatar
moritz committed
490
491
492
493
				exit(1);
			}
		}
	} else if (shout_metadata_add(shout_mdata, "song", songInfo) != SHOUTERR_SUCCESS) {
494
		log_syserr(ALERT, ENOMEM, "shout_metadata_add");
495
496
		exit(1);
	}
moritz's avatar
moritz committed
497

498
	if ((ret = shout_set_metadata(shout, shout_mdata)) != SHOUTERR_SUCCESS)
499
		log_warning("shout_set_metadata: %s", shout_get_error(shout));
moritz's avatar
moritz committed
500

501
	shout_metadata_free(shout_mdata);
moritz's avatar
moritz committed
502
503
504
505
506

	if (ret == SHOUTERR_SUCCESS) {
		if (mdata_copy != NULL && *mdata_copy == NULL)
			*mdata_copy = xstrdup(songInfo);
	}
moritz's avatar
moritz committed
507

508
509
	xfree(songInfo);
	return (ret);
510
511
}

512
513
FILE *
openResource(shout_t *shout, const char *fileName, int *popenFlag,
514
	     metadata_t **mdata_p, int *isStdin, long *songLen)
515
{
516
517
518
519
520
	FILE		*filep = NULL;
	char		 extension[25];
	char		*p = NULL;
	char		*pCommandString = NULL;
	metadata_t	*mdata;
oddsock's avatar
oddsock committed
521

522
523
	if (mdata_p != NULL)
		*mdata_p = NULL;
524
525
	if (songLen != NULL)
		*songLen = 0;
526

527
	if (strcmp(fileName, "stdin") == 0) {
528
529
		if (cfg_get_metadata_program()) {
			if ((mdata = getMetadata(cfg_get_metadata_program())) == NULL)
530
				return (NULL);
531
			if (setMetadata(shout, mdata, NULL) != SHOUTERR_SUCCESS) {
532
533
534
				metadata_free(&mdata);
				return (NULL);
			}
535
536
537
538
			if (mdata_p != NULL)
				*mdata_p = mdata;
			else
				metadata_free(&mdata);
539
		}
540

541
542
		if (isStdin != NULL)
			*isStdin = 1;
543
		filep = stdin;
544
		return (filep);
oddsock's avatar
oddsock committed
545
	}
546

547
548
549
550
	if (isStdin != NULL)
		*isStdin = 0;

	extension[0] = '\0';
551
552
553
554
555
556
557
	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) {
558
		log_error("%s: cannot determine file type", fileName);
559
560
561
		return (filep);
	}

562
563
	if (cfg_get_metadata_program()) {
		if ((mdata = getMetadata(cfg_get_metadata_program())) == NULL)
564
565
566
567
568
			return (NULL);
	} else {
		if ((mdata = getMetadata(fileName)) == NULL)
			return (NULL);
	}
569
570
	if (songLen != NULL)
		*songLen = metadata_get_length(mdata);
571
572

	*popenFlag = 0;
573
	if (cfg_get_stream_encoder()) {
574
		int	stderr_fd = -1;
575

576
577
		pCommandString = buildReencodeCommand(extension, fileName,
		    mdata);
578
579
580
581
		if (mdata_p != NULL)
			*mdata_p = mdata;
		else
			metadata_free(&mdata);
582
		log_info("running command: %s", pCommandString);
583

584
		if (cfg_get_program_quiet_stderr()) {
585
586
			int fd;

587
			stderr_fd = dup(fileno(stderr));
588
			if ((fd = open(_PATH_DEVNULL, O_RDWR, 0)) == -1) {
589
590
				log_alert("%s: %s", _PATH_DEVNULL,
				    strerror(errno));
591
				exit(1);
592
593
			}

594
595
596
597
598
599
600
601
602
603
			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)
604
605
				log_error("execution error: %s: %s",
				    pCommandString, strerror(errno));
606
			else
607
608
				log_error("execution error: %s",
				    pCommandString);
609
610
611
612
		} else {
			*popenFlag = 1;
		}
		xfree(pCommandString);
613

614
		if (cfg_get_program_quiet_stderr())
615
			dup2(stderr_fd, fileno(stderr));
616
617
618

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

620
		return (filep);
621
	}
622

623
624
625
626
	if (mdata_p != NULL)
		*mdata_p = mdata;
	else
		metadata_free(&mdata);
627

628
629
630
631
	if ((filep = fopen(fileName, "rb")) == NULL) {
		log_error("%s: %s", fileName, strerror(errno));
		return (NULL);
	}
632
633

	return (filep);
634
635
}

636
637
638
639
640
641
int
reconnectServer(shout_t *shout, int closeConn)
{
	unsigned int	i;
	int		close_conn = closeConn;

642
	log_warning("%s: connection lost", cfg_get_server_hostname());
643
644
645

	i = 0;
	while (++i) {
646
		if (cfg_get_server_reconnect_attempts() > 0)
647
			log_notice("reconnect: %s: attempt #%u/%u ...",
648
649
			    cfg_get_server_hostname(), i,
			    cfg_get_server_reconnect_attempts());
650
		else
651
			log_notice("reconnect: %s: attempt #%u ...",
652
			    cfg_get_server_hostname(), i);
653
654
655
656
657
658

		if (close_conn == 0)
			close_conn = 1;
		else
			shout_close(shout);
		if (shout_open(shout) == SHOUTERR_SUCCESS) {
659
			log_notice("reconnect: %s: success",
660
			    cfg_get_server_hostname());
661
662
663
			return (1);
		}

664
		log_warning("reconnect failed: %s: %s",
665
		    cfg_get_server_hostname(), shout_get_error(shout));
666

667
668
		if (cfg_get_server_reconnect_attempts() > 0 &&
		    i >= cfg_get_server_reconnect_attempts())
669
670
			break;

671
672
673
674
		if (quit)
			return (0);
		else
			sleep(5);
675
676
	};

677
	log_warning("reconnect failed: giving up");
678
679
680
	return (0);
}

681
const char *
682
getTimeString(long seconds)
683
684
{
	static char	str[20];
685
	long		secs, mins, hours;
686
687
688
689
690
691
692
693
694
695

	if (seconds < 0)
		return (NULL);

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

696
	snprintf(str, sizeof(str), "%ldh%02ldm%02lds", hours, mins, secs);
697
698
699
	return ((const char *)str);
}

700
int
701
sendStream(shout_t *shout, FILE *filepstream, const char *fileName,
702
	   int isStdin, const char *songLenStr, struct timeval *tv)
703
704
{
	unsigned char	 buff[4096];
705
	size_t		 bytes_read, total, oldTotal;
706
	int		 ret;
707
	double		 kbps = -1.0;
708
	struct timeval	 timeStamp, *startTime = tv;
709
	struct timeval	 callTime, currentTime;
710

711
712
	ez_gettimeofday((void *)&callTime);

713
714
	timeStamp.tv_sec = startTime->tv_sec;
	timeStamp.tv_usec = startTime->tv_usec;
715
716

	total = oldTotal = 0;
717
	ret = STREAM_DONE;
718
	while ((bytes_read = fread(buff, 1UL, sizeof(buff), filepstream)) > 0) {
719
720
721
722
723
724
		if (shout_get_connected(shout) != SHOUTERR_CONNECTED &&
		    reconnectServer(shout, 0) == 0) {
			ret = STREAM_SERVERR;
			break;
		}

725
726
		shout_sync(shout);

727
		if (shout_send(shout, buff, bytes_read) != SHOUTERR_SUCCESS) {
728
			log_error("shout_send: %s", shout_get_error(shout));
729
730
731
732
733
734
735
736
			if (reconnectServer(shout, 1))
				break;
			else {
				ret = STREAM_SERVERR;
				break;
			}
		}

737
738
		if (quit)
			break;
739
740
		if (rereadPlaylist_notify) {
			rereadPlaylist_notify = 0;
741
			if (CFG_MEDIA_PLAYLIST == cfg_get_media_type())
742
				log_notice("HUP signal received: playlist re-read scheduled");
743
744
745
		}
		if (skipTrack) {
			skipTrack = 0;
746
			ret = STREAM_SKIP;
747
748
			break;
		}
749
750
751
752

		ez_gettimeofday((void *)&currentTime);

		if (queryMetadata ||
753
		    (0 <= cfg_get_metadata_refresh_interval() &&
754
755
			(currentTime.tv_sec - callTime.tv_sec >=
			    cfg_get_metadata_refresh_interval()))) {
756
			queryMetadata = 0;
757
			if (cfg_get_metadata_program()) {
758
				ret = STREAM_UPDMDATA;
759
				break;
oddsock's avatar
oddsock committed
760
			}
761
762
		}

763
		total += bytes_read;
764
		if (cfg_get_program_rtstatus_output()) {
765
			double	oldTime, newTime;
766

767
			if (!isStdin && playlistMode) {
768
769
				if (CFG_MEDIA_PROGRAM == cfg_get_media_type()) {
					char *tmp = xstrdup(cfg_get_media_filename());
770
					printf("  [%s]", basename(tmp));
771
772
773
					xfree(tmp);
				} else
					printf("  [%4lu/%-4lu]",
774
775
					    playlist_get_position(playlist),
					    playlist_get_num_items(playlist));
776
			}
777
778

			oldTime = (double)timeStamp.tv_sec
779
			    + (double)timeStamp.tv_usec / 1000000.0;
780
			newTime = (double)currentTime.tv_sec
781
			    + (double)currentTime.tv_usec / 1000000.0;
782
783
			if (songLenStr == NULL)
				printf("  [ %s]",
784
785
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec));
786
787
			else
				printf("  [ %s/%s]",
788
789
790
				    getTimeString(currentTime.tv_sec -
					startTime->tv_sec),
				    songLenStr);
791
			if (newTime - oldTime >= 1.0) {
792
				kbps = (((double)(total - oldTotal)
793
				    / (newTime - oldTime)) * 8.0) / 1000.0;
794
795
				timeStamp.tv_sec = currentTime.tv_sec;
				timeStamp.tv_usec = currentTime.tv_usec;
796
797
798
799
800
801
802
803
804
805
				oldTotal = total;
			}
			if (kbps < 0)
				printf("                 ");
			else
				printf("  [%8.2f kbps]", kbps);

			printf("  \r");
			fflush(stdout);
		}
oddsock's avatar
oddsock committed
806
	}
807
808
809
	if (ferror(filepstream)) {
		if (errno == EINTR) {
			clearerr(filepstream);
810
			ret = STREAM_CONT;
811
		} else if (errno == EBADF && isStdin)
812
			log_notice("no (more) data available on standard input");
813
		else
814
815
			log_error("sendStream: %s: %s", fileName,
			    strerror(errno));
816
817
	}

818
	return (ret);
819
820
821
822
823
824
825
}

int
streamFile(shout_t *shout, const char *fileName)
{
	FILE		*filepstream = NULL;
	int		 popenFlag = 0;
826
	char		*songLenStr = NULL;
827
	int		 isStdin = 0;
828
829
	int		 ret, retval = 0;
	long		 songLen;
830
	metadata_t	*mdata;
831
832
	struct timeval	 startTime;

833
	if ((filepstream = openResource(shout, fileName, &popenFlag, &mdata, &isStdin, &songLen))
834
835
	    == NULL) {
		if (++resource_errors > 100) {
836
			log_error("too many errors; giving up");
837
838
			return (0);
		}
839
840
		/* Continue with next resource on failure: */
		return (1);
841
842
	}
	resource_errors = 0;
843

844
	if (mdata != NULL) {
845
		char	*tmp, *metaData;
846

847
		tmp = metadata_assemble_string(mdata);
848
849
		if ((metaData = UTF8toCHAR(tmp, ICONV_REPLACE)) == NULL)
			metaData = xstrdup("(unknown title)");
850
		xfree(tmp);
851
		log_notice("streaming: %s (%s)", metaData, fileName);
852
		xfree(metaData);
853
854

		/* MP3 streams are special, so set the metadata explicitly: */
855
		if (CFG_STREAM_MP3 == cfg_get_stream_format())
856
857
858
			setMetadata(shout, mdata, NULL);

		metadata_free(&mdata);
859
	} else if (isStdin)
860
		log_notice("streaming: standard input");
861

moritz's avatar
moritz committed
862
	if (songLen > 0)
863
		songLenStr = xstrdup(getTimeString(songLen));
864
	ez_gettimeofday((void *)&startTime);
865
866
	do {
		ret = sendStream(shout, filepstream, fileName, isStdin,
867
		    songLenStr, &startTime);
868
869
		if (quit)
			break;
870
		if (ret != STREAM_DONE) {
871
872
			if ((skipTrack && rereadPlaylist) ||
			    (skipTrack && queryMetadata)) {
873
				skipTrack = 0;
874
875
876
877
878
				ret = STREAM_CONT;
			}
			if (queryMetadata && rereadPlaylist) {
				queryMetadata = 0;
				ret = STREAM_CONT;
879
			}
880
			if (ret == STREAM_SKIP || skipTrack) {
881
				skipTrack = 0;
882
883
				if (!isStdin)
					log_notice("USR1 signal received: skipping current track");
884
				retval = 1;
885
886
				ret = STREAM_DONE;
			}
887
888
			if (ret == STREAM_UPDMDATA || queryMetadata) {
				queryMetadata = 0;
889
				if (cfg_get_metadata_no_updates())
890
					continue;
891
				if (cfg_get_metadata_program()) {
892
					char		*mdataStr = NULL;
893
					metadata_t	*prog_mdata;
894

895
					log_info("running metadata program: %s",
896
897
					    cfg_get_metadata_program());
					if ((prog_mdata = getMetadata(cfg_get_metadata_program())) == NULL) {
898
899
900
901
						retval = 0;
						ret = STREAM_DONE;
						continue;
					}
902
					if (setMetadata(shout, prog_mdata, &mdataStr) != SHOUTERR_SUCCESS) {
903
904
						retval = 0;
						ret = STREAM_DONE;
905
						continue;
906
					}
907
					metadata_free(&prog_mdata);
908
					log_info("new metadata: %s", mdataStr);
909
910
911
					xfree(mdataStr);
				}
			}
912
913
914
			if (ret == STREAM_SERVERR) {
				retval = 0;
				ret = STREAM_DONE;
moritz's avatar