Debian Codegraph @

src/libmpg123/parse.c

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