xref: /reactos/sdk/lib/3rdparty/libmpg123/parse.c (revision d7fd62d4)
1 /*
2 	parse: spawned from common; clustering around stream/frame parsing
3 
4 	copyright ?-2020 by the mpg123 project - free software under the terms of the LGPL 2.1
5 	see COPYING and AUTHORS files in distribution or http://mpg123.org
6 	initially written by Michael Hipp & Thomas Orgis
7 */
8 
9 #include "mpg123lib_intern.h"
10 
11 #include <sys/stat.h>
12 #include <fcntl.h>
13 
14 #ifndef __REACTOS__
15 #include "getbits.h"
16 #endif
17 
18 #if defined (WANT_WIN32_SOCKETS)
19 #include <winsock2.h>
20 #include <ws2tcpip.h>
21 #endif
22 
23 #ifdef __REACTOS__
24 #include "getbits.h"
25 #endif
26 
27 /* a limit for number of frames in a track; beyond that unsigned long may not be enough to hold byte addresses */
28 #ifdef HAVE_LIMITS_H
29 #include <limits.h>
30 #endif
31 #ifndef ULONG_MAX
32 /* hm, is this portable across preprocessors? */
33 #define ULONG_MAX ((unsigned long)-1)
34 #endif
35 #define TRACK_MAX_FRAMES ULONG_MAX/4/1152
36 
37 #include "mpeghead.h"
38 
39 #include "debug.h"
40 
41 #define bsbufid(fr) (fr)->bsbuf==(fr)->bsspace[0] ? 0 : ((fr)->bsbuf==fr->bsspace[1] ? 1 : ( (fr)->bsbuf==(fr)->bsspace[0]+512 ? 2 : ((fr)->bsbuf==fr->bsspace[1]+512 ? 3 : -1) ) )
42 
43 /* PARSE_GOOD and PARSE_BAD have to be 1 and 0 (TRUE and FALSE), others can vary. */
44 enum parse_codes
45 {
46 	 PARSE_MORE = MPG123_NEED_MORE
47 	,PARSE_ERR  = MPG123_ERR
48 	,PARSE_END  = 10 /* No more audio data to find. */
49 	,PARSE_GOOD = 1 /* Everything's fine. */
50 	,PARSE_BAD  = 0 /* Not fine (invalid data). */
51 	,PARSE_RESYNC = 2 /* Header not good, go into resync. */
52 	,PARSE_AGAIN  = 3 /* Really start over, throw away and read a new header, again. */
53 };
54 
55 /* bitrates for [mpeg1/2][layer] */
56 static const int tabsel_123[2][3][16] =
57 {
58 	{
59 		{0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,},
60 		{0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,},
61 		{0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,}
62 	},
63 	{
64 		{0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,},
65 		{0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,},
66 		{0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,}
67 	}
68 };
69 
70 static const long freqs[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 };
71 
72 static int decode_header(mpg123_handle *fr,unsigned long newhead, int *freeformat_count);
73 static int skip_junk(mpg123_handle *fr, unsigned long *newheadp, long *headcount);
74 static int do_readahead(mpg123_handle *fr, unsigned long newhead);
75 static int wetwork(mpg123_handle *fr, unsigned long *newheadp);
76 
77 /* These two are to be replaced by one function that gives all the frame parameters (for outsiders).*/
78 /* Those functions are unsafe regarding bad arguments (inside the mpg123_handle), but just returning anything would also be unsafe, the caller code has to be trusted. */
79 
80 int frame_bitrate(mpg123_handle *fr)
81 {
82 	return tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index];
83 }
84 
85 long frame_freq(mpg123_handle *fr)
86 {
87 	return freqs[fr->sampling_frequency];
88 }
89 
90 /* compiler is smart enought to inline this one or should I really do it as macro...? */
91 static int head_check(unsigned long head)
92 {
93 	if
94 	(
95 		((head & HDR_SYNC) != HDR_SYNC)
96 		||
97 		/* layer: 01,10,11 is 1,2,3; 00 is reserved */
98 		(!(HDR_LAYER_VAL(head)))
99 		||
100 		/* 1111 means bad bitrate */
101 		(HDR_BITRATE_VAL(head) == 0xf)
102 		||
103 		/* sampling freq: 11 is reserved */
104 		(HDR_SAMPLERATE_VAL(head) == 0x3)
105 		/* here used to be a mpeg 2.5 check... re-enabled 2.5 decoding due to lack of evidence that it is really not good */
106 	)
107 	{
108 		return FALSE;
109 	}
110 	/* if no check failed, the header is valid (hopefully)*/
111 	else
112 	{
113 		return TRUE;
114 	}
115 }
116 
117 /* This is moderately sized buffers. Int offset is enough. */
118 static unsigned long bit_read_long(unsigned char *buf, int *offset)
119 {
120 	unsigned long val =  /* 32 bit value */
121 		(((unsigned long) buf[*offset])   << 24)
122 	|	(((unsigned long) buf[*offset+1]) << 16)
123 	|	(((unsigned long) buf[*offset+2]) << 8)
124 	|	 ((unsigned long) buf[*offset+3]);
125 	*offset += 4;
126 	return val;
127 }
128 
129 static unsigned short bit_read_short(unsigned char *buf, int *offset)
130 {
131 	unsigned short val = /* 16 bit value */
132 		(((unsigned short) buf[*offset]  ) << 8)
133 	|	 ((unsigned short) buf[*offset+1]);
134 	*offset += 2;
135 	return val;
136 }
137 
138 static int check_lame_tag(mpg123_handle *fr)
139 {
140 	int i;
141 	unsigned long xing_flags;
142 	unsigned long long_tmp;
143 	/*
144 		going to look for Xing or Info at some position after the header
145 		                                   MPEG 1  MPEG 2/2.5 (LSF)
146 		Stereo, Joint Stereo, Dual Channel  32      17
147 		Mono                                17       9
148 	*/
149 	int lame_offset = (fr->stereo == 2)
150 	? (fr->lsf ? 17 : 32)
151 	: (fr->lsf ? 9  : 17);
152 
153 	if(fr->p.flags & MPG123_IGNORE_INFOFRAME) goto check_lame_tag_no;
154 
155 	debug("do we have lame tag?");
156 	/*
157 		Note: CRC or not, that does not matter here.
158 		But, there is any combination of Xing flags in the wild. There are headers
159 		without the search index table! I cannot assume a reasonable minimal size
160 		for the actual data, have to check if each byte of information is present.
161 		But: 4 B Info/Xing + 4 B flags is bare minimum.
162 	*/
163 	if(fr->framesize < lame_offset+8) goto check_lame_tag_no;
164 
165 	/* only search for tag when all zero before it (apart from checksum) */
166 	for(i=2; i < lame_offset; ++i) if(fr->bsbuf[i] != 0) goto check_lame_tag_no;
167 
168 	debug("possibly...");
169 	if
170 	(
171 		   (fr->bsbuf[lame_offset]   == 'I')
172 		&& (fr->bsbuf[lame_offset+1] == 'n')
173 		&& (fr->bsbuf[lame_offset+2] == 'f')
174 		&& (fr->bsbuf[lame_offset+3] == 'o')
175 	)
176 	{
177 		/* We still have to see what there is */
178 	}
179 	else if
180 	(
181 		   (fr->bsbuf[lame_offset]   == 'X')
182 		&& (fr->bsbuf[lame_offset+1] == 'i')
183 		&& (fr->bsbuf[lame_offset+2] == 'n')
184 		&& (fr->bsbuf[lame_offset+3] == 'g')
185 	)
186 	{
187 		fr->vbr = MPG123_VBR; /* Xing header means always VBR */
188 	}
189 	else goto check_lame_tag_no;
190 
191 	/* we have one of these headers... */
192 	if(VERBOSE2) fprintf(stderr, "Note: Xing/Lame/Info header detected\n");
193 	lame_offset += 4;
194 	xing_flags = bit_read_long(fr->bsbuf, &lame_offset);
195 	debug1("Xing: flags 0x%08lx", xing_flags);
196 
197 	/* From now on, I have to carefully check if the announced data is actually
198 	   there! I'm always returning 'yes', though.  */
199 	#define check_bytes_left(n) if(fr->framesize < lame_offset+n) \
200 		goto check_lame_tag_yes
201 	if(xing_flags & 1) /* total bitstream frames */
202 	{
203 		check_bytes_left(4); long_tmp = bit_read_long(fr->bsbuf, &lame_offset);
204 		if(fr->p.flags & MPG123_IGNORE_STREAMLENGTH)
205 		{
206 			if(VERBOSE3) fprintf(stderr
207 			,	"Note: Ignoring Xing frames because of MPG123_IGNORE_STREAMLENGTH\n");
208 		}
209 		else
210 		{
211 			/* Check for endless stream, but: TRACK_MAX_FRAMES sensible at all? */
212 			fr->track_frames = long_tmp > TRACK_MAX_FRAMES ? 0 : (off_t) long_tmp;
213 #ifdef GAPLESS
214 			/* All or nothing: Only if encoder delay/padding is known, we'll cut
215 			   samples for gapless. */
216 			if(fr->p.flags & MPG123_GAPLESS)
217 			frame_gapless_init(fr, fr->track_frames, 0, 0);
218 #endif
219 			if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu frames\n", long_tmp);
220 		}
221 	}
222 	if(xing_flags & 0x2) /* total bitstream bytes */
223 	{
224 		check_bytes_left(4); long_tmp = bit_read_long(fr->bsbuf, &lame_offset);
225 		if(fr->p.flags & MPG123_IGNORE_STREAMLENGTH)
226 		{
227 			if(VERBOSE3) fprintf(stderr
228 			,	"Note: Ignoring Xing bytes because of MPG123_IGNORE_STREAMLENGTH\n");
229 		}
230 		else
231 		{
232 			/* The Xing bitstream length, at least as interpreted by the Lame
233 			   encoder, encompasses all data from the Xing header frame on,
234 			   ignoring leading ID3v2 data. Trailing tags (ID3v1) seem to be
235 			   included, though. */
236 			if(fr->rdat.filelen < 1)
237 			fr->rdat.filelen = (off_t) long_tmp + fr->audio_start; /* Overflow? */
238 			else
239 			{
240 				if((off_t)long_tmp != fr->rdat.filelen - fr->audio_start && NOQUIET)
241 				{ /* 1/filelen instead of 1/(filelen-start), my decision */
242 					double diff = 100.0/fr->rdat.filelen
243 					            * ( fr->rdat.filelen - fr->audio_start
244 					                - (off_t)long_tmp );
245 					if(diff < 0.) diff = -diff;
246 
247 					if(VERBOSE3) fprintf(stderr
248 					,	"Note: Xing stream size %lu differs by %f%% from determined/given file size!\n"
249 					,	long_tmp, diff);
250 
251 					if(diff > 1. && NOQUIET) fprintf(stderr
252 					,	"Warning: Xing stream size off by more than 1%%, fuzzy seeking may be even more fuzzy than by design!\n");
253 				}
254 			}
255 
256 			if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu bytes\n", long_tmp);
257 		}
258 	}
259 	if(xing_flags & 0x4) /* TOC */
260 	{
261 		check_bytes_left(100);
262 		frame_fill_toc(fr, fr->bsbuf+lame_offset);
263 		lame_offset += 100;
264 	}
265 	if(xing_flags & 0x8) /* VBR quality */
266 	{
267 		check_bytes_left(4); long_tmp = bit_read_long(fr->bsbuf, &lame_offset);
268 		if(VERBOSE3) fprintf(stderr, "Note: Xing: quality = %lu\n", long_tmp);
269 	}
270 	/*
271 		Either zeros/nothing, or:
272 			0-8: LAME3.90a
273 			9: revision/VBR method
274 			10: lowpass
275 			11-18: ReplayGain
276 			19: encoder flags
277 			20: ABR
278 			21-23: encoder delays
279 	*/
280 	check_bytes_left(24); /* I'm interested in 24 B of extra info. */
281 	if(fr->bsbuf[lame_offset] != 0)
282 	{
283 		unsigned char lame_vbr;
284 		float replay_gain[2] = {0,0};
285 		float peak = 0;
286 		float gain_offset = 0; /* going to be +6 for old lame that used 83dB */
287 		char nb[10];
288 		off_t pad_in;
289 		off_t pad_out;
290 		memcpy(nb, fr->bsbuf+lame_offset, 9);
291 		nb[9] = 0;
292 		if(VERBOSE3) fprintf(stderr, "Note: Info: Encoder: %s\n", nb);
293 		if(!strncmp("LAME", nb, 4))
294 		{
295 			/* Lame versions before 3.95.1 used 83 dB reference level, later
296 			   versions 89 dB. We stick with 89 dB as being "normal", adding
297 			   6 dB. */
298 			unsigned int major, minor;
299 			char rest[6];
300 			rest[0] = 0;
301 			if(sscanf(nb+4, "%u.%u%s", &major, &minor, rest) >= 2)
302 			{
303 				debug3("LAME: %u/%u/%s", major, minor, rest);
304 				/* We cannot detect LAME 3.95 reliably (same version string as
305 				   3.95.1), so this is a blind spot. Everything < 3.95 is safe,
306 				   though. */
307 				if(major < 3 || (major == 3 && minor < 95))
308 				{
309 					gain_offset = 6;
310 					if(VERBOSE3) fprintf(stderr
311 					,	"Note: Info: Old LAME detected, using ReplayGain preamp of %f dB.\n"
312 					,	gain_offset);
313 				}
314 			}
315 			else if(VERBOSE3) fprintf(stderr
316 			,	"Note: Info: Cannot determine LAME version.\n");
317 		}
318 		lame_offset += 9; /* 9 in */
319 
320 		/* The 4 big bits are tag revision, the small bits vbr method. */
321 		lame_vbr = fr->bsbuf[lame_offset] & 15;
322 		lame_offset += 1; /* 10 in */
323 		if(VERBOSE3)
324 		{
325 			fprintf(stderr, "Note: Info: rev %u\n", fr->bsbuf[lame_offset] >> 4);
326 			fprintf(stderr, "Note: Info: vbr mode %u\n", lame_vbr);
327 		}
328 		switch(lame_vbr)
329 		{
330 			/* from rev1 proposal... not sure if all good in practice */
331 			case 1:
332 			case 8: fr->vbr = MPG123_CBR; break;
333 			case 2:
334 			case 9: fr->vbr = MPG123_ABR; break;
335 			default: fr->vbr = MPG123_VBR; /* 00==unknown is taken as VBR */
336 		}
337 		lame_offset += 1; /* 11 in, skipping lowpass filter value */
338 
339 		/* ReplayGain peak ampitude, 32 bit float -- why did I parse it as int
340 		   before??	Ah, yes, Lame seems to store it as int since some day in 2003;
341 		   I've only seen zeros anyway until now, bah! */
342 		if
343 		(
344 			   (fr->bsbuf[lame_offset]   != 0)
345 			|| (fr->bsbuf[lame_offset+1] != 0)
346 			|| (fr->bsbuf[lame_offset+2] != 0)
347 			|| (fr->bsbuf[lame_offset+3] != 0)
348 		)
349 		{
350 			debug("Wow! Is there _really_ a non-zero peak value? Now is it stored as float or int - how should I know?");
351 			/* byte*peak_bytes = (byte*) &peak;
352 			... endianess ... just copy bytes to avoid floating point operation on unaligned memory?
353 			peak_bytes[0] = ...
354 			peak = *(float*) (fr->bsbuf+lame_offset); */
355 		}
356 		if(VERBOSE3) fprintf(stderr
357 		,	"Note: Info: peak = %f (I won't use this)\n", peak);
358 		peak = 0; /* until better times arrived */
359 		lame_offset += 4; /* 15 in */
360 
361 		/* ReplayGain values - lame only writes radio mode gain...
362 		   16bit gain, 3 bits name, 3 bits originator, sign (1=-, 0=+),
363 		   dB value*10 in 9 bits (fixed point) ignore the setting if name or
364 		   originator == 000!
365 		   radio      0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1
366 		   audiophile 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 */
367 		for(i =0; i < 2; ++i)
368 		{
369 			unsigned char gt     =  fr->bsbuf[lame_offset] >> 5;
370 			unsigned char origin = (fr->bsbuf[lame_offset] >> 2) & 0x7;
371 			float factor         = (fr->bsbuf[lame_offset] & 0x2) ? -0.1f : 0.1f;
372 			unsigned short gain  = bit_read_short(fr->bsbuf, &lame_offset) & 0x1ff; /* 19 in (2 cycles) */
373 			if(origin == 0 || gt < 1 || gt > 2) continue;
374 
375 			--gt;
376 			replay_gain[gt] = factor * (float) gain;
377 			/* Apply gain offset for automatic origin. */
378 			if(origin == 3) replay_gain[gt] += gain_offset;
379 		}
380 		if(VERBOSE3)
381 		{
382 			fprintf(stderr, "Note: Info: Radio Gain = %03.1fdB\n"
383 			,	replay_gain[0]);
384 			fprintf(stderr, "Note: Info: Audiophile Gain = %03.1fdB\n"
385 			,	replay_gain[1]);
386 		}
387 		for(i=0; i < 2; ++i)
388 		{
389 			if(fr->rva.level[i] <= 0)
390 			{
391 				fr->rva.peak[i] = 0; /* TODO: use parsed peak? */
392 				fr->rva.gain[i] = replay_gain[i];
393 				fr->rva.level[i] = 0;
394 			}
395 		}
396 
397 		lame_offset += 1; /* 20 in, skipping encoding flags byte */
398 
399 		/* ABR rate */
400 		if(fr->vbr == MPG123_ABR)
401 		{
402 			fr->abr_rate = fr->bsbuf[lame_offset];
403 			if(VERBOSE3) fprintf(stderr, "Note: Info: ABR rate = %u\n"
404 			,	fr->abr_rate);
405 		}
406 		lame_offset += 1; /* 21 in */
407 
408 		/* Encoder delay and padding, two 12 bit values
409 		   ... lame does write them from int. */
410 		pad_in  = ( (((int) fr->bsbuf[lame_offset])   << 4)
411 		          | (((int) fr->bsbuf[lame_offset+1]) >> 4) );
412 		pad_out = ( (((int) fr->bsbuf[lame_offset+1]) << 8)
413 		          |  ((int) fr->bsbuf[lame_offset+2])       ) & 0xfff;
414 		lame_offset += 3; /* 24 in */
415 		if(VERBOSE3) fprintf(stderr, "Note: Encoder delay = %i; padding = %i\n"
416 		,	(int)pad_in, (int)pad_out);
417 		/* Store even if libmpg123 does not do gapless decoding itself. */
418 		fr->enc_delay   = (int)pad_in;
419 		fr->enc_padding = (int)pad_out;
420 		#ifdef GAPLESS
421 		if(fr->p.flags & MPG123_GAPLESS)
422 		frame_gapless_init(fr, fr->track_frames, pad_in, pad_out);
423 		#endif
424 		/* final: 24 B LAME data */
425 	}
426 
427 check_lame_tag_yes:
428 	/* switch buffer back ... */
429 	fr->bsbuf = fr->bsspace[fr->bsnum]+512;
430 	fr->bsnum = (fr->bsnum + 1) & 1;
431 	return 1;
432 check_lame_tag_no:
433 	return 0;
434 }
435 
436 /* Just tell if the header is some mono. */
437 static int header_mono(unsigned long newhead)
438 {
439 	return HDR_CHANNEL_VAL(newhead) == MPG_MD_MONO ? TRUE : FALSE;
440 }
441 
442 /* true if the two headers will work with the same decoding routines */
443 static int head_compatible(unsigned long fred, unsigned long bret)
444 {
445 	return ( (fred & HDR_CMPMASK) == (bret & HDR_CMPMASK)
446 		&&       header_mono(fred) == header_mono(bret)    );
447 }
448 
449 static void halfspeed_prepare(mpg123_handle *fr)
450 {
451 	/* save for repetition */
452 	if(fr->p.halfspeed && fr->lay == 3)
453 	{
454 		debug("halfspeed - reusing old bsbuf ");
455 		memcpy (fr->ssave, fr->bsbuf, fr->ssize);
456 	}
457 }
458 
459 /* If this returns 1, the next frame is the repetition. */
460 static int halfspeed_do(mpg123_handle *fr)
461 {
462 	/* Speed-down hack: Play it again, Sam (the frame, I mean). */
463 	if (fr->p.halfspeed)
464 	{
465 		if(fr->halfphase) /* repeat last frame */
466 		{
467 			debug("repeat!");
468 			fr->to_decode = fr->to_ignore = TRUE;
469 			--fr->halfphase;
470 			set_pointer(fr, 0, 0);
471 			if(fr->lay == 3) memcpy (fr->bsbuf, fr->ssave, fr->ssize);
472 			if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */
473 			return 1;
474 		}
475 		else
476 		{
477 			fr->halfphase = fr->p.halfspeed - 1;
478 		}
479 	}
480 	return 0;
481 }
482 
483 /*
484 	Temporary macro until we got this worked out.
485 	Idea is to filter out special return values that shall trigger direct jumps to end / resync / read again.
486 	Particularily, the generic ret==PARSE_BAD==0 and ret==PARSE_GOOD==1 are not affected.
487 */
488 #define JUMP_CONCLUSION(ret) \
489 { \
490 if(ret < 0){ debug1("%s", ret == MPG123_NEED_MORE ? "need more" : "read error"); goto read_frame_bad; } \
491 else if(ret == PARSE_AGAIN) goto read_again; \
492 else if(ret == PARSE_RESYNC) goto init_resync; \
493 else if(ret == PARSE_END){ ret=0; goto read_frame_bad; } \
494 }
495 
496 /*
497 	That's a big one: read the next frame. 1 is success, <= 0 is some error
498 	Special error READER_MORE means: Please feed more data and try again.
499 */
500 int read_frame(mpg123_handle *fr)
501 {
502 	/* TODO: rework this thing */
503 	int freeformat_count = 0;
504 	unsigned long newhead;
505 	off_t framepos;
506 	int ret;
507 	/* stuff that needs resetting if complete frame reading fails */
508 	int oldsize  = fr->framesize;
509 	int oldphase = fr->halfphase;
510 
511 	/* The counter for the search-first-header loop.
512 	   It is persistent outside the loop to prevent seemingly endless loops
513 	   when repeatedly headers are found that do not have valid followup headers. */
514 	long headcount = 0;
515 
516 	fr->fsizeold=fr->framesize;       /* for Layer3 */
517 
518 	if(halfspeed_do(fr) == 1) return 1;
519 
520 	/* From now on, old frame data is tainted by parsing attempts. */
521 	fr->to_decode = fr->to_ignore = FALSE;
522 
523 	if( fr->p.flags & MPG123_NO_FRANKENSTEIN &&
524 		( (fr->track_frames > 0 && fr->num >= fr->track_frames-1)
525 #ifdef GAPLESS
526 		|| (fr->gapless_frames > 0 && fr->num >= fr->gapless_frames-1)
527 #endif
528 		) )
529 	{
530 		mdebug( "stopping parsing at %"OFF_P
531 			" frames as indicated fixed track length"
532 		,	(off_p)fr->num+1 );
533 		return 0;
534 	}
535 
536 read_again:
537 	/* In case we are looping to find a valid frame, discard any buffered data before the current position.
538 	   This is essential to prevent endless looping, always going back to the beginning when feeder buffer is exhausted. */
539 	if(fr->rd->forget != NULL) fr->rd->forget(fr);
540 
541 	debug2("trying to get frame %"OFF_P" at %"OFF_P, (off_p)fr->num+1, (off_p)fr->rd->tell(fr));
542 	if((ret = fr->rd->head_read(fr,&newhead)) <= 0){ debug1("need more? (%i)", ret); goto read_frame_bad;}
543 
544 init_resync:
545 
546 #ifdef SKIP_JUNK
547 	if(!fr->firsthead && !head_check(newhead))
548 	{
549 		ret = skip_junk(fr, &newhead, &headcount);
550 		JUMP_CONCLUSION(ret);
551 	}
552 #endif
553 
554 	ret = head_check(newhead);
555 	if(ret) ret = decode_header(fr, newhead, &freeformat_count);
556 
557 	JUMP_CONCLUSION(ret); /* That only continues for ret == PARSE_BAD or PARSE_GOOD. */
558 	if(ret == PARSE_BAD)
559 	{ /* Header was not good. */
560 		ret = wetwork(fr, &newhead); /* Messy stuff, handle junk, resync ... */
561 		JUMP_CONCLUSION(ret);
562 		/* Normally, we jumped already. If for some reason everything's fine to continue, do continue. */
563 		if(ret != PARSE_GOOD) goto read_frame_bad;
564 	}
565 
566 	if(!fr->firsthead)
567 	{
568 		ret = fr->p.flags & MPG123_NO_READAHEAD
569 		?	PARSE_GOOD
570 		:	do_readahead(fr, newhead);
571 		/* readahead can fail mit NEED_MORE, in which case we must also make the just read header available again for next go */
572 		if(ret < 0) fr->rd->back_bytes(fr, 4);
573 		JUMP_CONCLUSION(ret);
574 	}
575 
576 	/* Now we should have our valid header and proceed to reading the frame. */
577 
578 	if(fr->p.flags & MPG123_NO_FRANKENSTEIN)
579 	{
580 		if(fr->firsthead && !head_compatible(fr->firsthead, newhead))
581 		{
582 			mdebug( "stopping before reading frame %"OFF_P
583 				" as its header indicates Frankenstein coming for you", (off_p)fr->num );
584 			return 0;
585 		}
586 	}
587 
588 	/* if filepos is invalid, so is framepos */
589 	framepos = fr->rd->tell(fr) - 4;
590 	/* flip/init buffer for Layer 3 */
591 	{
592 		unsigned char *newbuf = fr->bsspace[fr->bsnum]+512;
593 		/* read main data into memory */
594 		debug2("read frame body of %i at %"OFF_P, fr->framesize, framepos+4);
595 		if((ret=fr->rd->read_frame_body(fr,newbuf,fr->framesize))<0)
596 		{
597 			/* if failed: flip back */
598 			debug1("%s", ret == MPG123_NEED_MORE ? "need more" : "read error");
599 			goto read_frame_bad;
600 		}
601 		fr->bsbufold = fr->bsbuf;
602 		fr->bsbuf = newbuf;
603 	}
604 	fr->bsnum = (fr->bsnum + 1) & 1;
605 
606 	if(!fr->firsthead)
607 	{
608 		fr->firsthead = newhead; /* _now_ it's time to store it... the first real header */
609 		/* This is the first header of our current stream segment.
610 		   It is only the actual first header of the whole stream when fr->num is still below zero!
611 		   Think of resyncs where firsthead has been reset for format flexibility. */
612 		if(fr->num < 0)
613 		{
614 			fr->audio_start = framepos;
615 			/* Only check for LAME  tag at beginning of whole stream
616 			   ... when there indeed is one in between, it's the user's problem. */
617 			if(fr->lay == 3 && check_lame_tag(fr) == 1)
618 			{ /* ...in practice, Xing/LAME tags are layer 3 only. */
619 				if(fr->rd->forget != NULL) fr->rd->forget(fr);
620 
621 				fr->oldhead = 0;
622 				goto read_again;
623 			}
624 			/* now adjust volume */
625 			do_rva(fr);
626 		}
627 
628 		debug2("fr->firsthead: %08lx, audio_start: %li", fr->firsthead, (long int)fr->audio_start);
629 	}
630 
631 	set_pointer(fr, 0, 0);
632 
633 	/* Question: How bad does the floating point value get with repeated recomputation?
634 	   Also, considering that we can play the file or parts of many times. */
635 	if(++fr->mean_frames != 0)
636 	{
637 		fr->mean_framesize = ((fr->mean_frames-1)*fr->mean_framesize+compute_bpf(fr)) / fr->mean_frames ;
638 	}
639 	++fr->num; /* 0 for first frame! */
640 	debug4("Frame %"OFF_P" %08lx %i, next filepos=%"OFF_P,
641 	(off_p)fr->num, newhead, fr->framesize, (off_p)fr->rd->tell(fr));
642 	if(!(fr->state_flags & FRAME_FRANKENSTEIN) && (
643 		(fr->track_frames > 0 && fr->num >= fr->track_frames)
644 #ifdef GAPLESS
645 		|| (fr->gapless_frames > 0 && fr->num >= fr->gapless_frames)
646 #endif
647 	))
648 	{
649 		fr->state_flags |= FRAME_FRANKENSTEIN;
650 		if(NOQUIET) fprintf(stderr, "\nWarning: Encountered more data after announced end of track (frame %"OFF_P"/%"OFF_P"). Frankenstein!\n", (off_p)fr->num,
651 #ifdef GAPLESS
652 		fr->gapless_frames > 0 ? (off_p)fr->gapless_frames :
653 #endif
654 		(off_p)fr->track_frames);
655 	}
656 
657 	halfspeed_prepare(fr);
658 
659 	/* index the position */
660 	fr->input_offset = framepos;
661 #ifdef FRAME_INDEX
662 	/* Keep track of true frame positions in our frame index.
663 	   but only do so when we are sure that the frame number is accurate... */
664 	if((fr->state_flags & FRAME_ACCURATE) && FI_NEXT(fr->index, fr->num))
665 	fi_add(&fr->index, framepos);
666 #endif
667 
668 	if(fr->silent_resync > 0) --fr->silent_resync;
669 
670 	if(fr->rd->forget != NULL) fr->rd->forget(fr);
671 
672 	fr->to_decode = fr->to_ignore = TRUE;
673 	if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */
674 
675 	/*
676 		Let's check for header change after deciding that the new one is good
677 		and actually having read a frame.
678 
679 		header_change > 1: decoder structure has to be updated
680 		Preserve header_change value from previous runs if it is serious.
681 		If we still have a big change pending, it should be dealt with outside,
682 		fr->header_change set to zero afterwards.
683 	*/
684 	if(fr->header_change < 2)
685 	{
686 		fr->header_change = 2; /* output format change is possible... */
687 		if(fr->oldhead)        /* check a following header for change */
688 		{
689 			if(fr->oldhead == newhead) fr->header_change = 0;
690 			else
691 			/* Headers that match in this test behave the same for the outside world.
692 			   namely: same decoding routines, same amount of decoded data. */
693 			if(head_compatible(fr->oldhead, newhead))
694 			fr->header_change = 1;
695 			else
696 			{
697 				fr->state_flags |= FRAME_FRANKENSTEIN;
698 				if(NOQUIET)
699 				fprintf(stderr, "\nWarning: Big change (MPEG version, layer, rate). Frankenstein stream?\n");
700 			}
701 		}
702 		else if(fr->firsthead && !head_compatible(fr->firsthead, newhead))
703 		{
704 			fr->state_flags |= FRAME_FRANKENSTEIN;
705 			if(NOQUIET)
706 			fprintf(stderr, "\nWarning: Big change from first (MPEG version, layer, rate). Frankenstein stream?\n");
707 		}
708 	}
709 
710 	fr->oldhead = newhead;
711 
712 	return 1;
713 read_frame_bad:
714 	/* Also if we searched for valid data in vein, we can forget skipped data.
715 	   Otherwise, the feeder would hold every dead old byte in memory until the first valid frame! */
716 	if(fr->rd->forget != NULL) fr->rd->forget(fr);
717 
718 	fr->silent_resync = 0;
719 	if(fr->err == MPG123_OK) fr->err = MPG123_ERR_READER;
720 	fr->framesize = oldsize;
721 	fr->halfphase = oldphase;
722 	/* That return code might be inherited from some feeder action, or reader error. */
723 	return ret;
724 }
725 
726 
727 /*
728  * read ahead and find the next MPEG header, to guess framesize
729  * return value: success code
730  *  PARSE_GOOD: found a valid frame size (stored in the handle).
731  * <0: error codes, possibly from feeder buffer (NEED_MORE)
732  *  PARSE_BAD: cannot get the framesize for some reason and shall silentry try the next possible header (if this is no free format stream after all...)
733  */
734 static int guess_freeformat_framesize(mpg123_handle *fr, unsigned long oldhead)
735 {
736 	long i;
737 	int ret;
738 	unsigned long head;
739 	if(!(fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED)))
740 	{
741 		if(NOQUIET) error("Cannot look for freeformat frame size with non-seekable and non-buffered stream!");
742 
743 		return PARSE_BAD;
744 	}
745 	if((ret=fr->rd->head_read(fr,&head))<=0)
746 	return ret;
747 
748 	/* We are already 4 bytes into it */
749 	for(i=4;i<MAXFRAMESIZE+4;i++)
750 	{
751 		if((ret=fr->rd->head_shift(fr,&head))<=0) return ret;
752 
753 		/* No head_check needed, the mask contains all relevant bits. */
754 		if((head & HDR_SAMEMASK) == (oldhead & HDR_SAMEMASK))
755 		{
756 			fr->rd->back_bytes(fr,i+1);
757 			fr->framesize = i-3;
758 			return PARSE_GOOD; /* Success! */
759 		}
760 	}
761 	fr->rd->back_bytes(fr,i);
762 	return PARSE_BAD;
763 }
764 
765 
766 /*
767  * decode a header and write the information
768  * into the frame structure
769  * Return values are compatible with those of read_frame, namely:
770  *  1: success
771  *  0: no valid header
772  * <0: some error
773  * You are required to do a head_check() before calling!
774  */
775 static int decode_header(mpg123_handle *fr,unsigned long newhead, int *freeformat_count)
776 {
777 #ifdef DEBUG /* Do not waste cycles checking the header twice all the time. */
778 	if(!head_check(newhead))
779 	{
780 		error1("trying to decode obviously invalid header 0x%08lx", newhead);
781 	}
782 #endif
783 	/* For some reason, the layer and sampling freq settings used to be wrapped
784 	   in a weird conditional including MPG123_NO_RESYNC. What was I thinking?
785 	   This information has to be consistent. */
786 	fr->lay = 4 - HDR_LAYER_VAL(newhead);
787 
788 	if(HDR_VERSION_VAL(newhead) & 0x2)
789 	{
790 		fr->lsf = (HDR_VERSION_VAL(newhead) & 0x1) ? 0 : 1;
791 		fr->mpeg25 = 0;
792 		fr->sampling_frequency = HDR_SAMPLERATE_VAL(newhead) + (fr->lsf*3);
793 	}
794 	else
795 	{
796 		fr->lsf = 1;
797 		fr->mpeg25 = 1;
798 		fr->sampling_frequency = 6 + HDR_SAMPLERATE_VAL(newhead);
799 	}
800 
801 	#ifdef DEBUG
802 	/* seen a file where this varies (old lame tag without crc, track with crc) */
803 	if((HDR_CRC_VAL(newhead)^0x1) != fr->error_protection) debug("changed crc bit!");
804 	#endif
805 	fr->error_protection = HDR_CRC_VAL(newhead)^0x1;
806 	fr->bitrate_index    = HDR_BITRATE_VAL(newhead);
807 	fr->padding          = HDR_PADDING_VAL(newhead);
808 	fr->extension        = HDR_PRIVATE_VAL(newhead);
809 	fr->mode             = HDR_CHANNEL_VAL(newhead);
810 	fr->mode_ext         = HDR_CHANEX_VAL(newhead);
811 	fr->copyright        = HDR_COPYRIGHT_VAL(newhead);
812 	fr->original         = HDR_ORIGINAL_VAL(newhead);
813 	fr->emphasis         = HDR_EMPHASIS_VAL(newhead);
814 	fr->freeformat       = !(newhead & HDR_BITRATE);
815 
816 	fr->stereo = (fr->mode == MPG_MD_MONO) ? 1 : 2;
817 
818 	/* we can't use tabsel_123 for freeformat, so trying to guess framesize... */
819 	if(fr->freeformat)
820 	{
821 		/* when we first encounter the frame with freeformat, guess framesize */
822 		if(fr->freeformat_framesize < 0)
823 		{
824 			int ret;
825 			if(fr->p.flags & MPG123_NO_READAHEAD)
826 			{
827 				if(VERBOSE3)
828 					error("Got no free-format frame size and am not allowed to read ahead.");
829 				return PARSE_BAD;
830 			}
831 			*freeformat_count += 1;
832 			if(*freeformat_count > 5)
833 			{
834 				if(VERBOSE3) error("You fooled me too often. Refusing to guess free format frame size _again_.");
835 				return PARSE_BAD;
836 			}
837 			ret = guess_freeformat_framesize(fr, newhead);
838 			if(ret == PARSE_GOOD)
839 			{
840 				fr->freeformat_framesize = fr->framesize - fr->padding;
841 				if(VERBOSE2)
842 				fprintf(stderr, "Note: free format frame size %li\n", fr->freeformat_framesize);
843 			}
844 			else
845 			{
846 				if(ret == MPG123_NEED_MORE)
847 				debug("Need more data to guess free format frame size.");
848 				else if(VERBOSE3)
849 				error("Encountered free format header, but failed to guess frame size.");
850 
851 				return ret;
852 			}
853 		}
854 		/* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */
855 		else
856 		{
857 			fr->framesize = fr->freeformat_framesize + fr->padding;
858 		}
859 	}
860 
861 	switch(fr->lay)
862 	{
863 #ifndef NO_LAYER1
864 		case 1:
865 			fr->spf = 384;
866 			fr->do_layer = do_layer1;
867 			if(!fr->freeformat)
868 			{
869 				long fs = (long) tabsel_123[fr->lsf][0][fr->bitrate_index] * 12000;
870 				fs /= freqs[fr->sampling_frequency];
871 				fs = ((fs+fr->padding)<<2)-4;
872 				fr->framesize = (int)fs;
873 			}
874 		break;
875 #endif
876 #ifndef NO_LAYER2
877 		case 2:
878 			fr->spf = 1152;
879 			fr->do_layer = do_layer2;
880 			if(!fr->freeformat)
881 			{
882 				debug2("bitrate index: %i (%i)", fr->bitrate_index, tabsel_123[fr->lsf][1][fr->bitrate_index] );
883 				long fs = (long) tabsel_123[fr->lsf][1][fr->bitrate_index] * 144000;
884 				fs /= freqs[fr->sampling_frequency];
885 				fs += fr->padding - 4;
886 				fr->framesize = (int)fs;
887 			}
888 		break;
889 #endif
890 #ifndef NO_LAYER3
891 		case 3:
892 			fr->spf = fr->lsf ? 576 : 1152; /* MPEG 2.5 implies LSF.*/
893 			fr->do_layer = do_layer3;
894 			if(fr->lsf)
895 			fr->ssize = (fr->stereo == 1) ? 9 : 17;
896 			else
897 			fr->ssize = (fr->stereo == 1) ? 17 : 32;
898 
899 			if(fr->error_protection)
900 			fr->ssize += 2;
901 
902 			if(!fr->freeformat)
903 			{
904 				long fs = (long) tabsel_123[fr->lsf][2][fr->bitrate_index] * 144000;
905 				fs /= freqs[fr->sampling_frequency]<<(fr->lsf);
906 				fs += fr->padding - 4;
907 				fr->framesize = fs;
908 			}
909 			if(fr->framesize < fr->ssize)
910 			{
911 				if(NOQUIET)
912 					error2( "Frame smaller than mandatory side info (%i < %i)!"
913 					,	fr->framesize, fr->ssize );
914 				return PARSE_BAD;
915 			}
916 		break;
917 #endif
918 		default:
919 			if(NOQUIET) error1("Layer type %i not supported in this build!", fr->lay);
920 
921 			return PARSE_BAD;
922 	}
923 	if (fr->framesize > MAXFRAMESIZE)
924 	{
925 		if(NOQUIET) error1("Frame size too big: %d", fr->framesize+4-fr->padding);
926 
927 		return PARSE_BAD;
928 	}
929 	return PARSE_GOOD;
930 }
931 
932 /* Prepare for bit reading. Two stages:
933   0. Layers 1 and 2, side info for layer 3
934   1. Second call for possible bit reservoir for layer 3 part 2,3.
935      This overwrites side info needed for stage 0.
936 
937   Continuing to read bits after layer 3 side info shall fail unless
938   set_pointer() is called to refresh things.
939 */
940 void set_pointer(mpg123_handle *fr, int part2, long backstep)
941 {
942 	fr->bitindex = 0;
943 	if(fr->lay == 3)
944 	{
945 		if(part2)
946 		{
947 			fr->wordpointer = fr->bsbuf + fr->ssize - backstep;
948 			if(backstep)
949 				memcpy( fr->wordpointer, fr->bsbufold+fr->fsizeold-backstep
950 				,	backstep );
951 			fr->bits_avail = (long)(fr->framesize - fr->ssize + backstep)*8;
952 		}
953 		else
954 		{
955 			fr->wordpointer = fr->bsbuf;
956 			fr->bits_avail  = fr->ssize*8;
957 		}
958 	}
959 	else
960 	{
961 		fr->wordpointer = fr->bsbuf;
962 		fr->bits_avail  = fr->framesize*8;
963 	}
964 }
965 
966 /********************************/
967 
968 double compute_bpf(mpg123_handle *fr)
969 {
970 	return (fr->framesize > 0) ? fr->framesize + 4.0 : 1.0;
971 }
972 
973 int attribute_align_arg mpg123_spf(mpg123_handle *mh)
974 {
975 	if(mh == NULL) return MPG123_ERR;
976 
977 	return mh->firsthead ? mh->spf : MPG123_ERR;
978 }
979 
980 double attribute_align_arg mpg123_tpf(mpg123_handle *fr)
981 {
982 	static int bs[4] = { 0,384,1152,1152 };
983 	double tpf;
984 	if(fr == NULL || !fr->firsthead) return MPG123_ERR;
985 
986 	tpf = (double) bs[fr->lay];
987 	tpf /= freqs[fr->sampling_frequency] << (fr->lsf);
988 	return tpf;
989 }
990 
991 int attribute_align_arg mpg123_position(mpg123_handle *fr, off_t no, off_t buffsize,
992 	off_t  *current_frame,   off_t  *frames_left,
993 	double *current_seconds, double *seconds_left)
994 {
995 	double tpf;
996 	double dt = 0.0;
997 	off_t cur, left;
998 	double curs, lefts;
999 
1000 	if(!fr || !fr->rd) return MPG123_ERR;
1001 
1002 	no += fr->num; /* no starts out as offset */
1003 	cur = no;
1004 	tpf = mpg123_tpf(fr);
1005 	if(buffsize > 0 && fr->af.rate > 0 && fr->af.channels > 0)
1006 	{
1007 		dt = (double) buffsize / fr->af.rate / fr->af.channels;
1008 		if(fr->af.encoding & MPG123_ENC_16) dt *= 0.5;
1009 	}
1010 
1011 	left = 0;
1012 
1013 	if((fr->track_frames != 0) && (fr->track_frames >= fr->num)) left = no < fr->track_frames ? fr->track_frames - no : 0;
1014 	else
1015 	if(fr->rdat.filelen >= 0)
1016 	{
1017 		double bpf;
1018 		off_t t = fr->rd->tell(fr);
1019 		bpf = fr->mean_framesize ? fr->mean_framesize : compute_bpf(fr);
1020 		left = (off_t)((double)(fr->rdat.filelen-t)/bpf);
1021 		/* no can be different for prophetic purposes, file pointer is always associated with fr->num! */
1022 		if(fr->num != no)
1023 		{
1024 			if(fr->num > no) left += fr->num - no;
1025 			else
1026 			{
1027 				if(left >= (no - fr->num)) left -= no - fr->num;
1028 				else left = 0; /* uh, oh! */
1029 			}
1030 		}
1031 		/* I totally don't understand why we should re-estimate the given correct(?) value */
1032 		/* fr->num = (unsigned long)((double)t/bpf); */
1033 	}
1034 
1035 	/* beginning with 0 or 1?*/
1036 	curs = (double) no*tpf-dt;
1037 	lefts = (double)left*tpf+dt;
1038 #if 0
1039 	curs = curs < 0 ? 0.0 : curs;
1040 #endif
1041 	if(left < 0 || lefts < 0)
1042 	{ /* That is the case for non-seekable streams. */
1043 		left  = 0;
1044 		lefts = 0.0;
1045 	}
1046 	if(current_frame != NULL) *current_frame = cur;
1047 	if(frames_left   != NULL) *frames_left   = left;
1048 	if(current_seconds != NULL) *current_seconds = curs;
1049 	if(seconds_left    != NULL) *seconds_left   = lefts;
1050 	return MPG123_OK;
1051 }
1052 
1053 int get_songlen(mpg123_handle *fr,int no)
1054 {
1055 	double tpf;
1056 
1057 	if(!fr)
1058 		return 0;
1059 
1060 	if(no < 0) {
1061 		if(!fr->rd || fr->rdat.filelen < 0)
1062 			return 0;
1063 		no = (int) ((double) fr->rdat.filelen / compute_bpf(fr));
1064 	}
1065 
1066 	tpf = mpg123_tpf(fr);
1067 	return (int) (no*tpf);
1068 }
1069 
1070 /* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */
1071 static int do_readahead(mpg123_handle *fr, unsigned long newhead)
1072 {
1073 	unsigned long nexthead = 0;
1074 	int hd = 0;
1075 	off_t start, oret;
1076 	int ret;
1077 
1078 	if( ! (!fr->firsthead && fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED)) )
1079 	return PARSE_GOOD;
1080 
1081 	start = fr->rd->tell(fr);
1082 
1083 	debug2("doing ahead check with BPF %d at %"OFF_P, fr->framesize+4, (off_p)start);
1084 	/* step framesize bytes forward and read next possible header*/
1085 	if((oret=fr->rd->skip_bytes(fr, fr->framesize))<0)
1086 	{
1087 		if(oret==READER_ERROR && NOQUIET) error("cannot seek!");
1088 
1089 		return oret == MPG123_NEED_MORE ? PARSE_MORE : PARSE_ERR;
1090 	}
1091 
1092 	/* Read header, seek back. */
1093 	hd = fr->rd->head_read(fr,&nexthead);
1094 	if( fr->rd->back_bytes(fr, fr->rd->tell(fr)-start) < 0 )
1095 	{
1096 		if(NOQUIET) error("Cannot seek back!");
1097 
1098 		return PARSE_ERR;
1099 	}
1100 	if(hd == MPG123_NEED_MORE) return PARSE_MORE;
1101 
1102 	debug1("After fetching next header, at %"OFF_P, (off_p)fr->rd->tell(fr));
1103 	if(!hd)
1104 	{
1105 		if(NOQUIET) warning("Cannot read next header, a one-frame stream? Duh...");
1106 		return PARSE_END;
1107 	}
1108 
1109 	debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead);
1110 	if(!head_check(nexthead) || !head_compatible(newhead, nexthead))
1111 	{
1112 		debug("No, the header was not valid, start from beginning...");
1113 		fr->oldhead = 0; /* start over */
1114 		/* try next byte for valid header */
1115 		if((ret=fr->rd->back_bytes(fr, 3))<0)
1116 		{
1117 			if(NOQUIET) error("Cannot seek 3 bytes back!");
1118 
1119 			return PARSE_ERR;
1120 		}
1121 		return PARSE_AGAIN;
1122 	}
1123 	else return PARSE_GOOD;
1124 }
1125 
1126 static int handle_id3v2(mpg123_handle *fr, unsigned long newhead)
1127 {
1128 	int ret;
1129 	fr->oldhead = 0; /* Think about that. Used to be present only for skipping of junk, not resync-style wetwork. */
1130 	ret = parse_new_id3(fr, newhead);
1131 	if     (ret < 0) return ret;
1132 #ifndef NO_ID3V2
1133 	else if(ret > 0){ debug("got ID3v2"); fr->metaflags  |= MPG123_NEW_ID3|MPG123_ID3; }
1134 	else debug("no useful ID3v2");
1135 #endif
1136 	return PARSE_AGAIN;
1137 }
1138 
1139 static int handle_apetag(mpg123_handle *fr, unsigned long newhead)
1140 {
1141 	unsigned char apebuf[28];
1142 	unsigned long val;
1143 	int i, ret;
1144 	/* How many bytes to backpedal to get back to just after the first byte of */
1145 	/* the supposed header. */
1146 	int back_bytes = 3;
1147 	fr->oldhead = 0;
1148 
1149 	debug1("trying to read remaining APE header at %"OFF_P, (off_p)fr->rd->tell(fr));
1150 	/* Apetag headers are 32 bytes, newhead contains 4, read the rest */
1151 	if((ret=fr->rd->fullread(fr,apebuf,28)) < 0)
1152 		return ret;
1153 	back_bytes += ret;
1154 	if(ret < 28)
1155 		goto apetag_bad;
1156 
1157 	debug1("trying to parse APE header at %"OFF_P, (off_p)fr->rd->tell(fr));
1158 	/* Apetags start with "APETAGEX", "APET" is already tested. */
1159 	if(strncmp((char *)apebuf,"AGEX",4) != 0)
1160 		goto apetag_bad;
1161 
1162 	/* Version must be 2.000 / 2000 */
1163 	val = ((unsigned long)apebuf[7]<<24)
1164 	|	((unsigned long)apebuf[6]<<16)
1165 	|	((unsigned long)apebuf[5]<<8)
1166 	|	apebuf[4];
1167 	if(val != 2000)
1168 		goto apetag_bad;
1169 
1170 	/* Last 8 bytes must be 0 */
1171 	for(i=20; i<28; i++)
1172 		if(apebuf[i])
1173 			goto apetag_bad;
1174 
1175 	/* Looks good, skip the rest. */
1176 	val = ((unsigned long)apebuf[11]<<24)
1177 	|	((unsigned long)apebuf[10]<<16)
1178 	|	((unsigned long)apebuf[9]<<8)
1179 	|	apebuf[8];
1180 	debug2( "skipping %lu bytes of APE data at %"OFF_P
1181 	,	val, (off_p)fr->rd->tell(fr) );
1182 	/* If encountering EOF here, things are just at an end. */
1183 	if((ret=fr->rd->skip_bytes(fr,val)) < 0)
1184 		return ret;
1185 
1186 	return PARSE_AGAIN;
1187 
1188 apetag_bad:
1189 	debug("no proper APE tag found, seeking back");
1190 	if(fr->rd->back_bytes(fr,back_bytes) < 0 && NOQUIET)
1191 		error1("Cannot seek %d bytes back!", back_bytes);
1192 
1193 	return PARSE_AGAIN; /* Give the resync code a chance to fix things */
1194 }
1195 
1196 /* Advance a byte in stream to get next possible header and forget
1197    buffered data if possible (for feed reader). */
1198 #define FORGET_INTERVAL 1024 /* Used by callers to set forget flag each <n> bytes. */
1199 static int forget_head_shift(mpg123_handle *fr, unsigned long *newheadp, int forget)
1200 {
1201 	int ret;
1202 	if((ret=fr->rd->head_shift(fr,newheadp))<=0) return ret;
1203 	/* Try to forget buffered data as early as possible to speed up parsing where
1204 	   new data needs to be added for resync (and things would be re-parsed again
1205 	   and again because of the start from beginning after hitting end). */
1206 	if(forget && fr->rd->forget != NULL)
1207 	{
1208 		/* Ensure that the last 4 bytes stay in buffers for reading the header
1209 		   anew. */
1210 		if(!fr->rd->back_bytes(fr, 4))
1211 		{
1212 			fr->rd->forget(fr);
1213 			fr->rd->back_bytes(fr, -4);
1214 		}
1215 	}
1216 	return ret; /* No surprise here, error already triggered early return. */
1217 }
1218 
1219 /* watch out for junk/tags on beginning of stream by invalid header */
1220 static int skip_junk(mpg123_handle *fr, unsigned long *newheadp, long *headcount)
1221 {
1222 	int ret;
1223 	int freeformat_count = 0;
1224 	long limit = 65536;
1225 	unsigned long newhead = *newheadp;
1226 	unsigned int forgetcount = 0;
1227 	/* check for id3v2; first three bytes (of 4) are "ID3" */
1228 	if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1229 	{
1230 		return handle_id3v2(fr, newhead);
1231 	}
1232 	else if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Junk at the beginning (0x%08lx)\n",newhead);
1233 
1234 	/* I even saw RIFF headers at the beginning of MPEG streams ;( */
1235 	if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F')
1236 	{
1237 		if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr, "Note: Looks like a RIFF header.\n");
1238 
1239 		if((ret=fr->rd->head_read(fr,&newhead))<=0) return ret;
1240 
1241 		while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a')
1242 		{
1243 			if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1244 			if((ret=forget_head_shift(fr,&newhead,!forgetcount))<=0) return ret;
1245 		}
1246 		if((ret=fr->rd->head_read(fr,&newhead))<=0) return ret;
1247 
1248 		if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Skipped RIFF header!\n");
1249 
1250 		fr->oldhead = 0;
1251 		*newheadp = newhead;
1252 		return PARSE_AGAIN;
1253 	}
1254 
1255 	/*
1256 		Unhandled junk... just continue search for a header, stepping in single bytes through next 64K.
1257 		This is rather identical to the resync loop.
1258 	*/
1259 	debug("searching for header...");
1260 	*newheadp = 0; /* Invalidate the external value. */
1261 	ret = 0; /* We will check the value after the loop. */
1262 
1263 	/* We prepare for at least the 64K bytes as usual, unless
1264 	   user explicitly wanted more (even infinity). Never less. */
1265 	if(fr->p.resync_limit < 0 || fr->p.resync_limit > limit)
1266 	limit = fr->p.resync_limit;
1267 
1268 	do
1269 	{
1270 		++(*headcount);
1271 		if(limit >= 0 && *headcount >= limit) break;
1272 
1273 		if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1274 		if((ret=forget_head_shift(fr, &newhead, !forgetcount))<=0) return ret;
1275 
1276 		if(head_check(newhead) && (ret=decode_header(fr, newhead, &freeformat_count))) break;
1277 	} while(1);
1278 	if(ret<0) return ret;
1279 
1280 	if(limit >= 0 && *headcount >= limit)
1281 	{
1282 		if(NOQUIET) error1("Giving up searching valid MPEG header after %li bytes of junk.", *headcount);
1283 		fr->err = MPG123_RESYNC_FAIL;
1284 		return PARSE_ERR;
1285 	}
1286 	else debug1("hopefully found one at %"OFF_P, (off_p)fr->rd->tell(fr));
1287 
1288 	/* If the new header ist good, it is already decoded. */
1289 	*newheadp = newhead;
1290 	return PARSE_GOOD;
1291 }
1292 
1293 /* The newhead is bad, so let's check if it is something special, otherwise just resync. */
1294 static int wetwork(mpg123_handle *fr, unsigned long *newheadp)
1295 {
1296 	int ret = PARSE_ERR;
1297 	unsigned long newhead = *newheadp;
1298 	*newheadp = 0;
1299 
1300 	/* Classic ID3 tags. Read, then start parsing again. */
1301 	if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8))
1302 	{
1303 		fr->id3buf[0] = (unsigned char) ((newhead >> 24) & 0xff);
1304 		fr->id3buf[1] = (unsigned char) ((newhead >> 16) & 0xff);
1305 		fr->id3buf[2] = (unsigned char) ((newhead >> 8)  & 0xff);
1306 		fr->id3buf[3] = (unsigned char) ( newhead        & 0xff);
1307 
1308 		if((ret=fr->rd->fullread(fr,fr->id3buf+4,124)) < 0) return ret;
1309 
1310 		fr->metaflags  |= MPG123_NEW_ID3|MPG123_ID3;
1311 		fr->rdat.flags |= READER_ID3TAG; /* that marks id3v1 */
1312 		if(VERBOSE3) fprintf(stderr,"Note: Skipped ID3v1 tag.\n");
1313 
1314 		return PARSE_AGAIN;
1315 	}
1316 	/* This is similar to initial junk skipping code... */
1317 	/* Check for id3v2; first three bytes (of 4) are "ID3" */
1318 	if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1319 	{
1320 		return handle_id3v2(fr, newhead);
1321 	}
1322 	/* Check for an apetag header */
1323 	if(newhead == ('A'<<24)+('P'<<16)+('E'<<8)+'T')
1324 	{
1325 		return handle_apetag(fr, newhead);
1326 	}
1327 	else if(NOQUIET && fr->silent_resync == 0)
1328 	{
1329 		fprintf(stderr,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset %"OFF_P".\n",
1330 			newhead, (off_p)fr->rd->tell(fr)-4);
1331 	}
1332 
1333 	/* Now we got something bad at hand, try to recover. */
1334 
1335 	if(NOQUIET && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n");
1336 
1337 	if( !(fr->p.flags & MPG123_NO_RESYNC) )
1338 	{
1339 		long try = 0;
1340 		long limit = fr->p.resync_limit;
1341 		unsigned int forgetcount = 0;
1342 
1343 		/* If a resync is needed the bitreservoir of previous frames is no longer valid */
1344 		fr->bitreservoir = 0;
1345 
1346 		if(NOQUIET && fr->silent_resync == 0) fprintf(stderr, "Note: Trying to resync...\n");
1347 
1348 		do /* ... shift the header with additional single bytes until be found something that could be a header. */
1349 		{
1350 			++try;
1351 			if(limit >= 0 && try >= limit) break;
1352 
1353 			if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1354 			if((ret=forget_head_shift(fr,&newhead,!forgetcount)) <= 0)
1355 			{
1356 				*newheadp = newhead;
1357 				if(NOQUIET) fprintf (stderr, "Note: Hit end of (available) data during resync.\n");
1358 
1359 				return ret ? ret : PARSE_END;
1360 			}
1361 			if(VERBOSE3) debug3("resync try %li at %"OFF_P", got newhead 0x%08lx", try, (off_p)fr->rd->tell(fr),  newhead);
1362 		} while(!head_check(newhead));
1363 
1364 		*newheadp = newhead;
1365 		if(NOQUIET && fr->silent_resync == 0) fprintf (stderr, "Note: Skipped %li bytes in input.\n", try);
1366 
1367 		/* Now we either got something that could be a header, or we gave up. */
1368 		if(limit >= 0 && try >= limit)
1369 		{
1370 			if(NOQUIET)
1371 			error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try);
1372 
1373 			fr->err = MPG123_RESYNC_FAIL;
1374 			return PARSE_ERR;
1375 		}
1376 		else
1377 		{
1378 			debug1("Found possibly valid header 0x%lx... unsetting oldhead to reinit stream.", newhead);
1379 			fr->oldhead = 0;
1380 			return PARSE_RESYNC;
1381 		}
1382 	}
1383 	else
1384 	{
1385 		if(NOQUIET) error("not attempting to resync...");
1386 
1387 		fr->err = MPG123_OUT_OF_SYNC;
1388 		return PARSE_ERR;
1389 	}
1390 	/* Control never goes here... we return before that. */
1391 }
1392