Sync winemp3.acm with Wine HEAD. This one uses libmpg123 which was added in Version...
[reactos.git] / reactos / lib / 3rdparty / libmpg123 / parse.c
1 /*
2 parse: spawned from common; clustering around stream/frame parsing
3
4 copyright ?-2009 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 "debug.h"
32
33 #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) ) )
34
35 /*
36 AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM
37 A: sync
38 B: mpeg version
39 C: layer
40 D: CRC
41 E: bitrate
42 F:sampling rate
43 G: padding
44 H: private
45 I: channel mode
46 J: mode ext
47 K: copyright
48 L: original
49 M: emphasis
50
51 old compare mask 0xfffffd00:
52 11111111 11111111 11111101 00000000
53
54 means: everything must match excluding padding and channel mode, ext mode, ...
55 But a vbr stream's headers will differ in bitrate!
56 We are already strict in allowing only frames of same type in stream, we should at least watch out for VBR while being strict.
57
58 So a better mask is:
59 11111111 11111111 00001101 00000000
60
61 Even more, I'll allow varying crc bit.
62 11111111 11111110 00001101 00000000
63
64 (still unsure about this private bit)
65 */
66 #define HDRCMPMASK 0xfffe0d00
67 #define HDRSAMPMASK 0xc00 /* 1100 00000000, FF bits (sample rate) */
68
69 /* bitrates for [mpeg1/2][layer] */
70 static const int tabsel_123[2][3][16] =
71 {
72 {
73 {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,},
74 {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,},
75 {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,}
76 },
77 {
78 {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,},
79 {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,},
80 {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,}
81 }
82 };
83
84 const long freqs[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 };
85
86 static int decode_header(mpg123_handle *fr,unsigned long newhead);
87
88 /* These two are to be replaced by one function that gives all the frame parameters (for outsiders).*/
89
90 int frame_bitrate(mpg123_handle *fr)
91 {
92 return tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index];
93 }
94
95 long frame_freq(mpg123_handle *fr)
96 {
97 return freqs[fr->sampling_frequency];
98 }
99
100 #define free_format_header(head) ( ((head & 0xffe00000) == 0xffe00000) && ((head>>17)&3) && (((head>>12)&0xf) == 0x0) && (((head>>10)&0x3) != 0x3 ))
101
102 /* compiler is smart enought to inline this one or should I really do it as macro...? */
103 int head_check(unsigned long head)
104 {
105 if
106 (
107 /* first 11 bits are set to 1 for frame sync */
108 ((head & 0xffe00000) != 0xffe00000)
109 ||
110 /* layer: 01,10,11 is 1,2,3; 00 is reserved */
111 (!((head>>17)&3))
112 ||
113 /* 1111 means bad bitrate */
114 (((head>>12)&0xf) == 0xf)
115 ||
116 /* sampling freq: 11 is reserved */
117 (((head>>10)&0x3) == 0x3 )
118 /* 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 */
119 )
120 {
121 return FALSE;
122 }
123 /* if no check failed, the header is valid (hopefully)*/
124 else
125 {
126 return TRUE;
127 }
128 }
129
130 static int check_lame_tag(mpg123_handle *fr)
131 {
132 /*
133 going to look for Xing or Info at some position after the header
134 MPEG 1 MPEG 2/2.5 (LSF)
135 Stereo, Joint Stereo, Dual Channel 32 17
136 Mono 17 9
137
138 Also, how to avoid false positives? I guess I should interpret more of the header to rule that out(?).
139 I hope that ensuring all zeros until tag start is enough.
140 */
141 int lame_offset = (fr->stereo == 2) ? (fr->lsf ? 17 : 32 ) : (fr->lsf ? 9 : 17);
142 /* At least skip the decoder delay. */
143 #ifdef GAPLESS
144 if(fr->p.flags & MPG123_GAPLESS)
145 {
146 if(fr->begin_s == 0) frame_gapless_init(fr, GAPLESS_DELAY, 0);
147 }
148 #endif
149
150 if(fr->framesize >= 120+lame_offset) /* traditional Xing header is 120 bytes */
151 {
152 int i;
153 int lame_type = 0;
154 debug("do we have lame tag?");
155 /* only search for tag when all zero before it (apart from checksum) */
156 for(i=2; i < lame_offset; ++i) if(fr->bsbuf[i] != 0) break;
157 if(i == lame_offset)
158 {
159 debug("possibly...");
160 if
161 (
162 (fr->bsbuf[lame_offset] == 'I')
163 && (fr->bsbuf[lame_offset+1] == 'n')
164 && (fr->bsbuf[lame_offset+2] == 'f')
165 && (fr->bsbuf[lame_offset+3] == 'o')
166 )
167 {
168 lame_type = 1; /* We still have to see what there is */
169 }
170 else if
171 (
172 (fr->bsbuf[lame_offset] == 'X')
173 && (fr->bsbuf[lame_offset+1] == 'i')
174 && (fr->bsbuf[lame_offset+2] == 'n')
175 && (fr->bsbuf[lame_offset+3] == 'g')
176 )
177 {
178 lame_type = 2;
179 fr->vbr = MPG123_VBR; /* Xing header means always VBR */
180 }
181 if(lame_type)
182 {
183 unsigned long xing_flags;
184
185 /* we have one of these headers... */
186 if(VERBOSE2) fprintf(stderr, "Note: Xing/Lame/Info header detected\n");
187 /* now interpret the Xing part, I have 120 bytes total for sure */
188 /* there are 4 bytes for flags, but only the last byte contains known ones */
189 lame_offset += 4; /* now first byte after Xing/Name */
190 /* 4 bytes dword for flags */
191 #define make_long(a, o) ((((unsigned long) a[o]) << 24) | (((unsigned long) a[o+1]) << 16) | (((unsigned long) a[o+2]) << 8) | ((unsigned long) a[o+3]))
192 /* 16 bit */
193 #define make_short(a,o) ((((unsigned short) a[o]) << 8) | ((unsigned short) a[o+1]))
194 xing_flags = make_long(fr->bsbuf, lame_offset);
195 lame_offset += 4;
196 debug1("Xing: flags 0x%08lx", xing_flags);
197 if(xing_flags & 1) /* frames */
198 {
199 if(fr->p.flags & MPG123_IGNORE_STREAMLENGTH)
200 {
201 if(VERBOSE3)
202 fprintf(stderr, "Note: Ignoring Xing frames because of MPG123_IGNORE_STREAMLENGTH\n");
203 }
204 else
205 {
206 /*
207 In theory, one should use that value for skipping...
208 When I know the exact number of samples I could simply count in flush_output,
209 but that's problematic with seeking and such.
210 I still miss the real solution for detecting the end.
211 */
212 fr->track_frames = (off_t) make_long(fr->bsbuf, lame_offset);
213 if(fr->track_frames > TRACK_MAX_FRAMES) fr->track_frames = 0; /* endless stream? */
214 #ifdef GAPLESS
215 /* if no further info there, remove/add at least the decoder delay */
216 if(fr->p.flags & MPG123_GAPLESS)
217 {
218 off_t length = fr->track_frames * spf(fr);
219 if(length > 1)
220 frame_gapless_init(fr, GAPLESS_DELAY, length+GAPLESS_DELAY);
221 }
222 #endif
223 if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu frames\n", (long unsigned)fr->track_frames);
224 }
225
226 lame_offset += 4;
227 }
228 if(xing_flags & 0x2) /* bytes */
229 {
230 if(fr->p.flags & MPG123_IGNORE_STREAMLENGTH)
231 {
232 if(VERBOSE3)
233 fprintf(stderr, "Note: Ignoring Xing bytes because of MPG123_IGNORE_STREAMLENGTH\n");
234 }
235 else
236 {
237 unsigned long xing_bytes = make_long(fr->bsbuf, lame_offset); /* We assume that this is the _total_ size of the file, including Xing frame ... and ID3 frames...
238 It's not that clearly documented... */
239 if(fr->rdat.filelen < 1)
240 fr->rdat.filelen = (off_t) xing_bytes; /* One could start caring for overflow here. */
241 else
242 {
243 if((off_t) xing_bytes != fr->rdat.filelen && NOQUIET)
244 {
245 double diff = 1.0/fr->rdat.filelen * (fr->rdat.filelen - (off_t)xing_bytes);
246 if(diff < 0.) diff = -diff;
247
248 if(VERBOSE3)
249 fprintf(stderr, "Note: Xing stream size %lu differs by %f%% from determined/given file size!\n", xing_bytes, diff);
250
251 if(diff > 1.)
252 fprintf(stderr, "Warning: Xing stream size off by more than 1%%, fuzzy seeking may be even more fuzzy than by design!\n");
253 }
254 }
255
256 if(VERBOSE3)
257 fprintf(stderr, "Note: Xing: %lu bytes\n", (long unsigned)xing_bytes);
258 }
259
260 lame_offset += 4;
261 }
262 if(xing_flags & 0x4) /* TOC */
263 {
264 frame_fill_toc(fr, fr->bsbuf+lame_offset);
265 lame_offset += 100; /* just skip */
266 }
267 if(xing_flags & 0x8) /* VBR quality */
268 {
269 if(VERBOSE3)
270 {
271 unsigned long xing_quality = make_long(fr->bsbuf, lame_offset);
272 fprintf(stderr, "Note: Xing: quality = %lu\n", (long unsigned)xing_quality);
273 }
274 lame_offset += 4;
275 }
276 /* I guess that either 0 or LAME extra data follows */
277 /* there may this crc16 be floating around... (?) */
278 if(fr->bsbuf[lame_offset] != 0)
279 {
280 unsigned char lame_vbr;
281 float replay_gain[2] = {0,0};
282 float peak = 0;
283 float gain_offset = 0; /* going to be +6 for old lame that used 83dB */
284 char nb[10];
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 gain_offset = 6;
291 debug("TODO: finish lame detetcion...");
292 }
293 lame_offset += 9;
294 /* the 4 big bits are tag revision, the small bits vbr method */
295 lame_vbr = fr->bsbuf[lame_offset] & 15;
296 if(VERBOSE3)
297 {
298 fprintf(stderr, "Note: Info: rev %u\n", fr->bsbuf[lame_offset] >> 4);
299 fprintf(stderr, "Note: Info: vbr mode %u\n", lame_vbr);
300 }
301 lame_offset += 1;
302 switch(lame_vbr)
303 {
304 /* from rev1 proposal... not sure if all good in practice */
305 case 1:
306 case 8: fr->vbr = MPG123_CBR; break;
307 case 2:
308 case 9: fr->vbr = MPG123_ABR; break;
309 default: fr->vbr = MPG123_VBR; /* 00==unknown is taken as VBR */
310 }
311 /* skipping: lowpass filter value */
312 lame_offset += 1;
313 /* replaygain */
314 /* 32bit float: peak amplitude -- why did I parse it as int before??*/
315 /* Ah, yes, lame seems to store it as int since some day in 2003; I've only seen zeros anyway until now, bah! */
316 if
317 (
318 (fr->bsbuf[lame_offset] != 0)
319 || (fr->bsbuf[lame_offset+1] != 0)
320 || (fr->bsbuf[lame_offset+2] != 0)
321 || (fr->bsbuf[lame_offset+3] != 0)
322 )
323 {
324 debug("Wow! Is there _really_ a non-zero peak value? Now is it stored as float or int - how should I know?");
325 /* byte*peak_bytes = (byte*) &peak;
326 ... endianess ... just copy bytes to avoid floating point operation on unaligned memory?
327 peak_bytes[0] = ...
328 peak = *(float*) (fr->bsbuf+lame_offset); */
329 }
330 if(VERBOSE3) fprintf(stderr, "Note: Info: peak = %f (I won't use this)\n", peak);
331 peak = 0; /* until better times arrived */
332 lame_offset += 4;
333 /*
334 ReplayGain values - lame only writes radio mode gain...
335 16bit gain, 3 bits name, 3 bits originator, sign (1=-, 0=+), dB value*10 in 9 bits (fixed point)
336 ignore the setting if name or originator == 000!
337 radio 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1
338 audiophile 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0
339 */
340
341 for(i =0; i < 2; ++i)
342 {
343 unsigned char origin = (fr->bsbuf[lame_offset] >> 2) & 0x7; /* the 3 bits after that... */
344 if(origin != 0)
345 {
346 unsigned char gt = fr->bsbuf[lame_offset] >> 5; /* only first 3 bits */
347 if(gt == 1) gt = 0; /* radio */
348 else if(gt == 2) gt = 1; /* audiophile */
349 else continue;
350 /* get the 9 bits into a number, divide by 10, multiply sign... happy bit banging */
351 replay_gain[0] = (float) ((fr->bsbuf[lame_offset] & 0x2) ? -0.1 : 0.1) * (make_short(fr->bsbuf, lame_offset) & 0x1f);
352 }
353 lame_offset += 2;
354 }
355 if(VERBOSE3)
356 {
357 fprintf(stderr, "Note: Info: Radio Gain = %03.1fdB\n", replay_gain[0]);
358 fprintf(stderr, "Note: Info: Audiophile Gain = %03.1fdB\n", replay_gain[1]);
359 }
360 for(i=0; i < 2; ++i)
361 {
362 if(fr->rva.level[i] <= 0)
363 {
364 fr->rva.peak[i] = 0; /* at some time the parsed peak should be used */
365 fr->rva.gain[i] = replay_gain[i];
366 fr->rva.level[i] = 0;
367 }
368 }
369 lame_offset += 1; /* skipping encoding flags byte */
370 if(fr->vbr == MPG123_ABR)
371 {
372 fr->abr_rate = fr->bsbuf[lame_offset];
373 if(VERBOSE3) fprintf(stderr, "Note: Info: ABR rate = %u\n", fr->abr_rate);
374 }
375 lame_offset += 1;
376 /* encoder delay and padding, two 12 bit values... lame does write them from int ...*/
377 if(VERBOSE3)
378 fprintf(stderr, "Note: Encoder delay = %i; padding = %i\n",
379 ((((int) fr->bsbuf[lame_offset]) << 4) | (((int) fr->bsbuf[lame_offset+1]) >> 4)),
380 (((((int) fr->bsbuf[lame_offset+1]) << 8) | (((int) fr->bsbuf[lame_offset+2]))) & 0xfff) );
381 #ifdef GAPLESS
382 if(fr->p.flags & MPG123_GAPLESS)
383 {
384 off_t length = fr->track_frames * spf(fr);
385 off_t skipbegin = GAPLESS_DELAY + ((((int) fr->bsbuf[lame_offset]) << 4) | (((int) fr->bsbuf[lame_offset+1]) >> 4));
386 off_t skipend = -GAPLESS_DELAY + (((((int) fr->bsbuf[lame_offset+1]) << 8) | (((int) fr->bsbuf[lame_offset+2]))) & 0xfff);
387 debug3("preparing gapless mode for layer3: length %lu, skipbegin %lu, skipend %lu",
388 (long unsigned)length, (long unsigned)skipbegin, (long unsigned)skipend);
389 if(length > 1)
390 frame_gapless_init(fr, skipbegin, (skipend < length) ? length-skipend : length);
391 }
392 #endif
393 }
394 /* switch buffer back ... */
395 fr->bsbuf = fr->bsspace[fr->bsnum]+512;
396 fr->bsnum = (fr->bsnum + 1) & 1;
397 return 1; /* got it! */
398 }
399 }
400 }
401 return 0; /* no lame tag */
402 }
403
404 /* Just tell if the header is some mono. */
405 static int header_mono(unsigned long newhead)
406 {
407 return ((newhead>>6)&0x3) == MPG_MD_MONO ? TRUE : FALSE;
408 }
409
410 /*
411 That's a big one: read the next frame. 1 is success, <= 0 is some error
412 Special error READER_MORE means: Please feed more data and try again.
413 */
414 int read_frame(mpg123_handle *fr)
415 {
416 /* TODO: rework this thing */
417 unsigned long newhead;
418 off_t framepos;
419 int ret;
420 /* stuff that needs resetting if complete frame reading fails */
421 int oldsize = fr->framesize;
422 int oldphase = fr->halfphase;
423
424 /* The counter for the search-first-header loop.
425 It is persistent outside the loop to prevent seemingly endless loops
426 when repeatedly headers are found that do not have valid followup headers. */
427 int headcount = 0;
428
429 fr->fsizeold=fr->framesize; /* for Layer3 */
430
431 /* Speed-down hack: Play it again, Sam (the frame, I mean). */
432 if (fr->p.halfspeed)
433 {
434 if(fr->halfphase) /* repeat last frame */
435 {
436 debug("repeat!");
437 fr->to_decode = fr->to_ignore = TRUE;
438 --fr->halfphase;
439 fr->bitindex = 0;
440 fr->wordpointer = (unsigned char *) fr->bsbuf;
441 if(fr->lay == 3) memcpy (fr->bsbuf, fr->ssave, fr->ssize);
442 if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */
443 return 1;
444 }
445 else
446 {
447 fr->halfphase = fr->p.halfspeed - 1;
448 }
449 }
450
451 read_again:
452 /* In case we are looping to find a valid frame, discard any buffered data before the current position.
453 This is essential to prevent endless looping, always going back to the beginning when feeder buffer is exhausted. */
454 if(fr->rd->forget != NULL) fr->rd->forget(fr);
455
456 debug2("trying to get frame %"OFF_P" at %"OFF_P, (off_p)fr->num+1, (off_p)fr->rd->tell(fr));
457 if((ret = fr->rd->head_read(fr,&newhead)) <= 0){ debug("need more?"); goto read_frame_bad;}
458
459 init_resync:
460
461 fr->header_change = 2; /* output format change is possible... */
462 if(fr->oldhead) /* check a following header for change */
463 {
464 if(fr->oldhead == newhead) fr->header_change = 0;
465 else
466 /* If they have the same sample rate. Note that only is _not_ the case for the first header, as we enforce sample rate match for following frames.
467 So, during one stream, only change of stereoness is possible and indicated by header_change == 2. */
468 if((fr->oldhead & HDRSAMPMASK) == (newhead & HDRSAMPMASK))
469 {
470 /* Now if both channel modes are mono or both stereo, it's no big deal. */
471 if( header_mono(fr->oldhead) == header_mono(newhead))
472 fr->header_change = 1;
473 }
474 }
475
476 #ifdef SKIP_JUNK
477 /* watch out for junk/tags on beginning of stream by invalid header */
478 if(!fr->firsthead && !head_check(newhead)) {
479
480 /* check for id3v2; first three bytes (of 4) are "ID3" */
481 if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
482 {
483 int id3ret = 0;
484 id3ret = parse_new_id3(fr, newhead);
485 if (id3ret < 0){ debug("need more?"); ret = id3ret; goto read_frame_bad; }
486 #ifndef NO_ID3V2
487 else if(id3ret > 0){ debug("got ID3v2"); fr->metaflags |= MPG123_NEW_ID3|MPG123_ID3; }
488 else debug("no useful ID3v2");
489 #endif
490
491 fr->oldhead = 0;
492 goto read_again; /* Also in case of invalid ID3 tag (ret==0), try to get on track again. */
493 }
494 else if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Junk at the beginning (0x%08lx)\n",newhead);
495
496 /* I even saw RIFF headers at the beginning of MPEG streams ;( */
497 if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F') {
498 if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr, "Note: Looks like a RIFF header.\n");
499
500 if((ret=fr->rd->head_read(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; }
501
502 while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a')
503 {
504 if((ret=fr->rd->head_shift(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; }
505 }
506 if((ret=fr->rd->head_read(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; }
507
508 if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Skipped RIFF header!\n");
509
510 fr->oldhead = 0;
511 goto read_again;
512 }
513 /* unhandled junk... just continue search for a header */
514 /* step in byte steps through next 64K */
515 debug("searching for header...");
516
517 ret = 0; /* We will check the value after the loop. */
518 for(; headcount<65536; headcount++)
519 {
520 if((ret=fr->rd->head_shift(fr,&newhead))<=0){ debug("need more?"); goto read_frame_bad; }
521 /* if(head_check(newhead)) */
522 if(head_check(newhead) && (ret=decode_header(fr, newhead)))
523 break;
524 }
525 if(ret<0){ debug("need more?"); goto read_frame_bad; }
526
527 if(headcount == 65536)
528 {
529 if(NOQUIET) error("Giving up searching valid MPEG header after (over) 64K of junk.");
530 return 0;
531 }
532 else debug1("hopefully found one at %"OFF_P, (off_p)fr->rd->tell(fr));
533 /*
534 * should we additionaly check, whether a new frame starts at
535 * the next expected position? (some kind of read ahead)
536 * We could implement this easily, at least for files.
537 */
538 }
539 #endif
540
541 /* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */
542 if(!fr->firsthead && fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED) && head_check(newhead) && (ret=decode_header(fr, newhead)))
543 {
544 unsigned long nexthead = 0;
545 int hd = 0;
546 off_t start = fr->rd->tell(fr);
547 if(ret<0){ debug("need more?"); goto read_frame_bad; }
548
549 debug2("doing ahead check with BPF %d at %"OFF_P, fr->framesize+4, (off_p)start);
550 /* step framesize bytes forward and read next possible header*/
551 if((ret=fr->rd->skip_bytes(fr, fr->framesize))<0)
552 {
553 if(ret==READER_ERROR && NOQUIET) error("cannot seek!");
554 goto read_frame_bad;
555 }
556 hd = fr->rd->head_read(fr,&nexthead);
557 if(hd==MPG123_NEED_MORE){ debug("need more?"); ret = hd; goto read_frame_bad; }
558 if((ret=fr->rd->back_bytes(fr, fr->rd->tell(fr)-start))<0)
559 {
560 if(ret==READER_ERROR && NOQUIET) error("cannot seek!");
561 else debug("need more?");
562 goto read_frame_bad;
563 }
564 debug1("After fetching next header, at %"OFF_P, (off_p)fr->rd->tell(fr));
565 if(!hd)
566 {
567 if(NOQUIET) warning("cannot read next header, a one-frame stream? Duh...");
568 }
569 else
570 {
571 debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead);
572 /* not allowing free format yet */
573 if(!head_check(nexthead) || (nexthead & HDRCMPMASK) != (newhead & HDRCMPMASK))
574 {
575 debug("No, the header was not valid, start from beginning...");
576 fr->oldhead = 0; /* start over */
577 /* try next byte for valid header */
578 if((ret=fr->rd->back_bytes(fr, 3))<0)
579 {
580 if(NOQUIET) error("cannot seek!");
581 else debug("need more?");
582 goto read_frame_bad;
583 }
584 goto read_again;
585 }
586 }
587 }
588
589 /* why has this head check been avoided here before? */
590 if(!head_check(newhead))
591 {
592 /* and those ugly ID3 tags */
593 if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8))
594 {
595 fr->id3buf[0] = (unsigned char) ((newhead >> 24) & 0xff);
596 fr->id3buf[1] = (unsigned char) ((newhead >> 16) & 0xff);
597 fr->id3buf[2] = (unsigned char) ((newhead >> 8) & 0xff);
598 fr->id3buf[3] = (unsigned char) ( newhead & 0xff);
599 if((ret=fr->rd->fullread(fr,fr->id3buf+4,124)) < 0){ debug("need more?"); goto read_frame_bad; }
600 fr->metaflags |= MPG123_NEW_ID3|MPG123_ID3;
601 fr->rdat.flags |= READER_ID3TAG; /* that marks id3v1 */
602 if (VERBOSE3) fprintf(stderr,"Note: Skipped ID3v1 tag.\n");
603 goto read_again;
604 }
605 /* duplicated code from above! */
606 /* check for id3v2; first three bytes (of 4) are "ID3" */
607 if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
608 {
609 int id3length = 0;
610 id3length = parse_new_id3(fr, newhead);
611 if(id3length < 0){ debug("need more?"); ret = id3length; goto read_frame_bad; }
612
613 fr->metaflags |= MPG123_NEW_ID3|MPG123_ID3;
614 goto read_again;
615 }
616 else if(NOQUIET && fr->silent_resync == 0)
617 {
618 fprintf(stderr,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset %"OFF_P".\n",
619 newhead, (off_p)fr->rd->tell(fr)-4);
620 }
621
622 if(NOQUIET && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n");
623 /* Do resync if not forbidden by flag.
624 I used to have a check for not-icy-meta here, but concluded that the desync issues came from a reader bug, not the stream. */
625 if( !(fr->p.flags & MPG123_NO_RESYNC) )
626 {
627 long try = 0;
628 long limit = fr->p.resync_limit;
629
630 /* If a resync is needed the bitreservoir of previous frames is no longer valid */
631 fr->bitreservoir = 0;
632
633 /* TODO: make this more robust, I'd like to cat two mp3 fragments together (in a dirty way) and still have mpg123 beign able to decode all it somehow. */
634 if(NOQUIET && fr->silent_resync == 0) fprintf(stderr, "Note: Trying to resync...\n");
635 /* Read more bytes until we find something that looks
636 reasonably like a valid header. This is not a
637 perfect strategy, but it should get us back on the
638 track within a short time (and hopefully without
639 too much distortion in the audio output). */
640 do
641 {
642 ++try;
643 if(limit >= 0 && try >= limit) break;
644
645 if((ret=fr->rd->head_shift(fr,&newhead)) <= 0)
646 {
647 debug("need more?");
648 if(NOQUIET) fprintf (stderr, "Note: Hit end of (available) data during resync.\n");
649
650 goto read_frame_bad;
651 }
652 if(VERBOSE3) debug3("resync try %li at %"OFF_P", got newhead 0x%08lx", try, (off_p)fr->rd->tell(fr), newhead);
653
654 if(!fr->oldhead)
655 {
656 debug("going to init_resync...");
657 goto init_resync; /* "considered harmful", eh? */
658 }
659 /* we should perhaps collect a list of valid headers that occured in file... there can be more */
660 /* Michael's new resync routine seems to work better with the one frame readahead (and some input buffering?) */
661 } while
662 (
663 !head_check(newhead) /* Simply check for any valid header... we have the readahead to get it straight now(?) */
664 /* (newhead & HDRCMPMASK) != (fr->oldhead & HDRCMPMASK)
665 && (newhead & HDRCMPMASK) != (fr->firsthead & HDRCMPMASK)*/
666 );
667 /* too many false positives
668 }while (!(head_check(newhead) && decode_header(fr, newhead))); */
669 if(NOQUIET && fr->silent_resync == 0) fprintf (stderr, "Note: Skipped %li bytes in input.\n", try);
670
671 if(limit >= 0 && try >= limit)
672 {
673 if(NOQUIET)
674 error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try);
675
676 fr->err = MPG123_RESYNC_FAIL;
677 return READER_ERROR;
678 }
679 else
680 {
681 debug1("Found valid header 0x%lx... unsetting firsthead to reinit stream.", newhead);
682 fr->firsthead = 0;
683 goto init_resync;
684 }
685 }
686 else
687 {
688 if(NOQUIET) error("not attempting to resync...");
689
690 fr->err = MPG123_OUT_OF_SYNC;
691 return READER_ERROR;
692 }
693 }
694
695 /* Man, that code looks awfully redundant...
696 I need to untangle the spaghetti here in a future version. */
697 if(!fr->firsthead)
698 {
699 ret=decode_header(fr,newhead);
700 if(ret == 0)
701 {
702 if(NOQUIET) error("decode header failed before first valid one, going to read again");
703
704 goto read_again;
705 }
706 else if(ret < 0){ debug("need more?"); goto read_frame_bad; }
707 }
708 else
709 {
710 ret=decode_header(fr,newhead);
711 if(ret == 0)
712 {
713 if(NOQUIET) error("decode header failed - goto resync");
714 /* return 0; */
715 goto init_resync;
716 }
717 else if(ret < 0){ debug("need more?"); goto read_frame_bad; }
718 }
719
720 /* if filepos is invalid, so is framepos */
721 framepos = fr->rd->tell(fr) - 4;
722 /* flip/init buffer for Layer 3 */
723 {
724 unsigned char *newbuf = fr->bsspace[fr->bsnum]+512;
725 /* read main data into memory */
726 if((ret=fr->rd->read_frame_body(fr,newbuf,fr->framesize))<0)
727 {
728 /* if failed: flip back */
729 debug("need more?");
730 goto read_frame_bad;
731 }
732 fr->bsbufold = fr->bsbuf;
733 fr->bsbuf = newbuf;
734 }
735 fr->bsnum = (fr->bsnum + 1) & 1;
736
737 if(!fr->firsthead)
738 {
739 fr->firsthead = newhead; /* _now_ it's time to store it... the first real header */
740 /* This is the first header of our current stream segment.
741 It is only the actual first header of the whole stream when fr->num is still below zero!
742 Think of resyncs where firsthead has been reset for format flexibility. */
743 if(fr->num < 0)
744 {
745 fr->audio_start = framepos;
746 /* Only check for LAME tag at beginning of whole stream
747 ... when there indeed is one in between, it's the user's problem. */
748 if(fr->lay == 3 && check_lame_tag(fr) == 1)
749 { /* ...in practice, Xing/LAME tags are layer 3 only. */
750 if(fr->rd->forget != NULL) fr->rd->forget(fr);
751
752 fr->oldhead = 0;
753 goto read_again;
754 }
755 /* now adjust volume */
756 do_rva(fr);
757 }
758
759 debug2("fr->firsthead: %08lx, audio_start: %li", fr->firsthead, (long int)fr->audio_start);
760 }
761
762 fr->bitindex = 0;
763 fr->wordpointer = (unsigned char *) fr->bsbuf;
764 /* Question: How bad does the floating point value get with repeated recomputation?
765 Also, considering that we can play the file or parts of many times. */
766 if(++fr->mean_frames != 0)
767 {
768 fr->mean_framesize = ((fr->mean_frames-1)*fr->mean_framesize+compute_bpf(fr)) / fr->mean_frames ;
769 }
770 ++fr->num; /* 0 for first frame! */
771 debug4("Frame %"OFF_P" %08lx %i, next filepos=%"OFF_P,
772 (off_p)fr->num, newhead, fr->framesize, (off_p)fr->rd->tell(fr));
773
774 /* save for repetition */
775 if(fr->p.halfspeed && fr->lay == 3)
776 {
777 debug("halfspeed - reusing old bsbuf ");
778 memcpy (fr->ssave, fr->bsbuf, fr->ssize);
779 }
780
781 /* index the position */
782 #ifdef FRAME_INDEX
783 /* Keep track of true frame positions in our frame index.
784 but only do so when we are sure that the frame number is accurate... */
785 if(fr->accurate && FI_NEXT(fr->index, fr->num))
786 fi_add(&fr->index, framepos);
787 #endif
788
789 if(fr->silent_resync > 0) --fr->silent_resync;
790
791 if(fr->rd->forget != NULL) fr->rd->forget(fr);
792
793 fr->to_decode = fr->to_ignore = TRUE;
794 if(fr->error_protection) fr->crc = getbits(fr, 16); /* skip crc */
795
796 return 1;
797 read_frame_bad:
798 /* Also if we searched for valid data in vain, we can forget skipped data.
799 Otherwise, the feeder would hold every dead old byte in memory until the first valid frame! */
800 if(fr->rd->forget != NULL) fr->rd->forget(fr);
801
802 fr->silent_resync = 0;
803 if(fr->err == MPG123_OK) fr->err = MPG123_ERR_READER;
804 fr->framesize = oldsize;
805 fr->halfphase = oldphase;
806 /* That return code might be inherited from some feeder action, or reader error. */
807 return ret;
808 }
809
810
811 /*
812 * read ahead and find the next MPEG header, to guess framesize
813 * return value: success code
814 * 1: found a valid frame size (stored in the handle).
815 * <0: error codes, possibly from feeder buffer (NEED_MORE)
816 * 0: cannot get the framesize for some reason and shall silentry try the next possible header (if this is no free format stream after all...)
817 */
818 static int guess_freeformat_framesize(mpg123_handle *fr)
819 {
820 long i;
821 int ret;
822 unsigned long head;
823 if(!(fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED)))
824 {
825 if(NOQUIET) error("Cannot look for freeformat frame size with non-seekable and non-buffered stream!");
826
827 return 0;
828 }
829 if((ret=fr->rd->head_read(fr,&head))<=0)
830 return ret;
831
832 /* We are already 4 bytes into it */
833 /* fix that limit to be absolute for the first header search! */
834 for(i=4;i<65536;i++) {
835 if((ret=fr->rd->head_shift(fr,&head))<=0)
836 {
837 return ret;
838 }
839 if(head_check(head))
840 {
841 int sampling_frequency,mpeg25,lsf;
842
843 if(head & (1<<20))
844 {
845 lsf = (head & (1<<19)) ? 0x0 : 0x1;
846 mpeg25 = 0;
847 }
848 else
849 {
850 lsf = 1;
851 mpeg25 = 1;
852 }
853
854 if(mpeg25)
855 sampling_frequency = 6 + ((head>>10)&0x3);
856 else
857 sampling_frequency = ((head>>10)&0x3) + (lsf*3);
858
859 if((lsf==fr->lsf) && (mpeg25==fr->mpeg25) && (sampling_frequency == fr->sampling_frequency))
860 {
861 fr->rd->back_bytes(fr,i+1);
862 fr->framesize = i-3;
863 return 1; /* Success! */
864 }
865 }
866 }
867 fr->rd->back_bytes(fr,i);
868 return 0;
869 }
870
871
872 /*
873 * decode a header and write the information
874 * into the frame structure
875 * Return values are compatible with those of read_frame, namely:
876 * 1: success
877 * 0: no valid header
878 * <0: some error
879 */
880 static int decode_header(mpg123_handle *fr,unsigned long newhead)
881 {
882 if(!head_check(newhead))
883 {
884 if(NOQUIET) error("tried to decode obviously invalid header");
885
886 return 0;
887 }
888 if( newhead & (1<<20) )
889 {
890 fr->lsf = (newhead & (1<<19)) ? 0x0 : 0x1;
891 fr->mpeg25 = 0;
892 }
893 else
894 {
895 fr->lsf = 1;
896 fr->mpeg25 = 1;
897 }
898
899 if( (fr->p.flags & MPG123_NO_RESYNC) || !fr->oldhead
900 || (((fr->oldhead>>19)&0x3) ^ ((newhead>>19)&0x3)) )
901 {
902 /* If "tryresync" is false, assume that certain
903 parameters do not change within the stream!
904 Force an update if lsf or mpeg25 settings
905 have changed. */
906 fr->lay = 4-((newhead>>17)&3);
907 if( ((newhead>>10)&0x3) == 0x3)
908 {
909 if(NOQUIET) error("Stream error");
910
911 return 0; /* exit() here really is too much, isn't it? */
912 }
913 if(fr->mpeg25)
914 fr->sampling_frequency = 6 + ((newhead>>10)&0x3);
915 else
916 fr->sampling_frequency = ((newhead>>10)&0x3) + (fr->lsf*3);
917 }
918
919 #ifdef DEBUG
920 if((((newhead>>16)&0x1)^0x1) != fr->error_protection) debug("changed crc bit!");
921 #endif
922 fr->error_protection = ((newhead>>16)&0x1)^0x1; /* seen a file where this varies (old lame tag without crc, track with crc) */
923 fr->bitrate_index = ((newhead>>12)&0xf);
924 fr->padding = ((newhead>>9)&0x1);
925 fr->extension = ((newhead>>8)&0x1);
926 fr->mode = ((newhead>>6)&0x3);
927 fr->mode_ext = ((newhead>>4)&0x3);
928 fr->copyright = ((newhead>>3)&0x1);
929 fr->original = ((newhead>>2)&0x1);
930 fr->emphasis = newhead & 0x3;
931 fr->freeformat = free_format_header(newhead);
932
933 fr->stereo = (fr->mode == MPG_MD_MONO) ? 1 : 2;
934
935 fr->oldhead = newhead;
936
937 /* we can't use tabsel_123 for freeformat, so trying to guess framesize... */
938 if(fr->freeformat)
939 {
940 /* when we first encounter the frame with freeformat, guess framesize */
941 if(fr->freeformat_framesize < 0)
942 {
943 int ret;
944 ret = guess_freeformat_framesize(fr);
945 if(ret>0)
946 {
947 fr->freeformat_framesize = fr->framesize - fr->padding;
948 if(VERBOSE2)
949 fprintf(stderr, "Note: free format frame size %li\n", fr->freeformat_framesize);
950 }
951 else
952 {
953 if(ret == MPG123_NEED_MORE)
954 debug("Need more data to guess free format frame size.");
955 else
956 error("Encountered free format header, but failed to guess frame size.");
957 return ret;
958 }
959 }
960 /* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */
961 else
962 {
963 fr->framesize = fr->freeformat_framesize + fr->padding;
964 }
965 }
966
967 switch(fr->lay)
968 {
969 #ifndef NO_LAYER1
970 case 1:
971 fr->do_layer = do_layer1;
972 if(!fr->freeformat)
973 {
974 fr->framesize = (long) tabsel_123[fr->lsf][0][fr->bitrate_index] * 12000;
975 fr->framesize /= freqs[fr->sampling_frequency];
976 fr->framesize = ((fr->framesize+fr->padding)<<2)-4;
977 }
978 break;
979 #endif
980 #ifndef NO_LAYER2
981 case 2:
982 fr->do_layer = do_layer2;
983 if(!fr->freeformat)
984 {
985 debug2("bitrate index: %i (%i)", fr->bitrate_index, tabsel_123[fr->lsf][1][fr->bitrate_index] );
986 fr->framesize = (long) tabsel_123[fr->lsf][1][fr->bitrate_index] * 144000;
987 fr->framesize /= freqs[fr->sampling_frequency];
988 fr->framesize += fr->padding - 4;
989 }
990 break;
991 #endif
992 #ifndef NO_LAYER3
993 case 3:
994 fr->do_layer = do_layer3;
995 if(fr->lsf)
996 fr->ssize = (fr->stereo == 1) ? 9 : 17;
997 else
998 fr->ssize = (fr->stereo == 1) ? 17 : 32;
999
1000 if(fr->error_protection)
1001 fr->ssize += 2;
1002
1003 if(!fr->freeformat)
1004 {
1005 fr->framesize = (long) tabsel_123[fr->lsf][2][fr->bitrate_index] * 144000;
1006 fr->framesize /= freqs[fr->sampling_frequency]<<(fr->lsf);
1007 fr->framesize = fr->framesize + fr->padding - 4;
1008 }
1009 break;
1010 #endif
1011 default:
1012 if(NOQUIET) error1("Layer type %i not supported in this build!", fr->lay);
1013
1014 return 0;
1015 }
1016 if (fr->framesize > MAXFRAMESIZE)
1017 {
1018 if(NOQUIET) error1("Frame size too big: %d", fr->framesize+4-fr->padding);
1019
1020 return (0);
1021 }
1022 return 1;
1023 }
1024
1025 void set_pointer(mpg123_handle *fr, long backstep)
1026 {
1027 fr->wordpointer = fr->bsbuf + fr->ssize - backstep;
1028 if (backstep)
1029 memcpy(fr->wordpointer,fr->bsbufold+fr->fsizeold-backstep,backstep);
1030
1031 fr->bitindex = 0;
1032 }
1033
1034 /********************************/
1035
1036 double compute_bpf(mpg123_handle *fr)
1037 {
1038 double bpf;
1039
1040 switch(fr->lay)
1041 {
1042 case 1:
1043 bpf = tabsel_123[fr->lsf][0][fr->bitrate_index];
1044 bpf *= 12000.0 * 4.0;
1045 bpf /= freqs[fr->sampling_frequency] <<(fr->lsf);
1046 break;
1047 case 2:
1048 case 3:
1049 bpf = tabsel_123[fr->lsf][fr->lay-1][fr->bitrate_index];
1050 bpf *= 144000;
1051 bpf /= freqs[fr->sampling_frequency] << (fr->lsf);
1052 break;
1053 default:
1054 bpf = 1.0;
1055 }
1056
1057 return bpf;
1058 }
1059
1060 double attribute_align_arg mpg123_tpf(mpg123_handle *fr)
1061 {
1062 static int bs[4] = { 0,384,1152,1152 };
1063 double tpf;
1064 if(fr == NULL) return -1;
1065
1066 tpf = (double) bs[fr->lay];
1067 tpf /= freqs[fr->sampling_frequency] << (fr->lsf);
1068 return tpf;
1069 }
1070
1071 int attribute_align_arg mpg123_position(mpg123_handle *fr, off_t no, off_t buffsize,
1072 off_t *current_frame, off_t *frames_left,
1073 double *current_seconds, double *seconds_left)
1074 {
1075 double tpf;
1076 double dt = 0.0;
1077 off_t cur, left;
1078 double curs, lefts;
1079
1080 if(!fr || !fr->rd) /* Isn't this too paranoid? */
1081 {
1082 debug("reader troubles!");
1083 return MPG123_ERR;
1084 }
1085
1086 no += fr->num; /* no starts out as offset */
1087 cur = no;
1088 tpf = mpg123_tpf(fr);
1089 if(buffsize > 0 && fr->af.rate > 0 && fr->af.channels > 0)
1090 {
1091 dt = (double) buffsize / fr->af.rate / fr->af.channels;
1092 if(fr->af.encoding & MPG123_ENC_16) dt *= 0.5;
1093 }
1094
1095 left = 0;
1096
1097 if((fr->track_frames != 0) && (fr->track_frames >= fr->num)) left = no < fr->track_frames ? fr->track_frames - no : 0;
1098 else
1099 if(fr->rdat.filelen >= 0)
1100 {
1101 double bpf;
1102 off_t t = fr->rd->tell(fr);
1103 bpf = fr->mean_framesize ? fr->mean_framesize : compute_bpf(fr);
1104 left = (off_t)((double)(fr->rdat.filelen-t)/bpf);
1105 /* no can be different for prophetic purposes, file pointer is always associated with fr->num! */
1106 if(fr->num != no)
1107 {
1108 if(fr->num > no) left += fr->num - no;
1109 else
1110 {
1111 if(left >= (no - fr->num)) left -= no - fr->num;
1112 else left = 0; /* uh, oh! */
1113 }
1114 }
1115 /* I totally don't understand why we should re-estimate the given correct(?) value */
1116 /* fr->num = (unsigned long)((double)t/bpf); */
1117 }
1118
1119 /* beginning with 0 or 1?*/
1120 curs = (double) no*tpf-dt;
1121 lefts = (double)left*tpf+dt;
1122 #if 0
1123 curs = curs < 0 ? 0.0 : curs;
1124 #endif
1125 if(left < 0 || lefts < 0)
1126 { /* That is the case for non-seekable streams. */
1127 left = 0;
1128 lefts = 0.0;
1129 }
1130 if(current_frame != NULL) *current_frame = cur;
1131 if(frames_left != NULL) *frames_left = left;
1132 if(current_seconds != NULL) *current_seconds = curs;
1133 if(seconds_left != NULL) *seconds_left = lefts;
1134 return MPG123_OK;
1135 }
1136
1137 int get_songlen(mpg123_handle *fr,int no)
1138 {
1139 double tpf;
1140
1141 if(!fr)
1142 return 0;
1143
1144 if(no < 0) {
1145 if(!fr->rd || fr->rdat.filelen < 0)
1146 return 0;
1147 no = (int) ((double) fr->rdat.filelen / compute_bpf(fr));
1148 }
1149
1150 tpf = mpg123_tpf(fr);
1151 return (int) (no*tpf);
1152 }