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