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 
frame_bitrate(mpg123_handle * fr)74 int frame_bitrate(mpg123_handle *fr)
75 {
76 	return tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index];
77 }
78 
frame_freq(mpg123_handle * fr)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...? */
head_check(unsigned long head)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. */
bit_read_long(unsigned char * buf,int * offset)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 
bit_read_short(unsigned char * buf,int * offset)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 
check_lame_tag(mpg123_handle * fr)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. */
header_mono(unsigned long newhead)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 */
head_compatible(unsigned long fred,unsigned long bret)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 
halfspeed_prepare(mpg123_handle * fr)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. */
halfspeed_do(mpg123_handle * fr)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 */
read_frame(mpg123_handle * fr)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 read_again:
513 	/* In case we are looping to find a valid frame, discard any buffered data before the current position.
514 	   This is essential to prevent endless looping, always going back to the beginning when feeder buffer is exhausted. */
515 	if(fr->rd->forget != NULL) fr->rd->forget(fr);
516 
517 	debug2("trying to get frame %"OFF_P" at %"OFF_P, (off_p)fr->num+1, (off_p)fr->rd->tell(fr));
518 	if((ret = fr->rd->head_read(fr,&newhead)) <= 0){ debug1("need more? (%i)", ret); goto read_frame_bad;}
519 
520 init_resync:
521 
522 #ifdef SKIP_JUNK
523 	if(!fr->firsthead && !head_check(newhead))
524 	{
525 		ret = skip_junk(fr, &newhead, &headcount);
526 		JUMP_CONCLUSION(ret);
527 	}
528 #endif
529 
530 	ret = head_check(newhead);
531 	if(ret) ret = decode_header(fr, newhead, &freeformat_count);
532 
533 	JUMP_CONCLUSION(ret); /* That only continues for ret == PARSE_BAD or PARSE_GOOD. */
534 	if(ret == PARSE_BAD)
535 	{ /* Header was not good. */
536 		ret = wetwork(fr, &newhead); /* Messy stuff, handle junk, resync ... */
537 		JUMP_CONCLUSION(ret);
538 		/* Normally, we jumped already. If for some reason everything's fine to continue, do continue. */
539 		if(ret != PARSE_GOOD) goto read_frame_bad;
540 	}
541 
542 	if(!fr->firsthead)
543 	{
544 		ret = do_readahead(fr, newhead);
545 		/* readahead can fail mit NEED_MORE, in which case we must also make the just read header available again for next go */
546 		if(ret < 0) fr->rd->back_bytes(fr, 4);
547 		JUMP_CONCLUSION(ret);
548 	}
549 
550 	/* Now we should have our valid header and proceed to reading the frame. */
551 
552 	/* if filepos is invalid, so is framepos */
553 	framepos = fr->rd->tell(fr) - 4;
554 	/* flip/init buffer for Layer 3 */
555 	{
556 		unsigned char *newbuf = fr->bsspace[fr->bsnum]+512;
557 		/* read main data into memory */
558 		if((ret=fr->rd->read_frame_body(fr,newbuf,fr->framesize))<0)
559 		{
560 			/* if failed: flip back */
561 			debug("need more?");
562 			goto read_frame_bad;
563 		}
564 		fr->bsbufold = fr->bsbuf;
565 		fr->bsbuf = newbuf;
566 	}
567 	fr->bsnum = (fr->bsnum + 1) & 1;
568 
569 	if(!fr->firsthead)
570 	{
571 		fr->firsthead = newhead; /* _now_ it's time to store it... the first real header */
572 		/* This is the first header of our current stream segment.
573 		   It is only the actual first header of the whole stream when fr->num is still below zero!
574 		   Think of resyncs where firsthead has been reset for format flexibility. */
575 		if(fr->num < 0)
576 		{
577 			fr->audio_start = framepos;
578 			/* Only check for LAME  tag at beginning of whole stream
579 			   ... when there indeed is one in between, it's the user's problem. */
580 			if(fr->lay == 3 && check_lame_tag(fr) == 1)
581 			{ /* ...in practice, Xing/LAME tags are layer 3 only. */
582 				if(fr->rd->forget != NULL) fr->rd->forget(fr);
583 
584 				fr->oldhead = 0;
585 				goto read_again;
586 			}
587 			/* now adjust volume */
588 			do_rva(fr);
589 		}
590 
591 		debug2("fr->firsthead: %08lx, audio_start: %li", fr->firsthead, (long int)fr->audio_start);
592 	}
593 
594   fr->bitindex = 0;
595   fr->wordpointer = (unsigned char *) fr->bsbuf;
596 	/* Question: How bad does the floating point value get with repeated recomputation?
597 	   Also, considering that we can play the file or parts of many times. */
598 	if(++fr->mean_frames != 0)
599 	{
600 		fr->mean_framesize = ((fr->mean_frames-1)*fr->mean_framesize+compute_bpf(fr)) / fr->mean_frames ;
601 	}
602 	++fr->num; /* 0 for first frame! */
603 	debug4("Frame %"OFF_P" %08lx %i, next filepos=%"OFF_P,
604 	(off_p)fr->num, newhead, fr->framesize, (off_p)fr->rd->tell(fr));
605 	if(!(fr->state_flags & FRAME_FRANKENSTEIN) && (
606 		(fr->track_frames > 0 && fr->num >= fr->track_frames)
607 #ifdef GAPLESS
608 		|| (fr->gapless_frames > 0 && fr->num >= fr->gapless_frames)
609 #endif
610 	))
611 	{
612 		fr->state_flags |= FRAME_FRANKENSTEIN;
613 		if(NOQUIET) fprintf(stderr, "\nWarning: Encountered more data after announced end of track (frame %"OFF_P"/%"OFF_P"). Frankenstein!\n", (off_p)fr->num,
614 #ifdef GAPLESS
615 		fr->gapless_frames > 0 ? (off_p)fr->gapless_frames :
616 #endif
617 		(off_p)fr->track_frames);
618 	}
619 
620 	halfspeed_prepare(fr);
621 
622 	/* index the position */
623 	fr->input_offset = framepos;
624 #ifdef FRAME_INDEX
625 	/* Keep track of true frame positions in our frame index.
626 	   but only do so when we are sure that the frame number is accurate... */
627 	if((fr->state_flags & FRAME_ACCURATE) && FI_NEXT(fr->index, fr->num))
628 	fi_add(&fr->index, framepos);
629 #endif
630 
631 	if(fr->silent_resync > 0) --fr->silent_resync;
632 
633 	if(fr->rd->forget != NULL) fr->rd->forget(fr);
634 
635 	fr->to_decode = fr->to_ignore = TRUE;
636 	if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */
637 
638 	/*
639 		Let's check for header change after deciding that the new one is good
640 		and actually having read a frame.
641 
642 		header_change > 1: decoder structure has to be updated
643 		Preserve header_change value from previous runs if it is serious.
644 		If we still have a big change pending, it should be dealt with outside,
645 		fr->header_change set to zero afterwards.
646 	*/
647 	if(fr->header_change < 2)
648 	{
649 		fr->header_change = 2; /* output format change is possible... */
650 		if(fr->oldhead)        /* check a following header for change */
651 		{
652 			if(fr->oldhead == newhead) fr->header_change = 0;
653 			else
654 			/* Headers that match in this test behave the same for the outside world.
655 			   namely: same decoding routines, same amount of decoded data. */
656 			if(head_compatible(fr->oldhead, newhead))
657 			fr->header_change = 1;
658 			else
659 			{
660 				fr->state_flags |= FRAME_FRANKENSTEIN;
661 				if(NOQUIET)
662 				fprintf(stderr, "\nWarning: Big change (MPEG version, layer, rate). Frankenstein stream?\n");
663 			}
664 		}
665 		else if(fr->firsthead && !head_compatible(fr->firsthead, newhead))
666 		{
667 			fr->state_flags |= FRAME_FRANKENSTEIN;
668 			if(NOQUIET)
669 			fprintf(stderr, "\nWarning: Big change from first (MPEG version, layer, rate). Frankenstein stream?\n");
670 		}
671 	}
672 
673 	fr->oldhead = newhead;
674 
675 	return 1;
676 read_frame_bad:
677 	/* Also if we searched for valid data in vein, we can forget skipped data.
678 	   Otherwise, the feeder would hold every dead old byte in memory until the first valid frame! */
679 	if(fr->rd->forget != NULL) fr->rd->forget(fr);
680 
681 	fr->silent_resync = 0;
682 	if(fr->err == MPG123_OK) fr->err = MPG123_ERR_READER;
683 	fr->framesize = oldsize;
684 	fr->halfphase = oldphase;
685 	/* That return code might be inherited from some feeder action, or reader error. */
686 	return ret;
687 }
688 
689 
690 /*
691  * read ahead and find the next MPEG header, to guess framesize
692  * return value: success code
693  *  PARSE_GOOD: found a valid frame size (stored in the handle).
694  * <0: error codes, possibly from feeder buffer (NEED_MORE)
695  *  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...)
696  */
guess_freeformat_framesize(mpg123_handle * fr,unsigned long oldhead)697 static int guess_freeformat_framesize(mpg123_handle *fr, unsigned long oldhead)
698 {
699 	long i;
700 	int ret;
701 	unsigned long head;
702 	if(!(fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED)))
703 	{
704 		if(NOQUIET) error("Cannot look for freeformat frame size with non-seekable and non-buffered stream!");
705 
706 		return PARSE_BAD;
707 	}
708 	if((ret=fr->rd->head_read(fr,&head))<=0)
709 	return ret;
710 
711 	/* We are already 4 bytes into it */
712 	for(i=4;i<MAXFRAMESIZE+4;i++)
713 	{
714 		if((ret=fr->rd->head_shift(fr,&head))<=0) return ret;
715 
716 		/* No head_check needed, the mask contains all relevant bits. */
717 		if((head & HDR_SAMEMASK) == (oldhead & HDR_SAMEMASK))
718 		{
719 			fr->rd->back_bytes(fr,i+1);
720 			fr->framesize = i-3;
721 			return PARSE_GOOD; /* Success! */
722 		}
723 	}
724 	fr->rd->back_bytes(fr,i);
725 	return PARSE_BAD;
726 }
727 
728 
729 /*
730  * decode a header and write the information
731  * into the frame structure
732  * Return values are compatible with those of read_frame, namely:
733  *  1: success
734  *  0: no valid header
735  * <0: some error
736  * You are required to do a head_check() before calling!
737  */
decode_header(mpg123_handle * fr,unsigned long newhead,int * freeformat_count)738 static int decode_header(mpg123_handle *fr,unsigned long newhead, int *freeformat_count)
739 {
740 #ifdef DEBUG /* Do not waste cycles checking the header twice all the time. */
741 	if(!head_check(newhead))
742 	{
743 		error1("trying to decode obviously invalid header 0x%08lx", newhead);
744 	}
745 #endif
746 	/* For some reason, the layer and sampling freq settings used to be wrapped
747 	   in a weird conditional including MPG123_NO_RESYNC. What was I thinking?
748 	   This information has to be consistent. */
749 	fr->lay = 4 - HDR_LAYER_VAL(newhead);
750 
751 	if(HDR_VERSION_VAL(newhead) & 0x2)
752 	{
753 		fr->lsf = (HDR_VERSION_VAL(newhead) & 0x1) ? 0 : 1;
754 		fr->mpeg25 = 0;
755 		fr->sampling_frequency = HDR_SAMPLERATE_VAL(newhead) + (fr->lsf*3);
756 	}
757 	else
758 	{
759 		fr->lsf = 1;
760 		fr->mpeg25 = 1;
761 		fr->sampling_frequency = 6 + HDR_SAMPLERATE_VAL(newhead);
762 	}
763 
764 	#ifdef DEBUG
765 	/* seen a file where this varies (old lame tag without crc, track with crc) */
766 	if((HDR_CRC_VAL(newhead)^0x1) != fr->error_protection) debug("changed crc bit!");
767 	#endif
768 	fr->error_protection = HDR_CRC_VAL(newhead)^0x1;
769 	fr->bitrate_index    = HDR_BITRATE_VAL(newhead);
770 	fr->padding          = HDR_PADDING_VAL(newhead);
771 	fr->extension        = HDR_PRIVATE_VAL(newhead);
772 	fr->mode             = HDR_CHANNEL_VAL(newhead);
773 	fr->mode_ext         = HDR_CHANEX_VAL(newhead);
774 	fr->copyright        = HDR_COPYRIGHT_VAL(newhead);
775 	fr->original         = HDR_ORIGINAL_VAL(newhead);
776 	fr->emphasis         = HDR_EMPHASIS_VAL(newhead);
777 	fr->freeformat       = !(newhead & HDR_BITRATE);
778 
779 	fr->stereo = (fr->mode == MPG_MD_MONO) ? 1 : 2;
780 
781 	/* we can't use tabsel_123 for freeformat, so trying to guess framesize... */
782 	if(fr->freeformat)
783 	{
784 		/* when we first encounter the frame with freeformat, guess framesize */
785 		if(fr->freeformat_framesize < 0)
786 		{
787 			int ret;
788 			*freeformat_count += 1;
789 			if(*freeformat_count > 5)
790 			{
791 				if(VERBOSE3) error("You fooled me too often. Refusing to guess free format frame size _again_.");
792 				return PARSE_BAD;
793 			}
794 			ret = guess_freeformat_framesize(fr, newhead);
795 			if(ret == PARSE_GOOD)
796 			{
797 				fr->freeformat_framesize = fr->framesize - fr->padding;
798 				if(VERBOSE2)
799 				fprintf(stderr, "Note: free format frame size %li\n", fr->freeformat_framesize);
800 			}
801 			else
802 			{
803 				if(ret == MPG123_NEED_MORE)
804 				debug("Need more data to guess free format frame size.");
805 				else if(VERBOSE3)
806 				error("Encountered free format header, but failed to guess frame size.");
807 
808 				return ret;
809 			}
810 		}
811 		/* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */
812 		else
813 		{
814 			fr->framesize = fr->freeformat_framesize + fr->padding;
815 		}
816 	}
817 
818 	switch(fr->lay)
819 	{
820 #ifndef NO_LAYER1
821 		case 1:
822 			fr->spf = 384;
823 			fr->do_layer = do_layer1;
824 			if(!fr->freeformat)
825 			{
826 				fr->framesize  = (long) tabsel_123[fr->lsf][0][fr->bitrate_index] * 12000;
827 				fr->framesize /= freqs[fr->sampling_frequency];
828 				fr->framesize  = ((fr->framesize+fr->padding)<<2)-4;
829 			}
830 		break;
831 #endif
832 #ifndef NO_LAYER2
833 		case 2:
834 			fr->spf = 1152;
835 			fr->do_layer = do_layer2;
836 			if(!fr->freeformat)
837 			{
838 				debug2("bitrate index: %i (%i)", fr->bitrate_index, tabsel_123[fr->lsf][1][fr->bitrate_index] );
839 				fr->framesize = (long) tabsel_123[fr->lsf][1][fr->bitrate_index] * 144000;
840 				fr->framesize /= freqs[fr->sampling_frequency];
841 				fr->framesize += fr->padding - 4;
842 			}
843 		break;
844 #endif
845 #ifndef NO_LAYER3
846 		case 3:
847 			fr->spf = fr->lsf ? 576 : 1152; /* MPEG 2.5 implies LSF.*/
848 			fr->do_layer = do_layer3;
849 			if(fr->lsf)
850 			fr->ssize = (fr->stereo == 1) ? 9 : 17;
851 			else
852 			fr->ssize = (fr->stereo == 1) ? 17 : 32;
853 
854 			if(fr->error_protection)
855 			fr->ssize += 2;
856 
857 			if(!fr->freeformat)
858 			{
859 				fr->framesize  = (long) tabsel_123[fr->lsf][2][fr->bitrate_index] * 144000;
860 				fr->framesize /= freqs[fr->sampling_frequency]<<(fr->lsf);
861 				fr->framesize = fr->framesize + fr->padding - 4;
862 			}
863 		break;
864 #endif
865 		default:
866 			if(NOQUIET) error1("Layer type %i not supported in this build!", fr->lay);
867 
868 			return PARSE_BAD;
869 	}
870 	if (fr->framesize > MAXFRAMESIZE)
871 	{
872 		if(NOQUIET) error1("Frame size too big: %d", fr->framesize+4-fr->padding);
873 
874 		return PARSE_BAD;
875 	}
876 	return PARSE_GOOD;
877 }
878 
set_pointer(mpg123_handle * fr,long backstep)879 void set_pointer(mpg123_handle *fr, long backstep)
880 {
881 	fr->wordpointer = fr->bsbuf + fr->ssize - backstep;
882 	if (backstep)
883 	memcpy(fr->wordpointer,fr->bsbufold+fr->fsizeold-backstep,backstep);
884 
885 	fr->bitindex = 0;
886 }
887 
888 /********************************/
889 
compute_bpf(mpg123_handle * fr)890 double compute_bpf(mpg123_handle *fr)
891 {
892 	double bpf;
893 
894 	switch(fr->lay)
895 	{
896 		case 1:
897 			bpf = tabsel_123[fr->lsf][0][fr->bitrate_index];
898 			bpf *= 12000.0 * 4.0;
899 			bpf /= freqs[fr->sampling_frequency] <<(fr->lsf);
900 		break;
901 		case 2:
902 		case 3:
903 			bpf = tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index];
904 			bpf *= 144000;
905 			bpf /= freqs[fr->sampling_frequency] << (fr->lsf);
906 		break;
907 		default:
908 			bpf = 1.0;
909 	}
910 
911 	return bpf;
912 }
913 
mpg123_spf(mpg123_handle * mh)914 int attribute_align_arg mpg123_spf(mpg123_handle *mh)
915 {
916 	if(mh == NULL) return MPG123_ERR;
917 
918 	return mh->firsthead ? mh->spf : MPG123_ERR;
919 }
920 
mpg123_tpf(mpg123_handle * fr)921 double attribute_align_arg mpg123_tpf(mpg123_handle *fr)
922 {
923 	static int bs[4] = { 0,384,1152,1152 };
924 	double tpf;
925 	if(fr == NULL || !fr->firsthead) return MPG123_ERR;
926 
927 	tpf = (double) bs[fr->lay];
928 	tpf /= freqs[fr->sampling_frequency] << (fr->lsf);
929 	return tpf;
930 }
931 
mpg123_position(mpg123_handle * fr,off_t no,off_t buffsize,off_t * current_frame,off_t * frames_left,double * current_seconds,double * seconds_left)932 int attribute_align_arg mpg123_position(mpg123_handle *fr, off_t no, off_t buffsize,
933 	off_t  *current_frame,   off_t  *frames_left,
934 	double *current_seconds, double *seconds_left)
935 {
936 	double tpf;
937 	double dt = 0.0;
938 	off_t cur, left;
939 	double curs, lefts;
940 
941 	if(!fr || !fr->rd) return MPG123_ERR;
942 
943 	no += fr->num; /* no starts out as offset */
944 	cur = no;
945 	tpf = mpg123_tpf(fr);
946 	if(buffsize > 0 && fr->af.rate > 0 && fr->af.channels > 0)
947 	{
948 		dt = (double) buffsize / fr->af.rate / fr->af.channels;
949 		if(fr->af.encoding & MPG123_ENC_16) dt *= 0.5;
950 	}
951 
952 	left = 0;
953 
954 	if((fr->track_frames != 0) && (fr->track_frames >= fr->num)) left = no < fr->track_frames ? fr->track_frames - no : 0;
955 	else
956 	if(fr->rdat.filelen >= 0)
957 	{
958 		double bpf;
959 		off_t t = fr->rd->tell(fr);
960 		bpf = fr->mean_framesize ? fr->mean_framesize : compute_bpf(fr);
961 		left = (off_t)((double)(fr->rdat.filelen-t)/bpf);
962 		/* no can be different for prophetic purposes, file pointer is always associated with fr->num! */
963 		if(fr->num != no)
964 		{
965 			if(fr->num > no) left += fr->num - no;
966 			else
967 			{
968 				if(left >= (no - fr->num)) left -= no - fr->num;
969 				else left = 0; /* uh, oh! */
970 			}
971 		}
972 		/* I totally don't understand why we should re-estimate the given correct(?) value */
973 		/* fr->num = (unsigned long)((double)t/bpf); */
974 	}
975 
976 	/* beginning with 0 or 1?*/
977 	curs = (double) no*tpf-dt;
978 	lefts = (double)left*tpf+dt;
979 #if 0
980 	curs = curs < 0 ? 0.0 : curs;
981 #endif
982 	if(left < 0 || lefts < 0)
983 	{ /* That is the case for non-seekable streams. */
984 		left  = 0;
985 		lefts = 0.0;
986 	}
987 	if(current_frame != NULL) *current_frame = cur;
988 	if(frames_left   != NULL) *frames_left   = left;
989 	if(current_seconds != NULL) *current_seconds = curs;
990 	if(seconds_left    != NULL) *seconds_left   = lefts;
991 	return MPG123_OK;
992 }
993 
get_songlen(mpg123_handle * fr,int no)994 int get_songlen(mpg123_handle *fr,int no)
995 {
996 	double tpf;
997 
998 	if(!fr)
999 		return 0;
1000 
1001 	if(no < 0) {
1002 		if(!fr->rd || fr->rdat.filelen < 0)
1003 			return 0;
1004 		no = (int) ((double) fr->rdat.filelen / compute_bpf(fr));
1005 	}
1006 
1007 	tpf = mpg123_tpf(fr);
1008 	return (int) (no*tpf);
1009 }
1010 
1011 /* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */
do_readahead(mpg123_handle * fr,unsigned long newhead)1012 static int do_readahead(mpg123_handle *fr, unsigned long newhead)
1013 {
1014 	unsigned long nexthead = 0;
1015 	int hd = 0;
1016 	off_t start, oret;
1017 	int ret;
1018 
1019 	if( ! (!fr->firsthead && fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED)) )
1020 	return PARSE_GOOD;
1021 
1022 	start = fr->rd->tell(fr);
1023 
1024 	debug2("doing ahead check with BPF %d at %"OFF_P, fr->framesize+4, (off_p)start);
1025 	/* step framesize bytes forward and read next possible header*/
1026 	if((oret=fr->rd->skip_bytes(fr, fr->framesize))<0)
1027 	{
1028 		if(oret==READER_ERROR && NOQUIET) error("cannot seek!");
1029 
1030 		return oret == MPG123_NEED_MORE ? PARSE_MORE : PARSE_ERR;
1031 	}
1032 
1033 	/* Read header, seek back. */
1034 	hd = fr->rd->head_read(fr,&nexthead);
1035 	if( fr->rd->back_bytes(fr, fr->rd->tell(fr)-start) < 0 )
1036 	{
1037 		if(NOQUIET) error("Cannot seek back!");
1038 
1039 		return PARSE_ERR;
1040 	}
1041 	if(hd == MPG123_NEED_MORE) return PARSE_MORE;
1042 
1043 	debug1("After fetching next header, at %"OFF_P, (off_p)fr->rd->tell(fr));
1044 	if(!hd)
1045 	{
1046 		if(NOQUIET) warning("Cannot read next header, a one-frame stream? Duh...");
1047 		return PARSE_END;
1048 	}
1049 
1050 	debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead);
1051 	if(!head_check(nexthead) || !head_compatible(newhead, nexthead))
1052 	{
1053 		debug("No, the header was not valid, start from beginning...");
1054 		fr->oldhead = 0; /* start over */
1055 		/* try next byte for valid header */
1056 		if((ret=fr->rd->back_bytes(fr, 3))<0)
1057 		{
1058 			if(NOQUIET) error("Cannot seek 3 bytes back!");
1059 
1060 			return PARSE_ERR;
1061 		}
1062 		return PARSE_AGAIN;
1063 	}
1064 	else return PARSE_GOOD;
1065 }
1066 
handle_id3v2(mpg123_handle * fr,unsigned long newhead)1067 static int handle_id3v2(mpg123_handle *fr, unsigned long newhead)
1068 {
1069 	int ret;
1070 	fr->oldhead = 0; /* Think about that. Used to be present only for skipping of junk, not resync-style wetwork. */
1071 	ret = parse_new_id3(fr, newhead);
1072 	if     (ret < 0) return ret;
1073 #ifndef NO_ID3V2
1074 	else if(ret > 0){ debug("got ID3v2"); fr->metaflags  |= MPG123_NEW_ID3|MPG123_ID3; }
1075 	else debug("no useful ID3v2");
1076 #endif
1077 	return PARSE_AGAIN;
1078 }
1079 
handle_apetag(mpg123_handle * fr,unsigned long newhead)1080 static int handle_apetag(mpg123_handle *fr, unsigned long newhead)
1081 {
1082 	unsigned char apebuf[28];
1083 	unsigned long val;
1084 	int i, ret;
1085 
1086 	fr->oldhead = 0;
1087 
1088 	/* Apetag headers are 32 bytes, newhead contains 4, read the rest */
1089 	if((ret=fr->rd->fullread(fr,apebuf,28)) < 0) return ret;
1090 
1091 	/* Apetags start with "APETAGEX", "APET" is already tested. */
1092 	if(strncmp((char *)apebuf,"AGEX",4) != 0)
1093 		goto apetag_bad;
1094 
1095 	/* Version must be 2.000 / 2000 */
1096 	val = (apebuf[7]<<24)|(apebuf[6]<<16)|(apebuf[5]<<8)|apebuf[4];
1097 	if(val != 2000)
1098 		goto apetag_bad;
1099 
1100 	/* Last 8 bytes must be 0 */
1101 	for(i=20; i<28; i++)
1102 		if(apebuf[i])
1103 			goto apetag_bad;
1104 
1105 	/* Looks good, skip the rest. */
1106 	val = (apebuf[11]<<24)|(apebuf[10]<<16)|(apebuf[9]<<8)|apebuf[8];
1107 	if((ret=fr->rd->skip_bytes(fr,val)) < 0) return ret;
1108 
1109 	return PARSE_AGAIN;
1110 
1111 apetag_bad:
1112 	if(fr->rd->back_bytes(fr,31) < 0 && NOQUIET)
1113 		error("Cannot seek 31 bytes back!");
1114 
1115 	return PARSE_AGAIN; /* Give the resync code a chance to fix things */
1116 }
1117 
1118 /* Advance a byte in stream to get next possible header and forget
1119    buffered data if possible (for feed reader). */
1120 #define FORGET_INTERVAL 1024 /* Used by callers to set forget flag each <n> bytes. */
forget_head_shift(mpg123_handle * fr,unsigned long * newheadp,int forget)1121 static int forget_head_shift(mpg123_handle *fr, unsigned long *newheadp, int forget)
1122 {
1123 	int ret;
1124 	if((ret=fr->rd->head_shift(fr,newheadp))<=0) return ret;
1125 	/* Try to forget buffered data as early as possible to speed up parsing where
1126 	   new data needs to be added for resync (and things would be re-parsed again
1127 	   and again because of the start from beginning after hitting end). */
1128 	if(forget && fr->rd->forget != NULL)
1129 	{
1130 		/* Ensure that the last 4 bytes stay in buffers for reading the header
1131 		   anew. */
1132 		if(!fr->rd->back_bytes(fr, 4))
1133 		{
1134 			fr->rd->forget(fr);
1135 			fr->rd->back_bytes(fr, -4);
1136 		}
1137 	}
1138 	return ret; /* No surprise here, error already triggered early return. */
1139 }
1140 
1141 /* watch out for junk/tags on beginning of stream by invalid header */
skip_junk(mpg123_handle * fr,unsigned long * newheadp,long * headcount)1142 static int skip_junk(mpg123_handle *fr, unsigned long *newheadp, long *headcount)
1143 {
1144 	int ret;
1145 	int freeformat_count = 0;
1146 	long limit = 65536;
1147 	unsigned long newhead = *newheadp;
1148 	unsigned int forgetcount = 0;
1149 	/* check for id3v2; first three bytes (of 4) are "ID3" */
1150 	if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1151 	{
1152 		return handle_id3v2(fr, newhead);
1153 	}
1154 	else if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Junk at the beginning (0x%08lx)\n",newhead);
1155 
1156 	/* I even saw RIFF headers at the beginning of MPEG streams ;( */
1157 	if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F')
1158 	{
1159 		if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr, "Note: Looks like a RIFF header.\n");
1160 
1161 		if((ret=fr->rd->head_read(fr,&newhead))<=0) return ret;
1162 
1163 		while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a')
1164 		{
1165 			if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1166 			if((ret=forget_head_shift(fr,&newhead,!forgetcount))<=0) return ret;
1167 		}
1168 		if((ret=fr->rd->head_read(fr,&newhead))<=0) return ret;
1169 
1170 		if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Skipped RIFF header!\n");
1171 
1172 		fr->oldhead = 0;
1173 		*newheadp = newhead;
1174 		return PARSE_AGAIN;
1175 	}
1176 
1177 	/*
1178 		Unhandled junk... just continue search for a header, stepping in single bytes through next 64K.
1179 		This is rather identical to the resync loop.
1180 	*/
1181 	debug("searching for header...");
1182 	*newheadp = 0; /* Invalidate the external value. */
1183 	ret = 0; /* We will check the value after the loop. */
1184 
1185 	/* We prepare for at least the 64K bytes as usual, unless
1186 	   user explicitly wanted more (even infinity). Never less. */
1187 	if(fr->p.resync_limit < 0 || fr->p.resync_limit > limit)
1188 	limit = fr->p.resync_limit;
1189 
1190 	do
1191 	{
1192 		++(*headcount);
1193 		if(limit >= 0 && *headcount >= limit) break;
1194 
1195 		if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1196 		if((ret=forget_head_shift(fr, &newhead, !forgetcount))<=0) return ret;
1197 
1198 		if(head_check(newhead) && (ret=decode_header(fr, newhead, &freeformat_count))) break;
1199 	} while(1);
1200 	if(ret<0) return ret;
1201 
1202 	if(limit >= 0 && *headcount >= limit)
1203 	{
1204 		if(NOQUIET) error1("Giving up searching valid MPEG header after %li bytes of junk.", *headcount);
1205 		return PARSE_END;
1206 	}
1207 	else debug1("hopefully found one at %"OFF_P, (off_p)fr->rd->tell(fr));
1208 
1209 	/* If the new header ist good, it is already decoded. */
1210 	*newheadp = newhead;
1211 	return PARSE_GOOD;
1212 }
1213 
1214 /* The newhead is bad, so let's check if it is something special, otherwise just resync. */
wetwork(mpg123_handle * fr,unsigned long * newheadp)1215 static int wetwork(mpg123_handle *fr, unsigned long *newheadp)
1216 {
1217 	int ret = PARSE_ERR;
1218 	unsigned long newhead = *newheadp;
1219 	*newheadp = 0;
1220 
1221 	/* Classic ID3 tags. Read, then start parsing again. */
1222 	if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8))
1223 	{
1224 		fr->id3buf[0] = (unsigned char) ((newhead >> 24) & 0xff);
1225 		fr->id3buf[1] = (unsigned char) ((newhead >> 16) & 0xff);
1226 		fr->id3buf[2] = (unsigned char) ((newhead >> 8)  & 0xff);
1227 		fr->id3buf[3] = (unsigned char) ( newhead        & 0xff);
1228 
1229 		if((ret=fr->rd->fullread(fr,fr->id3buf+4,124)) < 0) return ret;
1230 
1231 		fr->metaflags  |= MPG123_NEW_ID3|MPG123_ID3;
1232 		fr->rdat.flags |= READER_ID3TAG; /* that marks id3v1 */
1233 		if(VERBOSE3) fprintf(stderr,"Note: Skipped ID3v1 tag.\n");
1234 
1235 		return PARSE_AGAIN;
1236 	}
1237 	/* This is similar to initial junk skipping code... */
1238 	/* Check for id3v2; first three bytes (of 4) are "ID3" */
1239 	if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1240 	{
1241 		return handle_id3v2(fr, newhead);
1242 	}
1243 	/* Check for an apetag header */
1244 	if(newhead == ('A'<<24)+('P'<<16)+('E'<<8)+'T')
1245 	{
1246 		return handle_apetag(fr, newhead);
1247 	}
1248 	else if(NOQUIET && fr->silent_resync == 0)
1249 	{
1250 		fprintf(stderr,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset %"OFF_P".\n",
1251 			newhead, (off_p)fr->rd->tell(fr)-4);
1252 	}
1253 
1254 	/* Now we got something bad at hand, try to recover. */
1255 
1256 	if(NOQUIET && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n");
1257 
1258 	if( !(fr->p.flags & MPG123_NO_RESYNC) )
1259 	{
1260 		long try = 0;
1261 		long limit = fr->p.resync_limit;
1262 		unsigned int forgetcount = 0;
1263 
1264 		/* If a resync is needed the bitreservoir of previous frames is no longer valid */
1265 		fr->bitreservoir = 0;
1266 
1267 		if(NOQUIET && fr->silent_resync == 0) fprintf(stderr, "Note: Trying to resync...\n");
1268 
1269 		do /* ... shift the header with additional single bytes until be found something that could be a header. */
1270 		{
1271 			++try;
1272 			if(limit >= 0 && try >= limit) break;
1273 
1274 			if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1275 			if((ret=forget_head_shift(fr,&newhead,!forgetcount)) <= 0)
1276 			{
1277 				*newheadp = newhead;
1278 				if(NOQUIET) fprintf (stderr, "Note: Hit end of (available) data during resync.\n");
1279 
1280 				return ret ? ret : PARSE_END;
1281 			}
1282 			if(VERBOSE3) debug3("resync try %li at %"OFF_P", got newhead 0x%08lx", try, (off_p)fr->rd->tell(fr),  newhead);
1283 		} while(!head_check(newhead));
1284 
1285 		*newheadp = newhead;
1286 		if(NOQUIET && fr->silent_resync == 0) fprintf (stderr, "Note: Skipped %li bytes in input.\n", try);
1287 
1288 		/* Now we either got something that could be a header, or we gave up. */
1289 		if(limit >= 0 && try >= limit)
1290 		{
1291 			if(NOQUIET)
1292 			error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try);
1293 
1294 			fr->err = MPG123_RESYNC_FAIL;
1295 			return PARSE_ERR;
1296 		}
1297 		else
1298 		{
1299 			debug1("Found possibly valid header 0x%lx... unsetting oldhead to reinit stream.", newhead);
1300 			fr->oldhead = 0;
1301 			return PARSE_RESYNC;
1302 		}
1303 	}
1304 	else
1305 	{
1306 		if(NOQUIET) error("not attempting to resync...");
1307 
1308 		fr->err = MPG123_OUT_OF_SYNC;
1309 		return PARSE_ERR;
1310 	}
1311 	/* Control never goes here... we return before that. */
1312 }
1313