xref: /reactos/sdk/lib/3rdparty/libmpg123/readers.c (revision d7fd62d4)
1 /* TODO: Check all read calls (in loops, especially!) for return value 0 (EOF)! */
2 /* Check if get_fileinfo should read ID3 info or not, seems a bit out of place here. */
3 /* #define EXTRA_DEBUG */
4 /*
5 	readers.c: reading input data
6 
7 	copyright ?-2020 by the mpg123 project - free software under the terms of the LGPL 2.1
8 	see COPYING and AUTHORS files in distribution or http://mpg123.org
9 	initially written by Michael Hipp
10 */
11 
12 #include "mpg123lib_intern.h"
13 #include <sys/stat.h>
14 #include <fcntl.h>
15 #include <errno.h>
16 /* For select(), I need select.h according to POSIX 2001, else: sys/time.h sys/types.h unistd.h (the latter two included in compat.h already). */
17 #ifdef HAVE_SYS_SELECT_H
18 #include <sys/select.h>
19 #endif
20 #ifdef HAVE_SYS_TIME_H
21 #include <sys/time.h>
22 #endif
23 #ifdef _MSC_VER
24 #include <io.h>
25 #endif
26 
27 #include "compat.h"
28 #include "debug.h"
29 
30 static int default_init(mpg123_handle *fr);
31 static off_t get_fileinfo(mpg123_handle *);
32 static ssize_t posix_read(int fd, void *buf, size_t count){ return read(fd, buf, count); }
33 static off_t   posix_lseek(int fd, off_t offset, int whence){ return lseek(fd, offset, whence); }
34 static off_t     nix_lseek(int fd, off_t offset, int whence){ return -1; }
35 
36 static ssize_t plain_fullread(mpg123_handle *fr,unsigned char *buf, ssize_t count);
37 
38 /* Wrapper to decide between descriptor-based and external handle-based I/O. */
39 static off_t io_seek(struct reader_data *rdat, off_t offset, int whence);
40 static ssize_t io_read(struct reader_data *rdat, void *buf, size_t count);
41 
42 #ifndef NO_FEEDER
43 /* Bufferchain methods. */
44 static void bc_init(struct bufferchain *bc);
45 static void bc_reset(struct bufferchain *bc);
46 static int bc_append(struct bufferchain *bc, ssize_t size);
47 #if 0
48 static void bc_drop(struct bufferchain *bc);
49 #endif
50 static int bc_add(struct bufferchain *bc, const unsigned char *data, ssize_t size);
51 static ssize_t bc_give(struct bufferchain *bc, unsigned char *out, ssize_t size);
52 static ssize_t bc_skip(struct bufferchain *bc, ssize_t count);
53 static ssize_t bc_seekback(struct bufferchain *bc, ssize_t count);
54 static void bc_forget(struct bufferchain *bc);
55 #endif
56 
57 /* A normal read and a read with timeout. */
58 static ssize_t plain_read(mpg123_handle *fr, void *buf, size_t count)
59 {
60 	ssize_t ret = io_read(&fr->rdat, buf, count);
61 	if(VERBOSE3) debug2("read %li bytes of %li", (long)ret, (long)count);
62 	return ret;
63 }
64 
65 #ifdef TIMEOUT_READ
66 
67 /* Wait for data becoming available, allowing soft-broken network connection to die
68    This is needed for Shoutcast servers that have forgotten about us while connection was temporarily down. */
69 static ssize_t timeout_read(mpg123_handle *fr, void *buf, size_t count)
70 {
71 	struct timeval tv;
72 	ssize_t ret = 0;
73 	fd_set fds;
74 	tv.tv_sec = fr->rdat.timeout_sec;
75 	tv.tv_usec = 0;
76 	FD_ZERO(&fds);
77 	FD_SET(fr->rdat.filept, &fds);
78 	ret = select(fr->rdat.filept+1, &fds, NULL, NULL, &tv);
79 	/* This works only with "my" read function. Not user-replaced. */
80 	if(ret > 0) ret = read(fr->rdat.filept, buf, count);
81 	else
82 	{
83 		ret=-1; /* no activity is the error */
84 		if(NOQUIET) error("stream timed out");
85 	}
86 	return ret;
87 }
88 #endif
89 
90 #ifndef NO_ICY
91 /* stream based operation  with icy meta data*/
92 static ssize_t icy_fullread(mpg123_handle *fr, unsigned char *buf, ssize_t count)
93 {
94 	ssize_t ret,cnt;
95 	cnt = 0;
96 	if(fr->rdat.flags & READER_SEEKABLE)
97 	{
98 		if(NOQUIET) error("mpg123 programmer error: I don't do ICY on seekable streams.");
99 		return -1;
100 	}
101 	/*
102 		There used to be a check for expected file end here (length value or ID3 flag).
103 		This is not needed:
104 		1. EOF is indicated by fdread returning zero bytes anyway.
105 		2. We get false positives of EOF for either files that grew or
106 		3. ... files that have ID3v1 tags in between (stream with intro).
107 	*/
108 
109 	while(cnt < count)
110 	{
111 		/* all icy code is inside this if block, everything else is the plain fullread we know */
112 		/* debug1("read: %li left", (long) count-cnt); */
113 		if(fr->icy.next < count-cnt)
114 		{
115 			unsigned char temp_buff;
116 			size_t meta_size;
117 			ssize_t cut_pos;
118 
119 			/* we are near icy-metaint boundary, read up to the boundary */
120 			if(fr->icy.next > 0)
121 			{
122 				cut_pos = fr->icy.next;
123 				ret = fr->rdat.fdread(fr,buf+cnt,cut_pos);
124 				if(ret < 1)
125 				{
126 					if(ret == 0) break; /* Just EOF. */
127 					if(NOQUIET) error("icy boundary read");
128 
129 					return READER_ERROR;
130 				}
131 
132 				if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;
133 				cnt += ret;
134 				fr->icy.next -= ret;
135 				if(fr->icy.next > 0)
136 				{
137 					debug1("another try... still %li left", (long)fr->icy.next);
138 					continue;
139 				}
140 			}
141 			/* now off to read icy data */
142 
143 			/* one byte icy-meta size (must be multiplied by 16 to get icy-meta length) */
144 
145 			ret = fr->rdat.fdread(fr,&temp_buff,1); /* Getting one single byte hast to suceed. */
146 			if(ret < 0){ if(NOQUIET) error("reading icy size"); return READER_ERROR; }
147 			if(ret == 0) break;
148 
149 			debug2("got meta-size byte: %u, at filepos %li", temp_buff, (long)fr->rdat.filepos );
150 			if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret; /* 1... */
151 
152 			if((meta_size = ((size_t) temp_buff) * 16))
153 			{
154 				/* we have got some metadata */
155 				char *meta_buff;
156 				/* TODO: Get rid of this malloc ... perhaps hooking into the reader buffer pool? */
157 				meta_buff = malloc(meta_size+1);
158 				if(meta_buff != NULL)
159 				{
160 					ssize_t left = meta_size;
161 					while(left > 0)
162 					{
163 						ret = fr->rdat.fdread(fr,meta_buff+meta_size-left,left);
164 						/* 0 is error here, too... there _must_ be the ICY data, the server promised! */
165 						if(ret < 1){ if(NOQUIET) error("reading icy-meta"); return READER_ERROR; }
166 						left -= ret;
167 					}
168 					meta_buff[meta_size] = 0; /* string paranoia */
169 					if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;
170 
171 					if(fr->icy.data) free(fr->icy.data);
172 					fr->icy.data = meta_buff;
173 					fr->metaflags |= MPG123_NEW_ICY;
174 					debug2("icy-meta: %s size: %d bytes", fr->icy.data, (int)meta_size);
175 				}
176 				else
177 				{
178 					if(NOQUIET) error1("cannot allocate memory for meta_buff (%lu bytes) ... trying to skip the metadata!", (unsigned long)meta_size);
179 					fr->rd->skip_bytes(fr, meta_size);
180 				}
181 			}
182 			fr->icy.next = fr->icy.interval;
183 		}
184 		else
185 		{
186 			ret = plain_fullread(fr, buf+cnt, count-cnt);
187 			if(ret < 0){ if(NOQUIET) error1("reading the rest of %li", (long)(count-cnt)); return READER_ERROR; }
188 			if(ret == 0) break;
189 
190 			cnt += ret;
191 			fr->icy.next -= ret;
192 		}
193 	}
194 	/* debug1("done reading, got %li", (long)cnt); */
195 	return cnt;
196 }
197 #else
198 #define icy_fullread NULL
199 #endif /* NO_ICY */
200 
201 /* stream based operation */
202 static ssize_t plain_fullread(mpg123_handle *fr,unsigned char *buf, ssize_t count)
203 {
204 	ssize_t ret,cnt=0;
205 
206 #ifdef EXTRA_DEBUG
207 	debug1("plain fullread of %"SSIZE_P, (size_p)count);
208 #endif
209 	/*
210 		There used to be a check for expected file end here (length value or ID3 flag).
211 		This is not needed:
212 		1. EOF is indicated by fdread returning zero bytes anyway.
213 		2. We get false positives of EOF for either files that grew or
214 		3. ... files that have ID3v1 tags in between (stream with intro).
215 	*/
216 	while(cnt < count)
217 	{
218 		ret = fr->rdat.fdread(fr,buf+cnt,count-cnt);
219 		if(ret < 0) return READER_ERROR;
220 		if(ret == 0) break;
221 		if(!(fr->rdat.flags & READER_BUFFERED)) fr->rdat.filepos += ret;
222 		cnt += ret;
223 	}
224 	return cnt;
225 }
226 
227 static off_t stream_lseek(mpg123_handle *fr, off_t pos, int whence)
228 {
229 	off_t ret;
230 	ret = io_seek(&fr->rdat, pos, whence);
231 	if (ret >= 0)	fr->rdat.filepos = ret;
232 	else
233 	{
234 		fr->err = MPG123_LSEEK_FAILED;
235 		ret = READER_ERROR; /* not the original value */
236 	}
237 	return ret;
238 }
239 
240 static void stream_close(mpg123_handle *fr)
241 {
242 	if(fr->rdat.flags & READER_FD_OPENED) compat_close(fr->rdat.filept);
243 
244 	fr->rdat.filept = 0;
245 
246 #ifndef NO_FEEDER
247 	if(fr->rdat.flags & READER_BUFFERED)  bc_reset(&fr->rdat.buffer);
248 #endif
249 	if(fr->rdat.flags & READER_HANDLEIO)
250 	{
251 		if(fr->rdat.cleanup_handle != NULL) fr->rdat.cleanup_handle(fr->rdat.iohandle);
252 
253 		fr->rdat.iohandle = NULL;
254 	}
255 }
256 
257 static int stream_seek_frame(mpg123_handle *fr, off_t newframe)
258 {
259 	debug2("seek_frame to %"OFF_P" (from %"OFF_P")", (off_p)newframe, (off_p)fr->num);
260 	/* Seekable streams can go backwards and jump forwards.
261 	   Non-seekable streams still can go forward, just not jump. */
262 	if((fr->rdat.flags & READER_SEEKABLE) || (newframe >= fr->num))
263 	{
264 		off_t preframe; /* a leading frame we jump to */
265 		off_t seek_to;  /* the byte offset we want to reach */
266 		off_t to_skip;  /* bytes to skip to get there (can be negative) */
267 		/*
268 			now seek to nearest leading index position and read from there until newframe is reached.
269 			We use skip_bytes, which handles seekable and non-seekable streams
270 			(the latter only for positive offset, which we ensured before entering here).
271 		*/
272 		seek_to = frame_index_find(fr, newframe, &preframe);
273 		/* No need to seek to index position if we are closer already.
274 		   But I am picky about fr->num == newframe, play safe by reading the frame again.
275 		   If you think that's stupid, don't call a seek to the current frame. */
276 		if(fr->num >= newframe || fr->num < preframe)
277 		{
278 			to_skip = seek_to - fr->rd->tell(fr);
279 			if(fr->rd->skip_bytes(fr, to_skip) != seek_to)
280 			return READER_ERROR;
281 
282 			debug2("going to %lu; just got %lu", (long unsigned)newframe, (long unsigned)preframe);
283 			fr->num = preframe-1; /* Watch out! I am going to read preframe... fr->num should indicate the frame before! */
284 		}
285 		while(fr->num < newframe)
286 		{
287 			/* try to be non-fatal now... frameNum only gets advanced on success anyway */
288 			if(!read_frame(fr)) break;
289 		}
290 		/* Now the wanted frame should be ready for decoding. */
291 		debug1("arrived at %lu", (long unsigned)fr->num);
292 
293 		return MPG123_OK;
294 	}
295 	else
296 	{
297 		fr->err = MPG123_NO_SEEK;
298 		return READER_ERROR; /* invalid, no seek happened */
299 	}
300 }
301 
302 /* return FALSE on error, TRUE on success, READER_MORE on occasion */
303 static int generic_head_read(mpg123_handle *fr,unsigned long *newhead)
304 {
305 	unsigned char hbuf[4];
306 	int ret = fr->rd->fullread(fr,hbuf,4);
307 	if(ret == READER_MORE) return ret;
308 	if(ret != 4) return FALSE;
309 
310 	*newhead = ((unsigned long) hbuf[0] << 24) |
311 	           ((unsigned long) hbuf[1] << 16) |
312 	           ((unsigned long) hbuf[2] << 8)  |
313 	            (unsigned long) hbuf[3];
314 
315 	return TRUE;
316 }
317 
318 /* return FALSE on error, TRUE on success, READER_MORE on occasion */
319 static int generic_head_shift(mpg123_handle *fr,unsigned long *head)
320 {
321 	unsigned char hbuf;
322 	int ret = fr->rd->fullread(fr,&hbuf,1);
323 	if(ret == READER_MORE) return ret;
324 	if(ret != 1) return FALSE;
325 
326 	*head <<= 8;
327 	*head |= hbuf;
328 	*head &= 0xffffffff;
329 	return TRUE;
330 }
331 
332 /* returns reached position... negative ones are bad... */
333 static off_t stream_skip_bytes(mpg123_handle *fr,off_t len)
334 {
335 	if(fr->rdat.flags & READER_SEEKABLE)
336 	{
337 		off_t ret = stream_lseek(fr, len, SEEK_CUR);
338 		return (ret < 0) ? READER_ERROR : ret;
339 	}
340 	else if(len >= 0)
341 	{
342 		unsigned char buf[1024]; /* ThOr: Compaq cxx complained and it makes sense to me... or should one do a cast? What for? */
343 		ssize_t ret;
344 		while (len > 0)
345 		{
346 			ssize_t num = len < (off_t)sizeof(buf) ? (ssize_t)len : (ssize_t)sizeof(buf);
347 			ret = fr->rd->fullread(fr, buf, num);
348 			if (ret < 0) return ret;
349 			else if(ret == 0) break; /* EOF... an error? interface defined to tell the actual position... */
350 			len -= ret;
351 		}
352 		return fr->rd->tell(fr);
353 	}
354 #ifndef NO_FEEDER
355 	else if(fr->rdat.flags & READER_BUFFERED)
356 	{ /* Perhaps we _can_ go a bit back. */
357 		if(fr->rdat.buffer.pos >= -len)
358 		{
359 			fr->rdat.buffer.pos += len;
360 			return fr->rd->tell(fr);
361 		}
362 		else
363 		{
364 			fr->err = MPG123_NO_SEEK;
365 			return READER_ERROR;
366 		}
367 	}
368 #endif
369 	else
370 	{
371 		fr->err = MPG123_NO_SEEK;
372 		return READER_ERROR;
373 	}
374 }
375 
376 /* Return 0 on success... */
377 static int stream_back_bytes(mpg123_handle *fr, off_t bytes)
378 {
379 	off_t want = fr->rd->tell(fr)-bytes;
380 	if(want < 0) return READER_ERROR;
381 	if(stream_skip_bytes(fr,-bytes) != want) return READER_ERROR;
382 
383 	return 0;
384 }
385 
386 
387 /* returns size on success... otherwise an error code < 0 */
388 static int generic_read_frame_body(mpg123_handle *fr,unsigned char *buf, int size)
389 {
390 	long l;
391 	l=fr->rd->fullread(fr,buf,size);
392 	return (l >= 0 && l<size) ? READER_ERROR : l;
393 }
394 
395 static off_t generic_tell(mpg123_handle *fr)
396 {
397 #ifndef NO_FEEDER
398 	if(fr->rdat.flags & READER_BUFFERED)
399 	fr->rdat.filepos = fr->rdat.buffer.fileoff+fr->rdat.buffer.pos;
400 #endif
401 
402 	return fr->rdat.filepos;
403 }
404 
405 /* This does not (fully) work for non-seekable streams... You have to check for that flag, pal! */
406 static void stream_rewind(mpg123_handle *fr)
407 {
408 	if(fr->rdat.flags & READER_SEEKABLE)
409 	{
410 		fr->rdat.filepos = stream_lseek(fr,0,SEEK_SET);
411 #ifndef NO_FEEDER
412 		fr->rdat.buffer.fileoff = fr->rdat.filepos;
413 #endif
414 	}
415 #ifndef NO_FEEDER
416 	if(fr->rdat.flags & READER_BUFFERED)
417 	{
418 		fr->rdat.buffer.pos      = 0;
419 		fr->rdat.buffer.firstpos = 0;
420 		fr->rdat.filepos = fr->rdat.buffer.fileoff;
421 	}
422 #endif
423 }
424 
425 /*
426  * returns length of a file (if filept points to a file)
427  * reads the last 128 bytes information into buffer
428  * ... that is not totally safe...
429  */
430 static off_t get_fileinfo(mpg123_handle *fr)
431 {
432 	off_t len;
433 
434 	if((len=io_seek(&fr->rdat,0,SEEK_END)) < 0)
435 	{
436 		debug("cannot seek to end");
437 		return -1;
438 	} else if(len >= 128)
439 	{
440 		if(io_seek(&fr->rdat,-128,SEEK_END) < 0)
441 		{
442 			debug("cannot seek to END-128");
443 			return -1;
444 		}
445 		if(fr->rd->fullread(fr,(unsigned char *)fr->id3buf,128) != 128)
446 		{
447 			debug("cannot read ID3v1?!");
448 			return -1;
449 		}
450 		if(!strncmp((char*)fr->id3buf,"TAG",3)) len -= 128;
451 	} else
452 	{
453 		debug("stream too short for ID3");
454 	}
455 
456 	if(io_seek(&fr->rdat,0,SEEK_SET) < 0)
457 	{
458 		debug("cannot seek back");
459 		return -1;
460 	}
461 
462 	debug1("returning length: %"OFF_P, (off_p)len);
463 	return len;
464 }
465 
466 #ifndef NO_FEEDER
467 /* Methods for the buffer chain, mainly used for feed reader, but not just that. */
468 
469 
470 static struct buffy* buffy_new(size_t size, size_t minsize)
471 {
472 	struct buffy *newbuf;
473 	newbuf = malloc(sizeof(struct buffy));
474 	if(newbuf == NULL) return NULL;
475 
476 	newbuf->realsize = size > minsize ? size : minsize;
477 	newbuf->data = malloc(newbuf->realsize);
478 	if(newbuf->data == NULL)
479 	{
480 		free(newbuf);
481 		return NULL;
482 	}
483 	newbuf->size = 0;
484 	newbuf->next = NULL;
485 	return newbuf;
486 }
487 
488 static void buffy_del(struct buffy* buf)
489 {
490 	if(buf)
491 	{
492 		free(buf->data);
493 		free(buf);
494 	}
495 }
496 
497 /* Delete this buffy and all following buffies. */
498 static void buffy_del_chain(struct buffy* buf)
499 {
500 	while(buf)
501 	{
502 		struct buffy* next = buf->next;
503 		buffy_del(buf);
504 		buf = next;
505 	}
506 }
507 
508 void bc_prepare(struct bufferchain *bc, size_t pool_size, size_t bufblock)
509 {
510 	bc_poolsize(bc, pool_size, bufblock);
511 	bc->pool = NULL;
512 	bc->pool_fill = 0;
513 	bc_init(bc); /* Ensure that members are zeroed for read-only use. */
514 }
515 
516 size_t bc_fill(struct bufferchain *bc)
517 {
518 	return (size_t)(bc->size - bc->pos);
519 }
520 
521 void bc_poolsize(struct bufferchain *bc, size_t pool_size, size_t bufblock)
522 {
523 	bc->pool_size = pool_size;
524 	bc->bufblock = bufblock;
525 }
526 
527 void bc_cleanup(struct bufferchain *bc)
528 {
529 	buffy_del_chain(bc->pool);
530 	bc->pool = NULL;
531 	bc->pool_fill = 0;
532 }
533 
534 /* Fetch a buffer from the pool (if possible) or create one. */
535 static struct buffy* bc_alloc(struct bufferchain *bc, size_t size)
536 {
537 	/* Easy route: Just try the first available buffer.
538 	   Size does not matter, it's only a hint for creation of new buffers. */
539 	if(bc->pool)
540 	{
541 		struct buffy *buf = bc->pool;
542 		bc->pool = buf->next;
543 		buf->next = NULL; /* That shall be set to a sensible value later. */
544 		buf->size = 0;
545 		--bc->pool_fill;
546 		debug2("bc_alloc: picked %p from pool (fill now %"SIZE_P")", (void*)buf, (size_p)bc->pool_fill);
547 		return buf;
548 	}
549 	else return buffy_new(size, bc->bufblock);
550 }
551 
552 /* Either stuff the buffer back into the pool or free it for good. */
553 static void bc_free(struct bufferchain *bc, struct buffy* buf)
554 {
555 	if(!buf) return;
556 
557 	if(bc->pool_fill < bc->pool_size)
558 	{
559 		buf->next = bc->pool;
560 		bc->pool = buf;
561 		++bc->pool_fill;
562 	}
563 	else buffy_del(buf);
564 }
565 
566 /* Make the buffer count in the pool match the pool size. */
567 static int bc_fill_pool(struct bufferchain *bc)
568 {
569 	/* Remove superfluous ones. */
570 	while(bc->pool_fill > bc->pool_size)
571 	{
572 		/* Lazyness: Just work on the front. */
573 		struct buffy* buf = bc->pool;
574 		bc->pool = buf->next;
575 		buffy_del(buf);
576 		--bc->pool_fill;
577 	}
578 
579 	/* Add missing ones. */
580 	while(bc->pool_fill < bc->pool_size)
581 	{
582 		/* Again, just work on the front. */
583 		struct buffy* buf;
584 		buf = buffy_new(0, bc->bufblock); /* Use default block size. */
585 		if(!buf) return -1;
586 
587 		buf->next = bc->pool;
588 		bc->pool = buf;
589 		++bc->pool_fill;
590 	}
591 
592 	return 0;
593 }
594 
595 
596 static void bc_init(struct bufferchain *bc)
597 {
598 	bc->first = NULL;
599 	bc->last  = bc->first;
600 	bc->size  = 0;
601 	bc->pos   = 0;
602 	bc->firstpos = 0;
603 	bc->fileoff  = 0;
604 }
605 
606 static void bc_reset(struct bufferchain *bc)
607 {
608 	/* Free current chain, possibly stuffing back into the pool. */
609 	while(bc->first)
610 	{
611 		struct buffy* buf = bc->first;
612 		bc->first = buf->next;
613 		bc_free(bc, buf);
614 	}
615 	bc_fill_pool(bc); /* Ignoring an error here... */
616 	bc_init(bc);
617 }
618 
619 /* Create a new buffy at the end to be filled. */
620 static int bc_append(struct bufferchain *bc, ssize_t size)
621 {
622 	struct buffy *newbuf;
623 	if(size < 1) return -1;
624 
625 	newbuf = bc_alloc(bc, size);
626 	if(newbuf == NULL) return -2;
627 
628 	if(bc->last != NULL)  bc->last->next = newbuf;
629 	else if(bc->first == NULL) bc->first = newbuf;
630 
631 	bc->last  = newbuf;
632 	debug3("bc_append: new last buffer %p with %"SSIZE_P" B (really %"SSIZE_P")", (void*)bc->last, (ssize_p)bc->last->size, (ssize_p)bc->last->realsize);
633 	return 0;
634 }
635 
636 /* Append a new buffer and copy content to it. */
637 static int bc_add(struct bufferchain *bc, const unsigned char *data, ssize_t size)
638 {
639 	int ret = 0;
640 	ssize_t part = 0;
641 	debug2("bc_add: adding %"SSIZE_P" bytes at %"OFF_P, (ssize_p)size, (off_p)(bc->fileoff+bc->size));
642 	if(size >=4) debug4("first bytes: %02x %02x %02x %02x", data[0], data[1], data[2], data[3]);
643 
644 	while(size > 0)
645 	{
646 		/* Try to fill up the last buffer block. */
647 		if(bc->last != NULL && bc->last->size < bc->last->realsize)
648 		{
649 			part = bc->last->realsize - bc->last->size;
650 			if(part > size) part = size;
651 
652 			debug2("bc_add: adding %"SSIZE_P" B to existing block %p", (ssize_p)part, (void*)bc->last);
653 			memcpy(bc->last->data+bc->last->size, data, part);
654 			bc->last->size += part;
655 			size -= part;
656 			bc->size += part;
657 			data += part;
658 		}
659 
660 		/* If there is still data left, put it into a new buffer block. */
661 		if(size > 0 && (ret = bc_append(bc, size)) != 0)
662 		break;
663 	}
664 
665 	return ret;
666 }
667 
668 /* Common handler for "You want more than I can give." situation. */
669 static ssize_t bc_need_more(struct bufferchain *bc)
670 {
671 	debug3("hit end, back to beginning (%li - %li < %li)", (long)bc->size, (long)bc->pos, (long)bc->size);
672 	/* go back to firstpos, undo the previous reads */
673 	bc->pos = bc->firstpos;
674 	return READER_MORE;
675 }
676 
677 /* Give some data, advancing position but not forgetting yet. */
678 static ssize_t bc_give(struct bufferchain *bc, unsigned char *out, ssize_t size)
679 {
680 	struct buffy *b = bc->first;
681 	ssize_t gotcount = 0;
682 	ssize_t offset = 0;
683 	if(bc->size - bc->pos < size) return bc_need_more(bc);
684 
685 	/* find the current buffer */
686 	while(b != NULL && (offset + b->size) <= bc->pos)
687 	{
688 		offset += b->size;
689 		b = b->next;
690 	}
691 	/* now start copying from there */
692 	while(gotcount < size && (b != NULL))
693 	{
694 		ssize_t loff = bc->pos - offset;
695 		ssize_t chunk = size - gotcount; /* amount of bytes to get from here... */
696 		if(chunk > b->size - loff) chunk = b->size - loff;
697 
698 #ifdef EXTRA_DEBUG
699 		debug3("copying %liB from %p+%li",(long)chunk, b->data, (long)loff);
700 #endif
701 
702 		memcpy(out+gotcount, b->data+loff, chunk);
703 		gotcount += chunk;
704 		bc->pos  += chunk;
705 		offset += b->size;
706 		b = b->next;
707 	}
708 #ifdef EXTRA_DEBUG
709 	debug2("got %li bytes, pos advanced to %li", (long)gotcount, (long)bc->pos);
710 #endif
711 
712 	return gotcount;
713 }
714 
715 /* Skip some bytes and return the new position.
716    The buffers are still there, just the read pointer is moved! */
717 static ssize_t bc_skip(struct bufferchain *bc, ssize_t count)
718 {
719 	if(count >= 0)
720 	{
721 		if(bc->size - bc->pos < count) return bc_need_more(bc);
722 		else return bc->pos += count;
723 	}
724 	else return READER_ERROR;
725 }
726 
727 static ssize_t bc_seekback(struct bufferchain *bc, ssize_t count)
728 {
729 	if(count >= 0 && count <= bc->pos) return bc->pos -= count;
730 	else return READER_ERROR;
731 }
732 
733 /* Throw away buffies that we passed. */
734 static void bc_forget(struct bufferchain *bc)
735 {
736 	struct buffy *b = bc->first;
737 	/* free all buffers that are def'n'tly outdated */
738 	/* we have buffers until filepos... delete all buffers fully below it */
739 	if(b) debug2("bc_forget: block %lu pos %lu", (unsigned long)b->size, (unsigned long)bc->pos);
740 	else debug("forget with nothing there!");
741 
742 	while(b != NULL && bc->pos >= b->size)
743 	{
744 		struct buffy *n = b->next; /* != NULL or this is indeed the end and the last cycle anyway */
745 		if(n == NULL) bc->last = NULL; /* Going to delete the last buffy... */
746 		bc->fileoff += b->size;
747 		bc->pos  -= b->size;
748 		bc->size -= b->size;
749 
750 		debug5("bc_forget: forgot %p with %lu, pos=%li, size=%li, fileoff=%li", (void*)b->data, (long)b->size, (long)bc->pos,  (long)bc->size, (long)bc->fileoff);
751 
752 		bc_free(bc, b);
753 		b = n;
754 	}
755 	bc->first = b;
756 	bc->firstpos = bc->pos;
757 }
758 
759 /* reader for input via manually provided buffers */
760 
761 static int feed_init(mpg123_handle *fr)
762 {
763 	bc_init(&fr->rdat.buffer);
764 	bc_fill_pool(&fr->rdat.buffer);
765 	fr->rdat.filelen = 0;
766 	fr->rdat.filepos = 0;
767 	fr->rdat.flags |= READER_BUFFERED;
768 	return 0;
769 }
770 
771 /* externally called function, returns 0 on success, -1 on error */
772 int feed_more(mpg123_handle *fr, const unsigned char *in, long count)
773 {
774 	int ret = 0;
775 	if(VERBOSE3) debug("feed_more");
776 	if((ret = bc_add(&fr->rdat.buffer, in, count)) != 0)
777 	{
778 		ret = READER_ERROR;
779 		if(NOQUIET) error1("Failed to add buffer, return: %i", ret);
780 	}
781 	else /* Not talking about filelen... that stays at 0. */
782 
783 	if(VERBOSE3) debug3("feed_more: %p %luB bufsize=%lu", fr->rdat.buffer.last->data,
784 		(unsigned long)fr->rdat.buffer.last->size, (unsigned long)fr->rdat.buffer.size);
785 	return ret;
786 }
787 
788 static ssize_t feed_read(mpg123_handle *fr, unsigned char *out, ssize_t count)
789 {
790 	ssize_t gotcount = bc_give(&fr->rdat.buffer, out, count);
791 	if(gotcount >= 0 && gotcount != count) return READER_ERROR;
792 	else return gotcount;
793 }
794 
795 /* returns reached position... negative ones are bad... */
796 static off_t feed_skip_bytes(mpg123_handle *fr,off_t len)
797 {
798 	/* This is either the new buffer offset or some negative error value. */
799 	off_t res = bc_skip(&fr->rdat.buffer, (ssize_t)len);
800 	if(res < 0) return res;
801 
802 	return fr->rdat.buffer.fileoff+res;
803 }
804 
805 static int feed_back_bytes(mpg123_handle *fr, off_t bytes)
806 {
807 	if(bytes >=0)
808 	return bc_seekback(&fr->rdat.buffer, (ssize_t)bytes) >= 0 ? 0 : READER_ERROR;
809 	else
810 	return feed_skip_bytes(fr, -bytes) >= 0 ? 0 : READER_ERROR;
811 }
812 
813 static int feed_seek_frame(mpg123_handle *fr, off_t num){ return READER_ERROR; }
814 
815 /* Not just for feed reader, also for self-feeding buffered reader. */
816 static void buffered_forget(mpg123_handle *fr)
817 {
818 	bc_forget(&fr->rdat.buffer);
819 	fr->rdat.filepos = fr->rdat.buffer.fileoff + fr->rdat.buffer.pos;
820 }
821 
822 off_t feed_set_pos(mpg123_handle *fr, off_t pos)
823 {
824 	struct bufferchain *bc = &fr->rdat.buffer;
825 	if(pos >= bc->fileoff && pos-bc->fileoff < bc->size)
826 	{ /* We have the position! */
827 		bc->pos = (ssize_t)(pos - bc->fileoff);
828 		debug1("feed_set_pos inside, next feed from %"OFF_P, (off_p)(bc->fileoff+bc->size));
829 		return bc->fileoff+bc->size; /* Next input after end of buffer... */
830 	}
831 	else
832 	{ /* I expect to get the specific position on next feed. Forget what I have now. */
833 		bc_reset(bc);
834 		bc->fileoff = pos;
835 		debug1("feed_set_pos outside, buffer reset, next feed from %"OFF_P, (off_p)pos);
836 		return pos; /* Next input from exactly that position. */
837 	}
838 }
839 
840 /* The specific stuff for buffered stream reader. */
841 
842 static ssize_t buffered_fullread(mpg123_handle *fr, unsigned char *out, ssize_t count)
843 {
844 	struct bufferchain *bc = &fr->rdat.buffer;
845 	ssize_t gotcount;
846 	if(VERBOSE3)
847 		mdebug("buffered_fullread: want %zd", count);
848 	if(bc->size - bc->pos < count)
849 	{ /* Add more stuff to buffer. If hitting end of file, adjust count. */
850 		unsigned char readbuf[4096];
851 		ssize_t need = count - (bc->size-bc->pos);
852 		while(need>0)
853 		{
854 			int ret;
855 			ssize_t got = fr->rdat.fullread(fr, readbuf, sizeof(readbuf));
856 			if(got < 0)
857 			{
858 				if(NOQUIET) error("buffer reading");
859 				return READER_ERROR;
860 			}
861 
862 			if(VERBOSE3) debug1("buffered_fullread: buffering %li bytes from stream (if > 0)", (long)got);
863 			if(got > 0 && (ret=bc_add(bc, readbuf, got)) != 0)
864 			{
865 				if(NOQUIET) error1("unable to add to chain, return: %i", ret);
866 				return READER_ERROR;
867 			}
868 
869 			need -= got; /* May underflow here... */
870 			if(got < sizeof(readbuf)) /* That naturally catches got == 0, too. */
871 			{
872 				if(VERBOSE3) fprintf(stderr, "Note: Input data end.\n");
873 				break; /* End. */
874 			}
875 		}
876 		if(bc->size - bc->pos < count)
877 		count = bc->size - bc->pos; /* We want only what we got. */
878 	}
879 	gotcount = bc_give(bc, out, count);
880 	if(VERBOSE3)
881 		mdebug("buffered_fullread: got %zd", gotcount);
882 	if(gotcount != count){ if(NOQUIET) error("gotcount != count"); return READER_ERROR; }
883 	else return gotcount;
884 }
885 #else
886 int feed_more(mpg123_handle *fr, const unsigned char *in, long count)
887 {
888 	fr->err = MPG123_MISSING_FEATURE;
889 	return -1;
890 }
891 off_t feed_set_pos(mpg123_handle *fr, off_t pos)
892 {
893 	fr->err = MPG123_MISSING_FEATURE;
894 	return -1;
895 }
896 #endif /* NO_FEEDER */
897 
898 /*****************************************************************
899  * read frame helper
900  */
901 
902 #define bugger_off { mh->err = MPG123_NO_READER; return MPG123_ERR; }
903 static int bad_init(mpg123_handle *mh) bugger_off
904 static void bad_close(mpg123_handle *mh){}
905 static ssize_t bad_fullread(mpg123_handle *mh, unsigned char *data, ssize_t count) bugger_off
906 static int bad_head_read(mpg123_handle *mh, unsigned long *newhead) bugger_off
907 static int bad_head_shift(mpg123_handle *mh, unsigned long *head) bugger_off
908 static off_t bad_skip_bytes(mpg123_handle *mh, off_t len) bugger_off
909 static int bad_read_frame_body(mpg123_handle *mh, unsigned char *data, int size) bugger_off
910 static int bad_back_bytes(mpg123_handle *mh, off_t bytes) bugger_off
911 static int bad_seek_frame(mpg123_handle *mh, off_t num) bugger_off
912 static off_t bad_tell(mpg123_handle *mh) bugger_off
913 static void bad_rewind(mpg123_handle *mh){}
914 #undef bugger_off
915 
916 #define READER_STREAM 0
917 #define READER_ICY_STREAM 1
918 #define READER_FEED       2
919 #define READER_BUF_STREAM 3
920 #define READER_BUF_ICY_STREAM 4
921 static struct reader readers[] =
922 {
923 	{ /* READER_STREAM */
924 		default_init,
925 		stream_close,
926 		plain_fullread,
927 		generic_head_read,
928 		generic_head_shift,
929 		stream_skip_bytes,
930 		generic_read_frame_body,
931 		stream_back_bytes,
932 		stream_seek_frame,
933 		generic_tell,
934 		stream_rewind,
935 		NULL
936 	} ,
937 	{ /* READER_ICY_STREAM */
938 		default_init,
939 		stream_close,
940 		icy_fullread,
941 		generic_head_read,
942 		generic_head_shift,
943 		stream_skip_bytes,
944 		generic_read_frame_body,
945 		stream_back_bytes,
946 		stream_seek_frame,
947 		generic_tell,
948 		stream_rewind,
949 		NULL
950 	},
951 #ifdef NO_FEEDER
952 #define feed_init NULL
953 #define feed_read NULL
954 #define buffered_fullread NULL
955 #define feed_seek_frame NULL
956 #define feed_back_bytes NULL
957 #define feed_skip_bytes NULL
958 #define buffered_forget NULL
959 #endif
960 	{ /* READER_FEED */
961 		feed_init,
962 		stream_close,
963 		feed_read,
964 		generic_head_read,
965 		generic_head_shift,
966 		feed_skip_bytes,
967 		generic_read_frame_body,
968 		feed_back_bytes,
969 		feed_seek_frame,
970 		generic_tell,
971 		stream_rewind,
972 		buffered_forget
973 	},
974 	{ /* READER_BUF_STREAM */
975 		default_init,
976 		stream_close,
977 		buffered_fullread,
978 		generic_head_read,
979 		generic_head_shift,
980 		stream_skip_bytes,
981 		generic_read_frame_body,
982 		stream_back_bytes,
983 		stream_seek_frame,
984 		generic_tell,
985 		stream_rewind,
986 		buffered_forget
987 	} ,
988 	{ /* READER_BUF_ICY_STREAM */
989 		default_init,
990 		stream_close,
991 		buffered_fullread,
992 		generic_head_read,
993 		generic_head_shift,
994 		stream_skip_bytes,
995 		generic_read_frame_body,
996 		stream_back_bytes,
997 		stream_seek_frame,
998 		generic_tell,
999 		stream_rewind,
1000 		buffered_forget
1001 	},
1002 #ifdef READ_SYSTEM
1003 	,{
1004 		system_init,
1005 		NULL,	/* filled in by system_init() */
1006 		fullread,
1007 		NULL,
1008 		NULL,
1009 		NULL,
1010 		NULL,
1011 		NULL,
1012 		NULL,
1013 		NULL,
1014 		NULL,
1015 		NULL,
1016 	}
1017 #endif
1018 };
1019 
1020 static struct reader bad_reader =
1021 {
1022 	bad_init,
1023 	bad_close,
1024 	bad_fullread,
1025 	bad_head_read,
1026 	bad_head_shift,
1027 	bad_skip_bytes,
1028 	bad_read_frame_body,
1029 	bad_back_bytes,
1030 	bad_seek_frame,
1031 	bad_tell,
1032 	bad_rewind,
1033 	NULL
1034 };
1035 
1036 static int default_init(mpg123_handle *fr)
1037 {
1038 #ifdef TIMEOUT_READ
1039 	if(fr->p.timeout > 0)
1040 	{
1041 		int flags;
1042 		if(fr->rdat.r_read != NULL)
1043 		{
1044 			if(NOQUIET)
1045 				error( "Timeout reading does not work with user-provided"
1046 					" read function. Implement it yourself!" );
1047 			return -1;
1048 		}
1049 		flags = fcntl(fr->rdat.filept, F_GETFL);
1050 		flags |= O_NONBLOCK;
1051 		fcntl(fr->rdat.filept, F_SETFL, flags);
1052 		fr->rdat.fdread = timeout_read;
1053 		fr->rdat.timeout_sec = fr->p.timeout;
1054 		fr->rdat.flags |= READER_NONBLOCK;
1055 	}
1056 	else
1057 #endif
1058 	fr->rdat.fdread = plain_read;
1059 
1060 	fr->rdat.read  = fr->rdat.r_read  != NULL ? fr->rdat.r_read  : posix_read;
1061 	fr->rdat.lseek = fr->rdat.r_lseek != NULL ? fr->rdat.r_lseek : posix_lseek;
1062 #ifndef NO_ICY
1063 	/* ICY streams of any sort shall not be seekable. */
1064 	if(fr->p.icy_interval > 0) fr->rdat.lseek = nix_lseek;
1065 #endif
1066 
1067 	fr->rdat.filelen = fr->p.flags & MPG123_NO_PEEK_END ? -1 : get_fileinfo(fr);
1068 	fr->rdat.filepos = 0;
1069 	if(fr->p.flags & MPG123_FORCE_SEEKABLE)
1070 		fr->rdat.flags |= READER_SEEKABLE;
1071 	/*
1072 		Don't enable seeking on ICY streams, just plain normal files.
1073 		This check is necessary since the client can enforce ICY parsing on files that would otherwise be seekable.
1074 		It is a task for the future to make the ICY parsing safe with seeks ... or not.
1075 	*/
1076 	if(fr->rdat.filelen >= 0)
1077 	{
1078 		debug("seekable stream");
1079 		fr->rdat.flags |= READER_SEEKABLE;
1080 		if(!strncmp((char*)fr->id3buf,"TAG",3))
1081 		{
1082 			fr->rdat.flags |= READER_ID3TAG;
1083 			fr->metaflags  |= MPG123_NEW_ID3;
1084 		}
1085 	}
1086 	/* Switch reader to a buffered one, if allowed. */
1087 	else if(fr->p.flags & MPG123_SEEKBUFFER)
1088 	{
1089 #ifdef NO_FEEDER
1090 		if(NOQUIET)
1091 			error("Buffered readers not supported in this build.");
1092 		fr->err = MPG123_MISSING_FEATURE;
1093 		return -1;
1094 #else
1095 		if     (fr->rd == &readers[READER_STREAM])
1096 		{
1097 			debug("switching to buffered stream reader");
1098 			fr->rd = &readers[READER_BUF_STREAM];
1099 			fr->rdat.fullread = plain_fullread;
1100 		}
1101 #ifndef NO_ICY
1102 		else if(fr->rd == &readers[READER_ICY_STREAM])
1103 		{
1104 			debug("switching to buffered ICY stream reader");
1105 			fr->rd = &readers[READER_BUF_ICY_STREAM];
1106 			fr->rdat.fullread = icy_fullread;
1107 		}
1108 #endif
1109 		else
1110 		{
1111 			if(NOQUIET) error("mpg123 Programmer's fault: invalid reader");
1112 			return -1;
1113 		}
1114 		bc_init(&fr->rdat.buffer);
1115 		fr->rdat.filelen = 0; /* We carry the offset, but never know how big the stream is. */
1116 		fr->rdat.flags |= READER_BUFFERED;
1117 #endif /* NO_ICY */
1118 	}
1119 	return 0;
1120 }
1121 
1122 
1123 void open_bad(mpg123_handle *mh)
1124 {
1125 	debug("open_bad");
1126 #ifndef NO_ICY
1127 	clear_icy(&mh->icy);
1128 #endif
1129 	mh->rd = &bad_reader;
1130 	mh->rdat.flags = 0;
1131 #ifndef NO_FEEDER
1132 	bc_init(&mh->rdat.buffer);
1133 #endif
1134 	mh->rdat.filelen = -1;
1135 }
1136 
1137 int open_feed(mpg123_handle *fr)
1138 {
1139 	debug("feed reader");
1140 #ifdef NO_FEEDER
1141 	if(NOQUIET)
1142 		error("Buffered readers not supported in this build.");
1143 	fr->err = MPG123_MISSING_FEATURE;
1144 	return -1;
1145 #else
1146 #ifndef NO_ICY
1147 	if(fr->p.icy_interval > 0)
1148 	{
1149 		if(NOQUIET) error("Feed reader cannot do ICY parsing!");
1150 
1151 		return -1;
1152 	}
1153 	clear_icy(&fr->icy);
1154 #endif
1155 	fr->rd = &readers[READER_FEED];
1156 	fr->rdat.flags = 0;
1157 	if(fr->rd->init(fr) < 0) return -1;
1158 
1159 	debug("feed reader init successful");
1160 	return 0;
1161 #endif /* NO_FEEDER */
1162 }
1163 
1164 /* Final code common to open_stream and open_stream_handle. */
1165 static int open_finish(mpg123_handle *fr)
1166 {
1167 #ifndef NO_ICY
1168 	if(fr->p.icy_interval > 0)
1169 	{
1170 		debug("ICY reader");
1171 		fr->icy.interval = fr->p.icy_interval;
1172 		fr->icy.next = fr->icy.interval;
1173 		fr->rd = &readers[READER_ICY_STREAM];
1174 	}
1175 	else
1176 #endif
1177 	{
1178 		fr->rd = &readers[READER_STREAM];
1179 		debug("stream reader");
1180 	}
1181 
1182 	if(fr->rd->init(fr) < 0) return -1;
1183 
1184 	return MPG123_OK;
1185 }
1186 
1187 int open_stream(mpg123_handle *fr, const char *bs_filenam, int fd)
1188 {
1189 	int filept_opened = 1;
1190 	int filept; /* descriptor of opened file/stream */
1191 
1192 	clear_icy(&fr->icy); /* can be done inside frame_clear ...? */
1193 
1194 	if(!bs_filenam) /* no file to open, got a descriptor (stdin) */
1195 	{
1196 		filept = fd;
1197 		filept_opened = 0; /* and don't try to close it... */
1198 	}
1199 	#ifndef O_BINARY
1200 	#define O_BINARY (0)
1201 	#endif
1202 	else if((filept = compat_open(bs_filenam, O_RDONLY|O_BINARY)) < 0) /* a plain old file to open... */
1203 	{
1204 		if(NOQUIET) error2("Cannot open file %s: %s", bs_filenam, strerror(errno));
1205 		fr->err = MPG123_BAD_FILE;
1206 		return MPG123_ERR; /* error... */
1207 	}
1208 
1209 	/* now we have something behind filept and can init the reader */
1210 	fr->rdat.filelen = -1;
1211 	fr->rdat.filept  = filept;
1212 	fr->rdat.flags = 0;
1213 	if(filept_opened)	fr->rdat.flags |= READER_FD_OPENED;
1214 
1215 	return open_finish(fr);
1216 }
1217 
1218 int open_stream_handle(mpg123_handle *fr, void *iohandle)
1219 {
1220 	clear_icy(&fr->icy); /* can be done inside frame_clear ...? */
1221 	fr->rdat.filelen = -1;
1222 	fr->rdat.filept  = -1;
1223 	fr->rdat.iohandle = iohandle;
1224 	fr->rdat.flags = 0;
1225 	fr->rdat.flags |= READER_HANDLEIO;
1226 
1227 	return open_finish(fr);
1228 }
1229 
1230 /* Wrappers for actual reading/seeking... I'm full of wrappers here. */
1231 static off_t io_seek(struct reader_data *rdat, off_t offset, int whence)
1232 {
1233 	if(rdat->flags & READER_HANDLEIO)
1234 	{
1235 		if(rdat->r_lseek_handle != NULL)
1236 		{
1237 			return rdat->r_lseek_handle(rdat->iohandle, offset, whence);
1238 		}
1239 		else return -1;
1240 	}
1241 	else
1242 	return rdat->lseek(rdat->filept, offset, whence);
1243 }
1244 
1245 static ssize_t io_read(struct reader_data *rdat, void *buf, size_t count)
1246 {
1247 	if(rdat->flags & READER_HANDLEIO)
1248 	{
1249 		if(rdat->r_read_handle != NULL)
1250 		{
1251 			return rdat->r_read_handle(rdat->iohandle, buf, count);
1252 		}
1253 		else return -1;
1254 	}
1255 	else
1256 	return rdat->read(rdat->filept, buf, count);
1257 }
1258