2 parse: spawned from common; clustering around stream/frame parsing
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
9 #include "mpg123lib_intern.h"
16 #if defined (WANT_WIN32_SOCKETS)
21 /* a limit for number of frames in a track; beyond that unsigned long may not be enough to hold byte addresses */
26 /* hm, is this portable across preprocessors? */
27 #define ULONG_MAX ((unsigned long)-1)
29 #define TRACK_MAX_FRAMES ULONG_MAX/4/1152
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) ) )
36 AAAAAAAA AAABBCCD EEEEFFGH IIJJKLMM
51 old compare mask 0xfffffd00:
52 11111111 11111111 11111101 00000000
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.
59 11111111 11111111 00001101 00000000
61 Even more, I'll allow varying crc bit.
62 11111111 11111110 00001101 00000000
64 (still unsure about this private bit)
66 #define HDRCMPMASK 0xfffe0d00
67 #define HDRSAMPMASK 0xc00 /* 1100 00000000, FF bits (sample rate) */
69 /* bitrates for [mpeg1/2][layer] */
70 static const int tabsel_123
[2][3][16] =
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,}
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,}
84 const long freqs
[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 };
86 static int decode_header(mpg123_handle
*fr
,unsigned long newhead
);
88 /* These two are to be replaced by one function that gives all the frame parameters (for outsiders).*/
90 int frame_bitrate(mpg123_handle
*fr
)
92 return tabsel_123
[fr
->lsf
][fr
->lay
-1][fr
->bitrate_index
];
95 long frame_freq(mpg123_handle
*fr
)
97 return freqs
[fr
->sampling_frequency
];
100 #define free_format_header(head) ( ((head & 0xffe00000) == 0xffe00000) && ((head>>17)&3) && (((head>>12)&0xf) == 0x0) && (((head>>10)&0x3) != 0x3 ))
102 /* compiler is smart enought to inline this one or should I really do it as macro...? */
103 int head_check(unsigned long head
)
107 /* first 11 bits are set to 1 for frame sync */
108 ((head
& 0xffe00000) != 0xffe00000)
110 /* layer: 01,10,11 is 1,2,3; 00 is reserved */
113 /* 1111 means bad bitrate */
114 (((head
>>12)&0xf) == 0xf)
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 */
123 /* if no check failed, the header is valid (hopefully)*/
130 static int check_lame_tag(mpg123_handle
*fr
)
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
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.
141 int lame_offset
= (fr
->stereo
== 2) ? (fr
->lsf
? 17 : 32 ) : (fr
->lsf
? 9 : 17);
142 /* At least skip the decoder delay. */
144 if(fr
->p
.flags
& MPG123_GAPLESS
)
146 if(fr
->begin_s
== 0) frame_gapless_init(fr
, GAPLESS_DELAY
, 0);
150 if(fr
->framesize
>= 120+lame_offset
) /* traditional Xing header is 120 bytes */
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;
159 debug("possibly...");
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')
168 lame_type
= 1; /* We still have to see what there is */
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')
179 fr
->vbr
= MPG123_VBR
; /* Xing header means always VBR */
183 unsigned long xing_flags
;
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]))
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
);
196 debug1("Xing: flags 0x%08lx", xing_flags
);
197 if(xing_flags
& 1) /* frames */
199 if(fr
->p
.flags
& MPG123_IGNORE_STREAMLENGTH
)
202 fprintf(stderr
, "Note: Ignoring Xing frames because of MPG123_IGNORE_STREAMLENGTH\n");
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.
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? */
215 /* if no further info there, remove/add at least the decoder delay */
216 if(fr
->p
.flags
& MPG123_GAPLESS
)
218 off_t length
= fr
->track_frames
* spf(fr
);
220 frame_gapless_init(fr
, GAPLESS_DELAY
, length
+GAPLESS_DELAY
);
223 if(VERBOSE3
) fprintf(stderr
, "Note: Xing: %lu frames\n", (long unsigned)fr
->track_frames
);
228 if(xing_flags
& 0x2) /* bytes */
230 if(fr
->p
.flags
& MPG123_IGNORE_STREAMLENGTH
)
233 fprintf(stderr
, "Note: Ignoring Xing bytes because of MPG123_IGNORE_STREAMLENGTH\n");
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. */
243 if((off_t
) xing_bytes
!= fr
->rdat
.filelen
&& NOQUIET
)
245 double diff
= 1.0/fr
->rdat
.filelen
* (fr
->rdat
.filelen
- (off_t
)xing_bytes
);
246 if(diff
< 0.) diff
= -diff
;
249 fprintf(stderr
, "Note: Xing stream size %lu differs by %f%% from determined/given file size!\n", xing_bytes
, diff
);
252 fprintf(stderr
, "Warning: Xing stream size off by more than 1%%, fuzzy seeking may be even more fuzzy than by design!\n");
257 fprintf(stderr
, "Note: Xing: %lu bytes\n", (long unsigned)xing_bytes
);
262 if(xing_flags
& 0x4) /* TOC */
264 frame_fill_toc(fr
, fr
->bsbuf
+lame_offset
);
265 lame_offset
+= 100; /* just skip */
267 if(xing_flags
& 0x8) /* VBR quality */
271 unsigned long xing_quality
= make_long(fr
->bsbuf
, lame_offset
);
272 fprintf(stderr
, "Note: Xing: quality = %lu\n", (long unsigned)xing_quality
);
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)
280 unsigned char lame_vbr
;
281 float replay_gain
[2] = {0,0};
283 float gain_offset
= 0; /* going to be +6 for old lame that used 83dB */
285 memcpy(nb
, fr
->bsbuf
+lame_offset
, 9);
287 if(VERBOSE3
) fprintf(stderr
, "Note: Info: Encoder: %s\n", nb
);
288 if(!strncmp("LAME", nb
, 4))
291 debug("TODO: finish lame detetcion...");
294 /* the 4 big bits are tag revision, the small bits vbr method */
295 lame_vbr
= fr
->bsbuf
[lame_offset
] & 15;
298 fprintf(stderr
, "Note: Info: rev %u\n", fr
->bsbuf
[lame_offset
] >> 4);
299 fprintf(stderr
, "Note: Info: vbr mode %u\n", lame_vbr
);
304 /* from rev1 proposal... not sure if all good in practice */
306 case 8: fr
->vbr
= MPG123_CBR
; break;
308 case 9: fr
->vbr
= MPG123_ABR
; break;
309 default: fr
->vbr
= MPG123_VBR
; /* 00==unknown is taken as VBR */
311 /* skipping: lowpass filter value */
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! */
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)
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?
328 peak = *(float*) (fr->bsbuf+lame_offset); */
330 if(VERBOSE3
) fprintf(stderr
, "Note: Info: peak = %f (I won't use this)\n", peak
);
331 peak
= 0; /* until better times arrived */
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
341 for(i
=0; i
< 2; ++i
)
343 unsigned char origin
= (fr
->bsbuf
[lame_offset
] >> 2) & 0x7; /* the 3 bits after that... */
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 */
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);
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]);
362 if(fr
->rva
.level
[i
] <= 0)
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;
369 lame_offset
+= 1; /* skipping encoding flags byte */
370 if(fr
->vbr
== MPG123_ABR
)
372 fr
->abr_rate
= fr
->bsbuf
[lame_offset
];
373 if(VERBOSE3
) fprintf(stderr
, "Note: Info: ABR rate = %u\n", fr
->abr_rate
);
376 /* encoder delay and padding, two 12 bit values... lame does write them from int ...*/
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) );
382 if(fr
->p
.flags
& MPG123_GAPLESS
)
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
);
390 frame_gapless_init(fr
, skipbegin
, (skipend
< length
) ? length
-skipend
: length
);
394 /* switch buffer back ... */
395 fr
->bsbuf
= fr
->bsspace
[fr
->bsnum
]+512;
396 fr
->bsnum
= (fr
->bsnum
+ 1) & 1;
397 return 1; /* got it! */
401 return 0; /* no lame tag */
404 /* Just tell if the header is some mono. */
405 static int header_mono(unsigned long newhead
)
407 return ((newhead
>>6)&0x3) == MPG_MD_MONO
? TRUE
: FALSE
;
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.
414 int read_frame(mpg123_handle
*fr
)
416 /* TODO: rework this thing */
417 unsigned long newhead
;
420 /* stuff that needs resetting if complete frame reading fails */
421 int oldsize
= fr
->framesize
;
422 int oldphase
= fr
->halfphase
;
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. */
429 fr
->fsizeold
=fr
->framesize
; /* for Layer3 */
431 /* Speed-down hack: Play it again, Sam (the frame, I mean). */
434 if(fr
->halfphase
) /* repeat last frame */
437 fr
->to_decode
= fr
->to_ignore
= TRUE
;
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 */
447 fr
->halfphase
= fr
->p
.halfspeed
- 1;
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
);
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
;}
461 fr
->header_change
= 2; /* output format change is possible... */
462 if(fr
->oldhead
) /* check a following header for change */
464 if(fr
->oldhead
== newhead
) fr
->header_change
= 0;
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
))
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;
477 /* watch out for junk/tags on beginning of stream by invalid header */
478 if(!fr
->firsthead
&& !head_check(newhead
)) {
480 /* check for id3v2; first three bytes (of 4) are "ID3" */
481 if((newhead
& (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
484 id3ret
= parse_new_id3(fr
, newhead
);
485 if (id3ret
< 0){ debug("need more?"); ret
= id3ret
; goto read_frame_bad
; }
487 else if(id3ret
> 0){ debug("got ID3v2"); fr
->metaflags
|= MPG123_NEW_ID3
|MPG123_ID3
; }
488 else debug("no useful ID3v2");
492 goto read_again
; /* Also in case of invalid ID3 tag (ret==0), try to get on track again. */
494 else if(VERBOSE2
&& fr
->silent_resync
== 0) fprintf(stderr
,"Note: Junk at the beginning (0x%08lx)\n",newhead
);
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");
500 if((ret
=fr
->rd
->head_read(fr
,&newhead
))<=0){ debug("need more?"); goto read_frame_bad
; }
502 while(newhead
!= ('d'<<24)+('a'<<16)+('t'<<8)+'a')
504 if((ret
=fr
->rd
->head_shift(fr
,&newhead
))<=0){ debug("need more?"); goto read_frame_bad
; }
506 if((ret
=fr
->rd
->head_read(fr
,&newhead
))<=0){ debug("need more?"); goto read_frame_bad
; }
508 if(VERBOSE2
&& fr
->silent_resync
== 0) fprintf(stderr
,"Note: Skipped RIFF header!\n");
513 /* unhandled junk... just continue search for a header */
514 /* step in byte steps through next 64K */
515 debug("searching for header...");
517 ret
= 0; /* We will check the value after the loop. */
518 for(; headcount
<65536; headcount
++)
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
)))
525 if(ret
<0){ debug("need more?"); goto read_frame_bad
; }
527 if(headcount
== 65536)
529 if(NOQUIET
) error("Giving up searching valid MPEG header after (over) 64K of junk.");
532 else debug1("hopefully found one at %"OFF_P
, (off_p
)fr
->rd
->tell(fr
));
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.
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
)))
544 unsigned long nexthead
= 0;
546 off_t start
= fr
->rd
->tell(fr
);
547 if(ret
<0){ debug("need more?"); goto read_frame_bad
; }
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)
553 if(ret
==READER_ERROR
&& NOQUIET
) error("cannot seek!");
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)
560 if(ret
==READER_ERROR
&& NOQUIET
) error("cannot seek!");
561 else debug("need more?");
564 debug1("After fetching next header, at %"OFF_P
, (off_p
)fr
->rd
->tell(fr
));
567 if(NOQUIET
) warning("cannot read next header, a one-frame stream? Duh...");
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
))
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)
580 if(NOQUIET
) error("cannot seek!");
581 else debug("need more?");
589 /* why has this head check been avoided here before? */
590 if(!head_check(newhead
))
592 /* and those ugly ID3 tags */
593 if((newhead
& 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8))
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");
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)
610 id3length
= parse_new_id3(fr
, newhead
);
611 if(id3length
< 0){ debug("need more?"); ret
= id3length
; goto read_frame_bad
; }
613 fr
->metaflags
|= MPG123_NEW_ID3
|MPG123_ID3
;
616 else if(NOQUIET
&& fr
->silent_resync
== 0)
618 fprintf(stderr
,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset %"OFF_P
".\n",
619 newhead
, (off_p
)fr
->rd
->tell(fr
)-4);
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
) )
628 long limit
= fr
->p
.resync_limit
;
630 /* If a resync is needed the bitreservoir of previous frames is no longer valid */
631 fr
->bitreservoir
= 0;
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). */
643 if(limit
>= 0 && try >= limit
) break;
645 if((ret
=fr
->rd
->head_shift(fr
,&newhead
)) <= 0)
648 if(NOQUIET
) fprintf (stderr
, "Note: Hit end of (available) data during resync.\n");
652 if(VERBOSE3
) debug3("resync try %li at %"OFF_P
", got newhead 0x%08lx", try, (off_p
)fr
->rd
->tell(fr
), newhead
);
656 debug("going to init_resync...");
657 goto init_resync
; /* "considered harmful", eh? */
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?) */
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)*/
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);
671 if(limit
>= 0 && try >= limit
)
674 error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try);
676 fr
->err
= MPG123_RESYNC_FAIL
;
681 debug1("Found valid header 0x%lx... unsetting firsthead to reinit stream.", newhead
);
688 if(NOQUIET
) error("not attempting to resync...");
690 fr
->err
= MPG123_OUT_OF_SYNC
;
695 /* Man, that code looks awfully redundant...
696 I need to untangle the spaghetti here in a future version. */
699 ret
=decode_header(fr
,newhead
);
702 if(NOQUIET
) error("decode header failed before first valid one, going to read again");
706 else if(ret
< 0){ debug("need more?"); goto read_frame_bad
; }
710 ret
=decode_header(fr
,newhead
);
713 if(NOQUIET
) error("decode header failed - goto resync");
717 else if(ret
< 0){ debug("need more?"); goto read_frame_bad
; }
720 /* if filepos is invalid, so is framepos */
721 framepos
= fr
->rd
->tell(fr
) - 4;
722 /* flip/init buffer for Layer 3 */
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)
728 /* if failed: flip back */
732 fr
->bsbufold
= fr
->bsbuf
;
735 fr
->bsnum
= (fr
->bsnum
+ 1) & 1;
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. */
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
);
755 /* now adjust volume */
759 debug2("fr->firsthead: %08lx, audio_start: %li", fr
->firsthead
, (long int)fr
->audio_start
);
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)
768 fr
->mean_framesize
= ((fr
->mean_frames
-1)*fr
->mean_framesize
+compute_bpf(fr
)) / fr
->mean_frames
;
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
));
774 /* save for repetition */
775 if(fr
->p
.halfspeed
&& fr
->lay
== 3)
777 debug("halfspeed - reusing old bsbuf ");
778 memcpy (fr
->ssave
, fr
->bsbuf
, fr
->ssize
);
781 /* index the position */
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
);
789 if(fr
->silent_resync
> 0) --fr
->silent_resync
;
791 if(fr
->rd
->forget
!= NULL
) fr
->rd
->forget(fr
);
793 fr
->to_decode
= fr
->to_ignore
= TRUE
;
794 if(fr
->error_protection
) fr
->crc
= getbits(fr
, 16); /* skip crc */
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
);
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. */
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...)
818 static int guess_freeformat_framesize(mpg123_handle
*fr
)
823 if(!(fr
->rdat
.flags
& (READER_SEEKABLE
|READER_BUFFERED
)))
825 if(NOQUIET
) error("Cannot look for freeformat frame size with non-seekable and non-buffered stream!");
829 if((ret
=fr
->rd
->head_read(fr
,&head
))<=0)
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)
841 int sampling_frequency
,mpeg25
,lsf
;
845 lsf
= (head
& (1<<19)) ? 0x0 : 0x1;
855 sampling_frequency
= 6 + ((head
>>10)&0x3);
857 sampling_frequency
= ((head
>>10)&0x3) + (lsf
*3);
859 if((lsf
==fr
->lsf
) && (mpeg25
==fr
->mpeg25
) && (sampling_frequency
== fr
->sampling_frequency
))
861 fr
->rd
->back_bytes(fr
,i
+1);
863 return 1; /* Success! */
867 fr
->rd
->back_bytes(fr
,i
);
873 * decode a header and write the information
874 * into the frame structure
875 * Return values are compatible with those of read_frame, namely:
880 static int decode_header(mpg123_handle
*fr
,unsigned long newhead
)
882 if(!head_check(newhead
))
884 if(NOQUIET
) error("tried to decode obviously invalid header");
888 if( newhead
& (1<<20) )
890 fr
->lsf
= (newhead
& (1<<19)) ? 0x0 : 0x1;
899 if( (fr
->p
.flags
& MPG123_NO_RESYNC
) || !fr
->oldhead
900 || (((fr
->oldhead
>>19)&0x3) ^ ((newhead
>>19)&0x3)) )
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
906 fr
->lay
= 4-((newhead
>>17)&3);
907 if( ((newhead
>>10)&0x3) == 0x3)
909 if(NOQUIET
) error("Stream error");
911 return 0; /* exit() here really is too much, isn't it? */
914 fr
->sampling_frequency
= 6 + ((newhead
>>10)&0x3);
916 fr
->sampling_frequency
= ((newhead
>>10)&0x3) + (fr
->lsf
*3);
920 if((((newhead
>>16)&0x1)^0x1) != fr
->error_protection
) debug("changed crc bit!");
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
);
933 fr
->stereo
= (fr
->mode
== MPG_MD_MONO
) ? 1 : 2;
935 fr
->oldhead
= newhead
;
937 /* we can't use tabsel_123 for freeformat, so trying to guess framesize... */
940 /* when we first encounter the frame with freeformat, guess framesize */
941 if(fr
->freeformat_framesize
< 0)
944 ret
= guess_freeformat_framesize(fr
);
947 fr
->freeformat_framesize
= fr
->framesize
- fr
->padding
;
949 fprintf(stderr
, "Note: free format frame size %li\n", fr
->freeformat_framesize
);
953 if(ret
== MPG123_NEED_MORE
)
954 debug("Need more data to guess free format frame size.");
956 error("Encountered free format header, but failed to guess frame size.");
960 /* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */
963 fr
->framesize
= fr
->freeformat_framesize
+ fr
->padding
;
971 fr
->do_layer
= do_layer1
;
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;
982 fr
->do_layer
= do_layer2
;
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;
994 fr
->do_layer
= do_layer3
;
996 fr
->ssize
= (fr
->stereo
== 1) ? 9 : 17;
998 fr
->ssize
= (fr
->stereo
== 1) ? 17 : 32;
1000 if(fr
->error_protection
)
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;
1012 if(NOQUIET
) error1("Layer type %i not supported in this build!", fr
->lay
);
1016 if (fr
->framesize
> MAXFRAMESIZE
)
1018 if(NOQUIET
) error1("Frame size too big: %d", fr
->framesize
+4-fr
->padding
);
1025 void set_pointer(mpg123_handle
*fr
, long backstep
)
1027 fr
->wordpointer
= fr
->bsbuf
+ fr
->ssize
- backstep
;
1029 memcpy(fr
->wordpointer
,fr
->bsbufold
+fr
->fsizeold
-backstep
,backstep
);
1034 /********************************/
1036 double compute_bpf(mpg123_handle
*fr
)
1043 bpf
= tabsel_123
[fr
->lsf
][0][fr
->bitrate_index
];
1044 bpf
*= 12000.0 * 4.0;
1045 bpf
/= freqs
[fr
->sampling_frequency
] <<(fr
->lsf
);
1049 bpf
= tabsel_123
[fr
->lsf
][fr
->lay
-1][fr
->bitrate_index
];
1051 bpf
/= freqs
[fr
->sampling_frequency
] << (fr
->lsf
);
1060 double attribute_align_arg
mpg123_tpf(mpg123_handle
*fr
)
1062 static int bs
[4] = { 0,384,1152,1152 };
1064 if(fr
== NULL
) return -1;
1066 tpf
= (double) bs
[fr
->lay
];
1067 tpf
/= freqs
[fr
->sampling_frequency
] << (fr
->lsf
);
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
)
1080 if(!fr
|| !fr
->rd
) /* Isn't this too paranoid? */
1082 debug("reader troubles!");
1086 no
+= fr
->num
; /* no starts out as offset */
1088 tpf
= mpg123_tpf(fr
);
1089 if(buffsize
> 0 && fr
->af
.rate
> 0 && fr
->af
.channels
> 0)
1091 dt
= (double) buffsize
/ fr
->af
.rate
/ fr
->af
.channels
;
1092 if(fr
->af
.encoding
& MPG123_ENC_16
) dt
*= 0.5;
1097 if((fr
->track_frames
!= 0) && (fr
->track_frames
>= fr
->num
)) left
= no
< fr
->track_frames
? fr
->track_frames
- no
: 0;
1099 if(fr
->rdat
.filelen
>= 0)
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! */
1108 if(fr
->num
> no
) left
+= fr
->num
- no
;
1111 if(left
>= (no
- fr
->num
)) left
-= no
- fr
->num
;
1112 else left
= 0; /* uh, oh! */
1115 /* I totally don't understand why we should re-estimate the given correct(?) value */
1116 /* fr->num = (unsigned long)((double)t/bpf); */
1119 /* beginning with 0 or 1?*/
1120 curs
= (double) no
*tpf
-dt
;
1121 lefts
= (double)left
*tpf
+dt
;
1123 curs
= curs
< 0 ? 0.0 : curs
;
1125 if(left
< 0 || lefts
< 0)
1126 { /* That is the case for non-seekable streams. */
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
;
1137 int get_songlen(mpg123_handle
*fr
,int no
)
1145 if(!fr
->rd
|| fr
->rdat
.filelen
< 0)
1147 no
= (int) ((double) fr
->rdat
.filelen
/ compute_bpf(fr
));
1150 tpf
= mpg123_tpf(fr
);
1151 return (int) (no
*tpf
);