1 /*
2  * MOC - music on console
3  * Copyright (C) 2004-2005 Damian Pietras <daper@daper.net>
4  *
5  * This program is free software; you can redistribute it and/or modify
6  * it under the terms of the GNU General Public License as published by
7  * the Free Software Foundation; either version 2 of the License, or
8  * (at your option) any later version.
9  *
10  */
11 
12 #ifdef HAVE_CONFIG_H
13 # include "config.h"
14 #endif
15 
16 #include <stdio.h>
17 #include <pthread.h>
18 #include <string.h>
19 #include <stdint.h>
20 #include <errno.h>
21 #include <assert.h>
22 
23 #define DEBUG
24 
25 #include "common.h"
26 #include "log.h"
27 #include "decoder.h"
28 #include "audio.h"
29 #include "out_buf.h"
30 #include "server.h"
31 #include "options.h"
32 #include "player.h"
33 #include "files.h"
34 #include "playlist.h"
35 #include "md5.h"
36 
37 #define PCM_BUF_SIZE		(36 * 1024)
38 #define PREBUFFER_THRESHOLD	(18 * 1024)
39 
40 enum request
41 {
42 	REQ_NOTHING,
43 	REQ_SEEK,
44 	REQ_STOP,
45 	REQ_PAUSE,
46 	REQ_UNPAUSE
47 };
48 
49 struct bitrate_list_node
50 {
51 	struct bitrate_list_node *next;
52 	int time;
53 	int bitrate;
54 };
55 
56 /* List of points where bitrate has changed. We use it to show bitrate at the
57  * right time when playing, because the output buffer may be big and decoding
58  * may be many seconds ahead of what the user can hear. */
59 struct bitrate_list
60 {
61 	struct bitrate_list_node *head;
62 	struct bitrate_list_node *tail;
63 	pthread_mutex_t mutex;
64 };
65 
66 struct md5_data {
67 	bool okay;
68 	long len;
69 	struct md5_ctx ctx;
70 };
71 
72 struct precache
73 {
74 	char *file; /* the file to precache */
75 	char buf[2 * PCM_BUF_SIZE]; /* PCM buffer with precached data */
76 	int buf_fill;
77 	int ok; /* 1 if precache succeed */
78 	struct sound_params sound_params; /* of the sound in the buffer */
79 	struct decoder *f; /* decoder functions for precached file */
80 	void *decoder_data;
81 	int running; /* if the precache thread is running */
82 	pthread_t tid; /* tid of the precache thread */
83 	struct bitrate_list bitrate_list;
84 	int decoded_time; /* how much sound we decoded in seconds */
85 };
86 
87 struct precache precache;
88 
89 /* Request conditional and mutex. */
90 static pthread_cond_t request_cond = PTHREAD_COND_INITIALIZER;
91 static pthread_mutex_t request_cond_mutex = PTHREAD_MUTEX_INITIALIZER;
92 
93 static enum request request = REQ_NOTHING;
94 static int req_seek;
95 
96 /* Source of the played stream tags. */
97 static enum
98 {
99 	TAGS_SOURCE_DECODER,	/* tags from the stream (e.g., id3tags, vorbis comments) */
100 	TAGS_SOURCE_METADATA	/* tags from icecast metadata */
101 } tags_source;
102 
103 /* Tags of the currently played file. */
104 static struct file_tags *curr_tags = NULL;
105 
106 /* Mutex for curr_tags and tags_source. */
107 static pthread_mutex_t curr_tags_mut = PTHREAD_MUTEX_INITIALIZER;
108 
109 /* Stream associated with the currently playing decoder. */
110 static struct io_stream *decoder_stream = NULL;
111 static pthread_mutex_t decoder_stream_mut = PTHREAD_MUTEX_INITIALIZER;
112 
113 static int prebuffering = 0; /* are we prebuffering now? */
114 
115 static struct bitrate_list bitrate_list;
116 
bitrate_list_init(struct bitrate_list * b)117 static void bitrate_list_init (struct bitrate_list *b)
118 {
119 	assert (b != NULL);
120 
121 	b->head = NULL;
122 	b->tail = NULL;
123 	pthread_mutex_init (&b->mutex, NULL);
124 }
125 
bitrate_list_empty(struct bitrate_list * b)126 static void bitrate_list_empty (struct bitrate_list *b)
127 {
128 	assert (b != NULL);
129 
130 	LOCK (b->mutex);
131 	if (b->head) {
132 		while (b->head) {
133 			struct bitrate_list_node *t = b->head->next;
134 
135 			free (b->head);
136 			b->head = t;
137 		}
138 
139 		b->tail = NULL;
140 	}
141 
142 	debug ("Bitrate list elements removed.");
143 
144 	UNLOCK (b->mutex);
145 }
146 
bitrate_list_destroy(struct bitrate_list * b)147 static void bitrate_list_destroy (struct bitrate_list *b)
148 {
149 	int rc;
150 
151 	assert (b != NULL);
152 
153 	bitrate_list_empty (b);
154 
155 	rc = pthread_mutex_destroy (&b->mutex);
156 	if (rc != 0)
157 		logit ("Can't destroy bitrate list mutex: %s", strerror (rc));
158 }
159 
bitrate_list_add(struct bitrate_list * b,const int time,const int bitrate)160 static void bitrate_list_add (struct bitrate_list *b, const int time,
161 		const int bitrate)
162 {
163 	assert (b != NULL);
164 
165 	LOCK (b->mutex);
166 	if (!b->tail) {
167 		b->head = b->tail = (struct bitrate_list_node *)xmalloc (
168 				sizeof(struct bitrate_list_node));
169 		b->tail->next = NULL;
170 		b->tail->time = time;
171 		b->tail->bitrate = bitrate;
172 
173 		debug ("Adding bitrate %d at time %d", bitrate, time);
174 	}
175 	else if (b->tail->bitrate != bitrate && b->tail->time != time) {
176 		assert (b->tail->time < time);
177 
178 		b->tail->next = (struct bitrate_list_node *)xmalloc (
179 				sizeof(struct bitrate_list_node));
180 		b->tail = b->tail->next;
181 		b->tail->next = NULL;
182 		b->tail->time = time;
183 		b->tail->bitrate = bitrate;
184 
185 		debug ("Appending bitrate %d at time %d", bitrate, time);
186 	}
187 	else if (b->tail->bitrate == bitrate)
188 		debug ("Not adding bitrate %d at time %d because the bitrate"
189 				" hasn't changed", bitrate, time);
190 	else
191 		debug ("Not adding bitrate %d at time %d because it is for"
192 				" the same time as the last bitrate", bitrate, time);
193 	UNLOCK (b->mutex);
194 }
195 
bitrate_list_get(struct bitrate_list * b,const int time)196 static int bitrate_list_get (struct bitrate_list *b, const int time)
197 {
198 	int bitrate = -1;
199 
200 	assert (b != NULL);
201 
202 	LOCK (b->mutex);
203 	if (b->head) {
204 		while (b->head->next && b->head->next->time <= time) {
205 			struct bitrate_list_node *o = b->head;
206 
207 			b->head = o->next;
208 			debug ("Removing old bitrate %d for time %d", o->bitrate, o->time);
209 			free (o);
210 		}
211 
212 		bitrate = b->head->bitrate /*b->head->time + 1000*/;
213 		debug ("Getting bitrate for time %d (%d)", time, bitrate);
214 	}
215 	else {
216 		debug ("Getting bitrate for time %d (no bitrate information)", time);
217 		bitrate = -1;
218 	}
219 	UNLOCK (b->mutex);
220 
221 	return bitrate;
222 }
223 
update_time()224 static void update_time ()
225 {
226 	static int last_time = 0;
227 	int ctime = audio_get_time ();
228 
229 	if (ctime >= 0 && ctime != last_time) {
230 		last_time = ctime;
231 		ctime_change ();
232 		set_info_bitrate (bitrate_list_get (&bitrate_list, ctime));
233 	}
234 }
235 
precache_thread(void * data)236 static void *precache_thread (void *data)
237 {
238 	struct precache *precache = (struct precache *)data;
239 	int decoded;
240 	struct sound_params new_sound_params;
241 	struct decoder_error err;
242 
243 	precache->buf_fill = 0;
244 	precache->sound_params.channels = 0; /* mark that sound_params were not
245 						yet filled. */
246 	precache->decoded_time = 0.0;
247 	precache->f = get_decoder (precache->file);
248 	assert (precache->f != NULL);
249 
250 	precache->decoder_data = precache->f->open(precache->file);
251 	precache->f->get_error(precache->decoder_data, &err);
252 	if (err.type != ERROR_OK) {
253 		logit ("Failed to open the file for precache: %s", err.err);
254 		decoder_error_clear (&err);
255 		precache->f->close (precache->decoder_data);
256 		return NULL;
257 	}
258 
259 	audio_plist_set_time (precache->file,
260 			precache->f->get_duration(precache->decoder_data));
261 
262 	/* Stop at PCM_BUF_SIZE, because when we decode too much, there is no
263 	 * place where we can put the data that doesn't fit into the buffer. */
264 	while (precache->buf_fill < PCM_BUF_SIZE) {
265 		decoded = precache->f->decode (precache->decoder_data,
266 				precache->buf + precache->buf_fill,
267 				PCM_BUF_SIZE, &new_sound_params);
268 
269 		if (!decoded) {
270 
271 			/* EOF so fast? We can't pass this information
272 			 * in precache, so give up. */
273 			logit ("EOF when precaching.");
274 			precache->f->close (precache->decoder_data);
275 			return NULL;
276 		}
277 
278 		precache->f->get_error (precache->decoder_data, &err);
279 
280 		if (err.type == ERROR_FATAL) {
281 			logit ("Error reading file for precache: %s", err.err);
282 			decoder_error_clear (&err);
283 			precache->f->close (precache->decoder_data);
284 			return NULL;
285 		}
286 
287 		if (!precache->sound_params.channels)
288 			precache->sound_params = new_sound_params;
289 		else if (!sound_params_eq(precache->sound_params,
290 					new_sound_params)) {
291 
292 			/* There is no way to store sound with two different
293 			 * parameters in the buffer, give up with
294 			 * precaching. (this should never happen). */
295 			logit ("Sound parameters have changed when precaching.");
296 			decoder_error_clear (&err);
297 			precache->f->close (precache->decoder_data);
298 			return NULL;
299 		}
300 
301 		bitrate_list_add (&precache->bitrate_list,
302 				precache->decoded_time,
303 				precache->f->get_bitrate(
304 					precache->decoder_data));
305 
306 		precache->buf_fill += decoded;
307 		precache->decoded_time += decoded / (float)(sfmt_Bps(
308 					new_sound_params.fmt) *
309 				new_sound_params.rate *
310 				new_sound_params.channels);
311 
312 		if (err.type != ERROR_OK) {
313 			decoder_error_clear (&err);
314 			break; /* Don't lose the error message */
315 		}
316 	}
317 
318 	precache->ok = 1;
319 	logit ("Successfully precached file (%d bytes)", precache->buf_fill);
320 	return NULL;
321 }
322 
start_precache(struct precache * precache,const char * file)323 static void start_precache (struct precache *precache, const char *file)
324 {
325 	int rc;
326 
327 	assert (!precache->running);
328 	assert (file != NULL);
329 
330 	precache->file = xstrdup (file);
331 	bitrate_list_init (&precache->bitrate_list);
332 	logit ("Precaching file %s", file);
333 	precache->ok = 0;
334 	rc = pthread_create (&precache->tid, NULL, precache_thread, precache);
335 	if (rc != 0)
336 		logit ("Could not run precache thread: %s", strerror (rc));
337 	else
338 		precache->running = 1;
339 }
340 
precache_wait(struct precache * precache)341 static void precache_wait (struct precache *precache)
342 {
343 	int rc;
344 
345 	if (precache->running) {
346 		debug ("Waiting for precache thread...");
347 		rc = pthread_join (precache->tid, NULL);
348 		if (rc != 0)
349 			fatal ("pthread_join() for precache thread failed: %s",
350 			        strerror (rc));
351 		precache->running = 0;
352 		debug ("done");
353 	}
354 	else
355 		debug ("Precache thread is not running");
356 }
357 
precache_reset(struct precache * precache)358 static void precache_reset (struct precache *precache)
359 {
360 	assert (!precache->running);
361 	precache->ok = 0;
362 	if (precache->file) {
363 		free (precache->file);
364 		precache->file = NULL;
365 		bitrate_list_destroy (&precache->bitrate_list);
366 	}
367 }
368 
player_init()369 void player_init ()
370 {
371 	precache.file = NULL;
372 	precache.running = 0;
373 	precache.ok = 0;
374 }
375 
show_tags(const struct file_tags * tags)376 static void show_tags (const struct file_tags *tags)
377 {
378 	debug ("TAG[title]: %s", tags->title ? tags->title : "N/A");
379 	debug ("TAG[album]: %s", tags->album ? tags->album : "N/A");
380 	debug ("TAG[artist]: %s", tags->artist ? tags->artist : "N/A");
381 	debug ("TAG[track]: %d", tags->track);
382 }
383 
384 /* Update tags if tags from the decoder or the stream are available. */
update_tags(const struct decoder * f,void * decoder_data,struct io_stream * s)385 static void update_tags (const struct decoder *f, void *decoder_data,
386 		struct io_stream *s)
387 {
388 	char *stream_title = NULL;
389 	int tags_changed = 0;
390 	struct file_tags *new_tags;
391 
392 	new_tags = tags_new ();
393 
394 	LOCK (curr_tags_mut);
395 	if (f->current_tags && f->current_tags(decoder_data, new_tags)
396 			&& new_tags->title) {
397 		tags_changed = 1;
398 		tags_copy (curr_tags, new_tags);
399 		logit ("Tags change from the decoder");
400 		tags_source = TAGS_SOURCE_DECODER;
401 		show_tags (curr_tags);
402 	}
403 	else if (s && (stream_title = io_get_metadata_title(s))) {
404 		if (curr_tags && curr_tags->title
405 				&& tags_source == TAGS_SOURCE_DECODER) {
406 			logit ("New IO stream tags, ignored because there are "
407 					"decoder tags present");
408 			free (stream_title);
409 		}
410 		else {
411 			tags_clear (curr_tags);
412 			curr_tags->title = stream_title;
413 			show_tags (curr_tags);
414 			tags_changed = 1;
415 			logit ("New IO stream tags");
416 			tags_source = TAGS_SOURCE_METADATA;
417 		}
418 	}
419 
420 	if (tags_changed)
421 		tags_change ();
422 
423 	tags_free (new_tags);
424 
425 	UNLOCK (curr_tags_mut);
426 }
427 
428 /* Called when some free space in the output buffer appears. */
buf_free_callback()429 static void buf_free_callback ()
430 {
431 	LOCK (request_cond_mutex);
432 	pthread_cond_broadcast (&request_cond);
433 	UNLOCK (request_cond_mutex);
434 
435 	update_time ();
436 }
437 
438 /* Decoder loop for already opened and probably running for some time decoder.
439  * next_file will be precached at eof. */
decode_loop(const struct decoder * f,void * decoder_data,const char * next_file,struct out_buf * out_buf,struct sound_params * sound_params,struct md5_data * md5,const float already_decoded_sec)440 static void decode_loop (const struct decoder *f, void *decoder_data,
441 		const char *next_file, struct out_buf *out_buf,
442 		struct sound_params *sound_params, struct md5_data *md5,
443 		const float already_decoded_sec)
444 {
445 	bool eof = false;
446 	bool stopped = false;
447 	char buf[PCM_BUF_SIZE];
448 	int decoded = 0;
449 	struct sound_params new_sound_params;
450 	bool sound_params_change = false;
451 	float decode_time = already_decoded_sec; /* the position of the decoder
452 	                                            (in seconds) */
453 
454 	out_buf_set_free_callback (out_buf, buf_free_callback);
455 
456 	LOCK (curr_tags_mut);
457 	curr_tags = tags_new ();
458 	UNLOCK (curr_tags_mut);
459 
460 	if (f->get_stream) {
461 		LOCK (decoder_stream_mut);
462 		decoder_stream = f->get_stream (decoder_data);
463 		UNLOCK (decoder_stream_mut);
464 	}
465 	else
466 		logit ("No get_stream() function");
467 
468 	status_msg ("Playing...");
469 
470 	while (1) {
471 		debug ("loop...");
472 
473 		LOCK (request_cond_mutex);
474 		if (!eof && !decoded) {
475 			struct decoder_error err;
476 
477 			UNLOCK (request_cond_mutex);
478 
479 			if (decoder_stream && out_buf_get_fill(out_buf)
480 					< PREBUFFER_THRESHOLD) {
481 				prebuffering = 1;
482 				io_prebuffer (decoder_stream,
483 						options_get_int("Prebuffering")
484 						* 1024);
485 				prebuffering = 0;
486 				status_msg ("Playing...");
487 			}
488 
489 			decoded = f->decode (decoder_data, buf, sizeof(buf),
490 					&new_sound_params);
491 
492 			if (decoded)
493 				decode_time += decoded / (float)(sfmt_Bps(
494 							new_sound_params.fmt) *
495 						new_sound_params.rate *
496 						new_sound_params.channels);
497 
498 			f->get_error (decoder_data, &err);
499 			if (err.type != ERROR_OK) {
500 				md5->okay = false;
501 				if (err.type != ERROR_STREAM ||
502 				    options_get_bool ("ShowStreamErrors"))
503 					error ("%s", err.err);
504 				decoder_error_clear (&err);
505 			}
506 
507 			if (!decoded) {
508 				eof = true;
509 				logit ("EOF from decoder");
510 			}
511 			else {
512 				debug ("decoded %d bytes", decoded);
513 				if (!sound_params_eq(new_sound_params, *sound_params))
514 					sound_params_change = true;
515 
516 				bitrate_list_add (&bitrate_list, decode_time,
517 						f->get_bitrate(decoder_data));
518 				update_tags (f, decoder_data, decoder_stream);
519 			}
520 		}
521 
522 		/* Wait, if there is no space in the buffer to put the decoded
523 		 * data or EOF occurred and there is something in the buffer. */
524 		else if (decoded > out_buf_get_free(out_buf)
525 					|| (eof && out_buf_get_fill(out_buf))) {
526 			debug ("waiting...");
527 			if (eof && !precache.file && next_file
528 					&& file_type(next_file) == F_SOUND
529 					&& options_get_int("Precache")
530 					&& options_get_bool("AutoNext"))
531 				start_precache (&precache, next_file);
532 			pthread_cond_wait (&request_cond, &request_cond_mutex);
533 			UNLOCK (request_cond_mutex);
534 		}
535 		else
536 			UNLOCK (request_cond_mutex);
537 
538 		/* When clearing request, we must make sure, that another
539 		 * request will not arrive at the moment, so we check if
540 		 * the request has changed. */
541 		if (request == REQ_STOP) {
542 			logit ("stop");
543 			stopped = true;
544 			md5->okay = false;
545 			out_buf_stop (out_buf);
546 
547 			LOCK (request_cond_mutex);
548 			if (request == REQ_STOP)
549 				request = REQ_NOTHING;
550 			UNLOCK (request_cond_mutex);
551 
552 			break;
553 		}
554 		else if (request == REQ_SEEK) {
555 			int decoder_seek;
556 
557 			logit ("seeking");
558 			md5->okay = false;
559 			req_seek = MAX(0, req_seek);
560 			if ((decoder_seek = f->seek(decoder_data, req_seek)) == -1)
561 				logit ("error when seeking");
562 			else {
563 				out_buf_stop (out_buf);
564 				out_buf_reset (out_buf);
565 				out_buf_time_set (out_buf, decoder_seek);
566 				bitrate_list_empty (&bitrate_list);
567 				decode_time = decoder_seek;
568 				eof = false;
569 				decoded = 0;
570 			}
571 
572 			LOCK (request_cond_mutex);
573 			if (request == REQ_SEEK)
574 				request = REQ_NOTHING;
575 			UNLOCK (request_cond_mutex);
576 
577 		}
578 		else if (!eof && decoded <= out_buf_get_free(out_buf)
579 				&& !sound_params_change) {
580 			debug ("putting into the buffer %d bytes", decoded);
581 #if !defined(NDEBUG) && defined(DEBUG)
582 			if (md5->okay) {
583 				md5->len += decoded;
584 				md5_process_bytes (buf, decoded, &md5->ctx);
585 			}
586 #endif
587 			audio_send_buf (buf, decoded);
588 			decoded = 0;
589 		}
590 		else if (!eof && sound_params_change
591 				&& out_buf_get_fill(out_buf) == 0) {
592 			logit ("Sound parameters have changed.");
593 			*sound_params = new_sound_params;
594 			sound_params_change = false;
595 			set_info_channels (sound_params->channels);
596 			set_info_rate (sound_params->rate / 1000);
597 			out_buf_wait (out_buf);
598 			if (!audio_open(sound_params)) {
599 				md5->okay = false;
600 				break;
601 			}
602 		}
603 		else if (eof && out_buf_get_fill(out_buf) == 0) {
604 			logit ("played everything");
605 			break;
606 		}
607 	}
608 
609 	status_msg ("");
610 
611 	LOCK (decoder_stream_mut);
612 	decoder_stream = NULL;
613 	f->close (decoder_data);
614 	UNLOCK (decoder_stream_mut);
615 
616 	bitrate_list_destroy (&bitrate_list);
617 
618 	LOCK (curr_tags_mut);
619 	if (curr_tags) {
620 		tags_free (curr_tags);
621 		curr_tags = NULL;
622 	}
623 	UNLOCK (curr_tags_mut);
624 
625 	out_buf_wait (out_buf);
626 
627 	if (precache.ok && (stopped || !options_get_bool ("AutoNext"))) {
628 		precache_wait (&precache);
629 		precache.f->close (precache.decoder_data);
630 		precache_reset (&precache);
631 	}
632 }
633 
634 #if !defined(NDEBUG) && defined(DEBUG)
log_md5_sum(const char * file,struct sound_params sound_params,const struct decoder * f,uint8_t * md5,long md5_len)635 static void log_md5_sum (const char *file, struct sound_params sound_params,
636                          const struct decoder *f, uint8_t *md5, long md5_len)
637 {
638 	unsigned int ix, bps;
639 	char md5sum[MD5_DIGEST_SIZE * 2 + 1], format;
640 	const char *fn, *endian;
641 
642 	for (ix = 0; ix < MD5_DIGEST_SIZE; ix += 1)
643 		sprintf (&md5sum[ix * 2], "%02x", md5[ix]);
644 	md5sum[MD5_DIGEST_SIZE * 2] = 0x00;
645 
646 	switch (sound_params.fmt & SFMT_MASK_FORMAT) {
647 	case SFMT_S8:
648 	case SFMT_S16:
649 	case SFMT_S32:
650 		format = 's';
651 		break;
652 	case SFMT_U8:
653 	case SFMT_U16:
654 	case SFMT_U32:
655 		format = 'u';
656 		break;
657 	case SFMT_FLOAT:
658 		format = 'f';
659 		break;
660 	default:
661 		debug ("Unknown sound format: 0x%04lx", sound_params.fmt);
662 		return;
663 	}
664 
665 	bps = sfmt_Bps (sound_params.fmt) * 8;
666 
667 	endian = "";
668 	if (format != 'f' && bps != 8) {
669 		if (sound_params.fmt & SFMT_LE)
670 			endian = "le";
671 		else if (sound_params.fmt & SFMT_BE)
672 			endian = "be";
673 	}
674 
675 	fn = strrchr (file, '/');
676 	fn = fn ? fn + 1 : file;
677 	debug ("MD5(%s) = %s %ld %s %c%u%s %d %d",
678 	        fn, md5sum, md5_len, get_decoder_name (f),
679 	        format, bps, endian,
680 	        sound_params.channels, sound_params.rate);
681 }
682 #endif
683 
684 /* Play a file (disk file) using the given decoder. next_file is precached. */
play_file(const char * file,const struct decoder * f,const char * next_file,struct out_buf * out_buf)685 static void play_file (const char *file, const struct decoder *f,
686 		const char *next_file, struct out_buf *out_buf)
687 {
688 	void *decoder_data;
689 	struct sound_params sound_params = { 0, 0, 0 };
690 	float already_decoded_time;
691 	struct md5_data md5;
692 
693 #if !defined(NDEBUG) && defined(DEBUG)
694 	md5.okay = true;
695 	md5.len = 0;
696 	md5_init_ctx (&md5.ctx);
697 #endif
698 
699 	out_buf_reset (out_buf);
700 
701 	precache_wait (&precache);
702 
703 	if (precache.ok && strcmp(precache.file, file)) {
704 		logit ("The precached file is not the file we want.");
705 		precache.f->close (precache.decoder_data);
706 		precache_reset (&precache);
707 	}
708 
709 	if (precache.ok && !strcmp(precache.file, file)) {
710 		struct decoder_error err;
711 
712 		logit ("Using precached file");
713 
714 		assert (f == precache.f);
715 
716 		sound_params = precache.sound_params;
717 		decoder_data = precache.decoder_data;
718 		set_info_channels (sound_params.channels);
719 		set_info_rate (sound_params.rate / 1000);
720 
721 		if (!audio_open(&sound_params)) {
722 			md5.okay = false;
723 			precache.f->close (precache.decoder_data);
724 			precache_reset (&precache);
725 			return;
726 		}
727 
728 #if !defined(NDEBUG) && defined(DEBUG)
729 		md5.len += precache.buf_fill;
730 		md5_process_bytes (precache.buf, precache.buf_fill, &md5.ctx);
731 #endif
732 
733 		audio_send_buf (precache.buf, precache.buf_fill);
734 
735 		precache.f->get_error (precache.decoder_data, &err);
736 		if (err.type != ERROR_OK) {
737 			md5.okay = false;
738 			if (err.type != ERROR_STREAM ||
739 			    options_get_bool ("ShowStreamErrors"))
740 				error ("%s", err.err);
741 			decoder_error_clear (&err);
742 		}
743 
744 		already_decoded_time = precache.decoded_time;
745 
746 		if(f->get_avg_bitrate)
747 			set_info_avg_bitrate (f->get_avg_bitrate(decoder_data));
748 		else
749 			set_info_avg_bitrate (0);
750 
751 		bitrate_list_init (&bitrate_list);
752 		bitrate_list.head = precache.bitrate_list.head;
753 		bitrate_list.tail = precache.bitrate_list.tail;
754 
755 		/* don't free list elements when resetting precache */
756 		precache.bitrate_list.head = NULL;
757 		precache.bitrate_list.tail = NULL;
758 	}
759 	else {
760 		struct decoder_error err;
761 
762 		status_msg ("Opening...");
763 		decoder_data = f->open(file);
764 		f->get_error (decoder_data, &err);
765 		if (err.type != ERROR_OK) {
766 			f->close (decoder_data);
767 			status_msg ("");
768 			error ("%s", err.err);
769 			decoder_error_clear (&err);
770 			logit ("Can't open file, exiting");
771 			return;
772 		}
773 
774 		already_decoded_time = 0.0;
775 		if (f->get_avg_bitrate)
776 			set_info_avg_bitrate (f->get_avg_bitrate(decoder_data));
777 		bitrate_list_init (&bitrate_list);
778 	}
779 
780 	audio_plist_set_time (file, f->get_duration(decoder_data));
781 	audio_state_started_playing ();
782 	precache_reset (&precache);
783 
784 	decode_loop (f, decoder_data, next_file, out_buf, &sound_params,
785 			&md5, already_decoded_time);
786 
787 #if !defined(NDEBUG) && defined(DEBUG)
788 	if (md5.okay) {
789 		uint8_t buf[MD5_DIGEST_SIZE];
790 
791 		md5_finish_ctx (&md5.ctx, buf);
792 		log_md5_sum (file, sound_params, f, buf, md5.len);
793 	}
794 #endif
795 }
796 
797 /* Play the stream (global decoder_stream) using the given decoder. */
play_stream(const struct decoder * f,struct out_buf * out_buf)798 static void play_stream (const struct decoder *f, struct out_buf *out_buf)
799 {
800 	void *decoder_data;
801 	struct sound_params sound_params = { 0, 0, 0 };
802 	struct decoder_error err;
803 	struct md5_data null_md5;
804 
805 	null_md5.okay = false;
806 	out_buf_reset (out_buf);
807 
808 	assert (f->open_stream != NULL);
809 
810 	decoder_data = f->open_stream (decoder_stream);
811 	f->get_error (decoder_data, &err);
812 	if (err.type != ERROR_OK) {
813 		LOCK (decoder_stream_mut);
814 		decoder_stream = NULL;
815 		UNLOCK (decoder_stream_mut);
816 
817 		f->close (decoder_data);
818 		error ("%s", err.err);
819 		status_msg ("");
820 		decoder_error_clear (&err);
821 		logit ("Can't open file");
822 	}
823 	else {
824 		audio_state_started_playing ();
825 		bitrate_list_init (&bitrate_list);
826 		decode_loop (f, decoder_data, NULL, out_buf, &sound_params,
827 				&null_md5, 0.0);
828 	}
829 }
830 
831 /* Callback for io buffer fill - show the prebuffering state. */
fill_callback(struct io_stream * s ATTR_UNUSED,size_t fill,size_t buf_size ATTR_UNUSED,void * data_ptr ATTR_UNUSED)832 static void fill_callback (struct io_stream *s ATTR_UNUSED, size_t fill,
833 		size_t buf_size ATTR_UNUSED, void *data_ptr ATTR_UNUSED)
834 {
835 	if (prebuffering) {
836 		char msg[32];
837 
838 		sprintf (msg, "Prebuffering %zu/%d KB", fill / 1024U,
839 		              options_get_int("Prebuffering"));
840 		status_msg (msg);
841 	}
842 }
843 
844 /* Open a file, decode it and put output into the buffer. At the end, start
845  * precaching next_file. */
player(const char * file,const char * next_file,struct out_buf * out_buf)846 void player (const char *file, const char *next_file, struct out_buf *out_buf)
847 {
848 	struct decoder *f;
849 
850 	if (file_type(file) == F_URL) {
851 		status_msg ("Connecting...");
852 
853 		LOCK (decoder_stream_mut);
854 		decoder_stream = io_open (file, 1);
855 		if (!io_ok(decoder_stream)) {
856 			error ("Could not open URL: %s", io_strerror(decoder_stream));
857 			io_close (decoder_stream);
858 			status_msg ("");
859 			decoder_stream = NULL;
860 			UNLOCK (decoder_stream_mut);
861 			return;
862 		}
863 		UNLOCK (decoder_stream_mut);
864 
865 		f = get_decoder_by_content (decoder_stream);
866 		if (!f) {
867 			LOCK (decoder_stream_mut);
868 			io_close (decoder_stream);
869 			status_msg ("");
870 			decoder_stream = NULL;
871 			UNLOCK (decoder_stream_mut);
872 			return;
873 		}
874 
875 		status_msg ("Prebuffering...");
876 		prebuffering = 1;
877 		io_set_buf_fill_callback (decoder_stream, fill_callback, NULL);
878 		io_prebuffer (decoder_stream,
879 				options_get_int("Prebuffering") * 1024);
880 		prebuffering = 0;
881 
882 		status_msg ("Playing...");
883 		ev_audio_start ();
884 		play_stream (f, out_buf);
885 		ev_audio_stop ();
886 	}
887 	else {
888 		f = get_decoder (file);
889 		LOCK (decoder_stream_mut);
890 		decoder_stream = NULL;
891 		UNLOCK (decoder_stream_mut);
892 
893 		if (!f) {
894 			error ("Can't get decoder for %s", file);
895 			return;
896 		}
897 
898 		ev_audio_start ();
899 		play_file (file, f, next_file, out_buf);
900 		ev_audio_stop ();
901 	}
902 
903 	logit ("exiting");
904 }
905 
player_cleanup()906 void player_cleanup ()
907 {
908 	int rc;
909 
910 	rc = pthread_mutex_destroy (&request_cond_mutex);
911 	if (rc != 0)
912 		logit ("Can't destroy request mutex: %s", strerror (rc));
913 	rc = pthread_mutex_destroy (&curr_tags_mut);
914 	if (rc != 0)
915 		logit ("Can't destroy tags mutex: %s", strerror (rc));
916 	rc = pthread_mutex_destroy (&decoder_stream_mut);
917 	if (rc != 0)
918 		logit ("Can't destroy decoder_stream mutex: %s", strerror (rc));
919 	rc = pthread_cond_destroy (&request_cond);
920 	if (rc != 0)
921 		logit ("Can't destroy request condition: %s", strerror (rc));
922 
923 	precache_wait (&precache);
924 	precache_reset (&precache);
925 }
926 
player_reset()927 void player_reset ()
928 {
929 	request = REQ_NOTHING;
930 }
931 
player_stop()932 void player_stop ()
933 {
934 	logit ("requesting stop");
935 	request = REQ_STOP;
936 
937 	LOCK (decoder_stream_mut);
938 	if (decoder_stream) {
939 		logit ("decoder_stream present, aborting...");
940 		io_abort (decoder_stream);
941 	}
942 	UNLOCK (decoder_stream_mut);
943 
944 	LOCK (request_cond_mutex);
945 	pthread_cond_signal (&request_cond);
946 	UNLOCK (request_cond_mutex);
947 }
948 
player_seek(const int sec)949 void player_seek (const int sec)
950 {
951 	int time;
952 
953 	time = audio_get_time ();
954 	if (time >= 0) {
955 		request = REQ_SEEK;
956 		req_seek = sec + time;
957 		LOCK (request_cond_mutex);
958 		pthread_cond_signal (&request_cond);
959 		UNLOCK (request_cond_mutex);
960 	}
961 }
962 
player_jump_to(const int sec)963 void player_jump_to (const int sec)
964 {
965 	request = REQ_SEEK;
966 	req_seek = sec;
967 	LOCK (request_cond_mutex);
968 	pthread_cond_signal (&request_cond);
969 	UNLOCK (request_cond_mutex);
970 }
971 
972 /* Stop playing, clear the output buffer, but allow to unpause by starting
973  * playing the same stream. This is usefull for internet streams that can't
974  * be really paused. */
player_pause()975 void player_pause ()
976 {
977 	request = REQ_PAUSE;
978 	LOCK (request_cond_mutex);
979 	pthread_cond_signal (&request_cond);
980 	UNLOCK (request_cond_mutex);
981 }
982 
player_unpause()983 void player_unpause ()
984 {
985 	request = REQ_UNPAUSE;
986 	LOCK (request_cond_mutex);
987 	pthread_cond_signal (&request_cond);
988 	UNLOCK (request_cond_mutex);
989 }
990 
991 /* Return tags for the currently played file or NULL if there are no tags.
992  * Tags are duplicated. */
player_get_curr_tags()993 struct file_tags *player_get_curr_tags ()
994 {
995 	struct file_tags *tags;
996 
997 	LOCK (curr_tags_mut);
998 	if (curr_tags)
999 		tags = tags_dup (curr_tags);
1000 	else
1001 		tags = NULL;
1002 	UNLOCK (curr_tags_mut);
1003 
1004 	return tags;
1005 }
1006