2 parse: spawned from common; clustering around stream/frame parsing
4 copyright ?-2014 by the mpg123 project - free software under the terms of the LGPL 2.1
5 see COPYING and AUTHORS files in distribution or http://mpg123.org
6 initially written by Michael Hipp & Thomas Orgis
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
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) ) )
37 /* PARSE_GOOD and PARSE_BAD have to be 1 and 0 (TRUE and FALSE), others can vary. */
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. */
49 /* bitrates for [mpeg1/2][layer] */
50 static const int tabsel_123
[2][3][16] =
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,}
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,}
64 static const long freqs
[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 };
66 static int decode_header(mpg123_handle
*fr
,unsigned long newhead
, int *freeformat_count
);
67 static int skip_junk(mpg123_handle
*fr
, unsigned long *newheadp
, long *headcount
);
68 static int do_readahead(mpg123_handle
*fr
, unsigned long newhead
);
69 static int wetwork(mpg123_handle
*fr
, unsigned long *newheadp
);
71 /* These two are to be replaced by one function that gives all the frame parameters (for outsiders).*/
72 /* Those functions are unsafe regarding bad arguments (inside the mpg123_handle), but just returning anything would also be unsafe, the caller code has to be trusted. */
74 int frame_bitrate(mpg123_handle
*fr
)
76 return tabsel_123
[fr
->lsf
][fr
->lay
-1][fr
->bitrate_index
];
79 long frame_freq(mpg123_handle
*fr
)
81 return freqs
[fr
->sampling_frequency
];
84 /* compiler is smart enought to inline this one or should I really do it as macro...? */
85 static int head_check(unsigned long head
)
89 ((head
& HDR_SYNC
) != HDR_SYNC
)
91 /* layer: 01,10,11 is 1,2,3; 00 is reserved */
92 (!(HDR_LAYER_VAL(head
)))
94 /* 1111 means bad bitrate */
95 (HDR_BITRATE_VAL(head
) == 0xf)
97 /* sampling freq: 11 is reserved */
98 (HDR_SAMPLERATE_VAL(head
) == 0x3)
99 /* here used to be a mpeg 2.5 check... re-enabled 2.5 decoding due to lack of evidence that it is really not good */
104 /* if no check failed, the header is valid (hopefully)*/
111 /* This is moderately sized buffers. Int offset is enough. */
112 static unsigned long bit_read_long(unsigned char *buf
, int *offset
)
114 unsigned long val
= /* 32 bit value */
115 (((unsigned long) buf
[*offset
]) << 24)
116 | (((unsigned long) buf
[*offset
+1]) << 16)
117 | (((unsigned long) buf
[*offset
+2]) << 8)
118 | ((unsigned long) buf
[*offset
+3]);
123 static unsigned short bit_read_short(unsigned char *buf
, int *offset
)
125 unsigned short val
= /* 16 bit value */
126 (((unsigned short) buf
[*offset
] ) << 8)
127 | ((unsigned short) buf
[*offset
+1]);
132 static int check_lame_tag(mpg123_handle
*fr
)
135 unsigned long xing_flags
;
136 unsigned long long_tmp
;
138 going to look for Xing or Info at some position after the header
139 MPEG 1 MPEG 2/2.5 (LSF)
140 Stereo, Joint Stereo, Dual Channel 32 17
143 int lame_offset
= (fr
->stereo
== 2)
144 ? (fr
->lsf
? 17 : 32)
145 : (fr
->lsf
? 9 : 17);
147 if(fr
->p
.flags
& MPG123_IGNORE_INFOFRAME
) goto check_lame_tag_no
;
149 debug("do we have lame tag?");
151 Note: CRC or not, that does not matter here.
152 But, there is any combination of Xing flags in the wild. There are headers
153 without the search index table! I cannot assume a reasonable minimal size
154 for the actual data, have to check if each byte of information is present.
155 But: 4 B Info/Xing + 4 B flags is bare minimum.
157 if(fr
->framesize
< lame_offset
+8) goto check_lame_tag_no
;
159 /* only search for tag when all zero before it (apart from checksum) */
160 for(i
=2; i
< lame_offset
; ++i
) if(fr
->bsbuf
[i
] != 0) goto check_lame_tag_no
;
162 debug("possibly...");
165 (fr
->bsbuf
[lame_offset
] == 'I')
166 && (fr
->bsbuf
[lame_offset
+1] == 'n')
167 && (fr
->bsbuf
[lame_offset
+2] == 'f')
168 && (fr
->bsbuf
[lame_offset
+3] == 'o')
171 /* We still have to see what there is */
175 (fr
->bsbuf
[lame_offset
] == 'X')
176 && (fr
->bsbuf
[lame_offset
+1] == 'i')
177 && (fr
->bsbuf
[lame_offset
+2] == 'n')
178 && (fr
->bsbuf
[lame_offset
+3] == 'g')
181 fr
->vbr
= MPG123_VBR
; /* Xing header means always VBR */
183 else goto check_lame_tag_no
;
185 /* we have one of these headers... */
186 if(VERBOSE2
) fprintf(stderr
, "Note: Xing/Lame/Info header detected\n");
188 xing_flags
= bit_read_long(fr
->bsbuf
, &lame_offset
);
189 debug1("Xing: flags 0x%08lx", xing_flags
);
191 /* From now on, I have to carefully check if the announced data is actually
192 there! I'm always returning 'yes', though. */
193 #define check_bytes_left(n) if(fr->framesize < lame_offset+n) \
194 goto check_lame_tag_yes
195 if(xing_flags
& 1) /* total bitstream frames */
197 check_bytes_left(4); long_tmp
= bit_read_long(fr
->bsbuf
, &lame_offset
);
198 if(fr
->p
.flags
& MPG123_IGNORE_STREAMLENGTH
)
200 if(VERBOSE3
) fprintf(stderr
201 , "Note: Ignoring Xing frames because of MPG123_IGNORE_STREAMLENGTH\n");
205 /* Check for endless stream, but: TRACK_MAX_FRAMES sensible at all? */
206 fr
->track_frames
= long_tmp
> TRACK_MAX_FRAMES
? 0 : (off_t
) long_tmp
;
208 /* All or nothing: Only if encoder delay/padding is known, we'll cut
209 samples for gapless. */
210 if(fr
->p
.flags
& MPG123_GAPLESS
)
211 frame_gapless_init(fr
, fr
->track_frames
, 0, 0);
213 if(VERBOSE3
) fprintf(stderr
, "Note: Xing: %lu frames\n", long_tmp
);
216 if(xing_flags
& 0x2) /* total bitstream bytes */
218 check_bytes_left(4); long_tmp
= bit_read_long(fr
->bsbuf
, &lame_offset
);
219 if(fr
->p
.flags
& MPG123_IGNORE_STREAMLENGTH
)
221 if(VERBOSE3
) fprintf(stderr
222 , "Note: Ignoring Xing bytes because of MPG123_IGNORE_STREAMLENGTH\n");
226 /* The Xing bitstream length, at least as interpreted by the Lame
227 encoder, encompasses all data from the Xing header frame on,
228 ignoring leading ID3v2 data. Trailing tags (ID3v1) seem to be
230 if(fr
->rdat
.filelen
< 1)
231 fr
->rdat
.filelen
= (off_t
) long_tmp
+ fr
->audio_start
; /* Overflow? */
234 if((off_t
)long_tmp
!= fr
->rdat
.filelen
- fr
->audio_start
&& NOQUIET
)
235 { /* 1/filelen instead of 1/(filelen-start), my decision */
236 double diff
= 100.0/fr
->rdat
.filelen
237 * ( fr
->rdat
.filelen
- fr
->audio_start
239 if(diff
< 0.) diff
= -diff
;
241 if(VERBOSE3
) fprintf(stderr
242 , "Note: Xing stream size %lu differs by %f%% from determined/given file size!\n"
245 if(diff
> 1. && NOQUIET
) fprintf(stderr
246 , "Warning: Xing stream size off by more than 1%%, fuzzy seeking may be even more fuzzy than by design!\n");
250 if(VERBOSE3
) fprintf(stderr
, "Note: Xing: %lu bytes\n", long_tmp
);
253 if(xing_flags
& 0x4) /* TOC */
255 check_bytes_left(100);
256 frame_fill_toc(fr
, fr
->bsbuf
+lame_offset
);
259 if(xing_flags
& 0x8) /* VBR quality */
261 check_bytes_left(4); long_tmp
= bit_read_long(fr
->bsbuf
, &lame_offset
);
262 if(VERBOSE3
) fprintf(stderr
, "Note: Xing: quality = %lu\n", long_tmp
);
265 Either zeros/nothing, or:
267 9: revision/VBR method
272 21-23: encoder delays
274 check_bytes_left(24); /* I'm interested in 24 B of extra info. */
275 if(fr
->bsbuf
[lame_offset
] != 0)
277 unsigned char lame_vbr
;
278 float replay_gain
[2] = {0,0};
280 float gain_offset
= 0; /* going to be +6 for old lame that used 83dB */
284 memcpy(nb
, fr
->bsbuf
+lame_offset
, 9);
286 if(VERBOSE3
) fprintf(stderr
, "Note: Info: Encoder: %s\n", nb
);
287 if(!strncmp("LAME", nb
, 4))
289 /* Lame versions before 3.95.1 used 83 dB reference level, later
290 versions 89 dB. We stick with 89 dB as being "normal", adding
292 unsigned int major
, minor
;
295 if(sscanf(nb
+4, "%u.%u%s", &major
, &minor
, rest
) >= 2)
297 debug3("LAME: %u/%u/%s", major
, minor
, rest
);
298 /* We cannot detect LAME 3.95 reliably (same version string as
299 3.95.1), so this is a blind spot. Everything < 3.95 is safe,
301 if(major
< 3 || (major
== 3 && minor
< 95))
304 if(VERBOSE3
) fprintf(stderr
305 , "Note: Info: Old LAME detected, using ReplayGain preamp of %f dB.\n"
309 else if(VERBOSE3
) fprintf(stderr
310 , "Note: Info: Cannot determine LAME version.\n");
312 lame_offset
+= 9; /* 9 in */
314 /* The 4 big bits are tag revision, the small bits vbr method. */
315 lame_vbr
= fr
->bsbuf
[lame_offset
] & 15;
316 lame_offset
+= 1; /* 10 in */
319 fprintf(stderr
, "Note: Info: rev %u\n", fr
->bsbuf
[lame_offset
] >> 4);
320 fprintf(stderr
, "Note: Info: vbr mode %u\n", lame_vbr
);
324 /* from rev1 proposal... not sure if all good in practice */
326 case 8: fr
->vbr
= MPG123_CBR
; break;
328 case 9: fr
->vbr
= MPG123_ABR
; break;
329 default: fr
->vbr
= MPG123_VBR
; /* 00==unknown is taken as VBR */
331 lame_offset
+= 1; /* 11 in, skipping lowpass filter value */
333 /* ReplayGain peak ampitude, 32 bit float -- why did I parse it as int
334 before?? Ah, yes, Lame seems to store it as int since some day in 2003;
335 I've only seen zeros anyway until now, bah! */
338 (fr
->bsbuf
[lame_offset
] != 0)
339 || (fr
->bsbuf
[lame_offset
+1] != 0)
340 || (fr
->bsbuf
[lame_offset
+2] != 0)
341 || (fr
->bsbuf
[lame_offset
+3] != 0)
344 debug("Wow! Is there _really_ a non-zero peak value? Now is it stored as float or int - how should I know?");
345 /* byte*peak_bytes = (byte*) &peak;
346 ... endianess ... just copy bytes to avoid floating point operation on unaligned memory?
348 peak = *(float*) (fr->bsbuf+lame_offset); */
350 if(VERBOSE3
) fprintf(stderr
351 , "Note: Info: peak = %f (I won't use this)\n", peak
);
352 peak
= 0; /* until better times arrived */
353 lame_offset
+= 4; /* 15 in */
355 /* ReplayGain values - lame only writes radio mode gain...
356 16bit gain, 3 bits name, 3 bits originator, sign (1=-, 0=+),
357 dB value*10 in 9 bits (fixed point) ignore the setting if name or
359 radio 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1
360 audiophile 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0 */
361 for(i
=0; i
< 2; ++i
)
363 unsigned char gt
= fr
->bsbuf
[lame_offset
] >> 5;
364 unsigned char origin
= (fr
->bsbuf
[lame_offset
] >> 2) & 0x7;
365 float factor
= (fr
->bsbuf
[lame_offset
] & 0x2) ? -0.1 : 0.1;
366 unsigned short gain
= bit_read_short(fr
->bsbuf
, &lame_offset
) & 0x1ff; /* 19 in (2 cycles) */
367 if(origin
== 0 || gt
< 1 || gt
> 2) continue;
370 replay_gain
[gt
] = factor
* (float) gain
;
371 /* Apply gain offset for automatic origin. */
372 if(origin
== 3) replay_gain
[gt
] += gain_offset
;
376 fprintf(stderr
, "Note: Info: Radio Gain = %03.1fdB\n"
378 fprintf(stderr
, "Note: Info: Audiophile Gain = %03.1fdB\n"
383 if(fr
->rva
.level
[i
] <= 0)
385 fr
->rva
.peak
[i
] = 0; /* TODO: use parsed peak? */
386 fr
->rva
.gain
[i
] = replay_gain
[i
];
387 fr
->rva
.level
[i
] = 0;
391 lame_offset
+= 1; /* 20 in, skipping encoding flags byte */
394 if(fr
->vbr
== MPG123_ABR
)
396 fr
->abr_rate
= fr
->bsbuf
[lame_offset
];
397 if(VERBOSE3
) fprintf(stderr
, "Note: Info: ABR rate = %u\n"
400 lame_offset
+= 1; /* 21 in */
402 /* Encoder delay and padding, two 12 bit values
403 ... lame does write them from int. */
404 pad_in
= ( (((int) fr
->bsbuf
[lame_offset
]) << 4)
405 | (((int) fr
->bsbuf
[lame_offset
+1]) >> 4) );
406 pad_out
= ( (((int) fr
->bsbuf
[lame_offset
+1]) << 8)
407 | ((int) fr
->bsbuf
[lame_offset
+2]) ) & 0xfff;
408 lame_offset
+= 3; /* 24 in */
409 if(VERBOSE3
) fprintf(stderr
, "Note: Encoder delay = %i; padding = %i\n"
410 , (int)pad_in
, (int)pad_out
);
412 if(fr
->p
.flags
& MPG123_GAPLESS
)
413 frame_gapless_init(fr
, fr
->track_frames
, pad_in
, pad_out
);
415 /* final: 24 B LAME data */
419 /* switch buffer back ... */
420 fr
->bsbuf
= fr
->bsspace
[fr
->bsnum
]+512;
421 fr
->bsnum
= (fr
->bsnum
+ 1) & 1;
427 /* Just tell if the header is some mono. */
428 static int header_mono(unsigned long newhead
)
430 return HDR_CHANNEL_VAL(newhead
) == MPG_MD_MONO
? TRUE
: FALSE
;
433 /* true if the two headers will work with the same decoding routines */
434 static int head_compatible(unsigned long fred
, unsigned long bret
)
436 return ( (fred
& HDR_CMPMASK
) == (bret
& HDR_CMPMASK
)
437 && header_mono(fred
) == header_mono(bret
) );
440 static void halfspeed_prepare(mpg123_handle
*fr
)
442 /* save for repetition */
443 if(fr
->p
.halfspeed
&& fr
->lay
== 3)
445 debug("halfspeed - reusing old bsbuf ");
446 memcpy (fr
->ssave
, fr
->bsbuf
, fr
->ssize
);
450 /* If this returns 1, the next frame is the repetition. */
451 static int halfspeed_do(mpg123_handle
*fr
)
453 /* Speed-down hack: Play it again, Sam (the frame, I mean). */
456 if(fr
->halfphase
) /* repeat last frame */
459 fr
->to_decode
= fr
->to_ignore
= TRUE
;
462 fr
->wordpointer
= (unsigned char *) fr
->bsbuf
;
463 if(fr
->lay
== 3) memcpy (fr
->bsbuf
, fr
->ssave
, fr
->ssize
);
464 if(fr
->error_protection
) fr
->crc
= getbits(fr
, 16); /* skip crc */
469 fr
->halfphase
= fr
->p
.halfspeed
- 1;
476 Temporary macro until we got this worked out.
477 Idea is to filter out special return values that shall trigger direct jumps to end / resync / read again.
478 Particularily, the generic ret==PARSE_BAD==0 and ret==PARSE_GOOD==1 are not affected.
480 #define JUMP_CONCLUSION(ret) \
482 if(ret < 0){ debug1("%s", ret == MPG123_NEED_MORE ? "need more" : "read error"); goto read_frame_bad; } \
483 else if(ret == PARSE_AGAIN) goto read_again; \
484 else if(ret == PARSE_RESYNC) goto init_resync; \
485 else if(ret == PARSE_END){ ret=0; goto read_frame_bad; } \
489 That's a big one: read the next frame. 1 is success, <= 0 is some error
490 Special error READER_MORE means: Please feed more data and try again.
492 int read_frame(mpg123_handle
*fr
)
494 /* TODO: rework this thing */
495 int freeformat_count
= 0;
496 unsigned long newhead
;
499 /* stuff that needs resetting if complete frame reading fails */
500 int oldsize
= fr
->framesize
;
501 int oldphase
= fr
->halfphase
;
503 /* The counter for the search-first-header loop.
504 It is persistent outside the loop to prevent seemingly endless loops
505 when repeatedly headers are found that do not have valid followup headers. */
508 fr
->fsizeold
=fr
->framesize
; /* for Layer3 */
510 if(halfspeed_do(fr
) == 1) return 1;
513 /* In case we are looping to find a valid frame, discard any buffered data before the current position.
514 This is essential to prevent endless looping, always going back to the beginning when feeder buffer is exhausted. */
515 if(fr
->rd
->forget
!= NULL
) fr
->rd
->forget(fr
);
517 debug2("trying to get frame %"OFF_P
" at %"OFF_P
, (off_p
)fr
->num
+1, (off_p
)fr
->rd
->tell(fr
));
518 if((ret
= fr
->rd
->head_read(fr
,&newhead
)) <= 0){ debug1("need more? (%i)", ret
); goto read_frame_bad
;}
523 if(!fr
->firsthead
&& !head_check(newhead
))
525 ret
= skip_junk(fr
, &newhead
, &headcount
);
526 JUMP_CONCLUSION(ret
);
530 ret
= head_check(newhead
);
531 if(ret
) ret
= decode_header(fr
, newhead
, &freeformat_count
);
533 JUMP_CONCLUSION(ret
); /* That only continues for ret == PARSE_BAD or PARSE_GOOD. */
535 { /* Header was not good. */
536 ret
= wetwork(fr
, &newhead
); /* Messy stuff, handle junk, resync ... */
537 JUMP_CONCLUSION(ret
);
538 /* Normally, we jumped already. If for some reason everything's fine to continue, do continue. */
539 if(ret
!= PARSE_GOOD
) goto read_frame_bad
;
544 ret
= do_readahead(fr
, newhead
);
545 /* readahead can fail mit NEED_MORE, in which case we must also make the just read header available again for next go */
546 if(ret
< 0) fr
->rd
->back_bytes(fr
, 4);
547 JUMP_CONCLUSION(ret
);
550 /* Now we should have our valid header and proceed to reading the frame. */
552 /* if filepos is invalid, so is framepos */
553 framepos
= fr
->rd
->tell(fr
) - 4;
554 /* flip/init buffer for Layer 3 */
556 unsigned char *newbuf
= fr
->bsspace
[fr
->bsnum
]+512;
557 /* read main data into memory */
558 if((ret
=fr
->rd
->read_frame_body(fr
,newbuf
,fr
->framesize
))<0)
560 /* if failed: flip back */
564 fr
->bsbufold
= fr
->bsbuf
;
567 fr
->bsnum
= (fr
->bsnum
+ 1) & 1;
571 fr
->firsthead
= newhead
; /* _now_ it's time to store it... the first real header */
572 /* This is the first header of our current stream segment.
573 It is only the actual first header of the whole stream when fr->num is still below zero!
574 Think of resyncs where firsthead has been reset for format flexibility. */
577 fr
->audio_start
= framepos
;
578 /* Only check for LAME tag at beginning of whole stream
579 ... when there indeed is one in between, it's the user's problem. */
580 if(fr
->lay
== 3 && check_lame_tag(fr
) == 1)
581 { /* ...in practice, Xing/LAME tags are layer 3 only. */
582 if(fr
->rd
->forget
!= NULL
) fr
->rd
->forget(fr
);
587 /* now adjust volume */
591 debug2("fr->firsthead: %08lx, audio_start: %li", fr
->firsthead
, (long int)fr
->audio_start
);
595 fr
->wordpointer
= (unsigned char *) fr
->bsbuf
;
596 /* Question: How bad does the floating point value get with repeated recomputation?
597 Also, considering that we can play the file or parts of many times. */
598 if(++fr
->mean_frames
!= 0)
600 fr
->mean_framesize
= ((fr
->mean_frames
-1)*fr
->mean_framesize
+compute_bpf(fr
)) / fr
->mean_frames
;
602 ++fr
->num
; /* 0 for first frame! */
603 debug4("Frame %"OFF_P
" %08lx %i, next filepos=%"OFF_P
,
604 (off_p
)fr
->num
, newhead
, fr
->framesize
, (off_p
)fr
->rd
->tell(fr
));
605 if(!(fr
->state_flags
& FRAME_FRANKENSTEIN
) && (
606 (fr
->track_frames
> 0 && fr
->num
>= fr
->track_frames
)
608 || (fr
->gapless_frames
> 0 && fr
->num
>= fr
->gapless_frames
)
612 fr
->state_flags
|= FRAME_FRANKENSTEIN
;
613 if(NOQUIET
) fprintf(stderr
, "\nWarning: Encountered more data after announced end of track (frame %"OFF_P
"/%"OFF_P
"). Frankenstein!\n", (off_p
)fr
->num
,
615 fr
->gapless_frames
> 0 ? (off_p
)fr
->gapless_frames
:
617 (off_p
)fr
->track_frames
);
620 halfspeed_prepare(fr
);
622 /* index the position */
623 fr
->input_offset
= framepos
;
625 /* Keep track of true frame positions in our frame index.
626 but only do so when we are sure that the frame number is accurate... */
627 if((fr
->state_flags
& FRAME_ACCURATE
) && FI_NEXT(fr
->index
, fr
->num
))
628 fi_add(&fr
->index
, framepos
);
631 if(fr
->silent_resync
> 0) --fr
->silent_resync
;
633 if(fr
->rd
->forget
!= NULL
) fr
->rd
->forget(fr
);
635 fr
->to_decode
= fr
->to_ignore
= TRUE
;
636 if(fr
->error_protection
) fr
->crc
= getbits(fr
, 16); /* skip crc */
639 Let's check for header change after deciding that the new one is good
640 and actually having read a frame.
642 header_change > 1: decoder structure has to be updated
643 Preserve header_change value from previous runs if it is serious.
644 If we still have a big change pending, it should be dealt with outside,
645 fr->header_change set to zero afterwards.
647 if(fr
->header_change
< 2)
649 fr
->header_change
= 2; /* output format change is possible... */
650 if(fr
->oldhead
) /* check a following header for change */
652 if(fr
->oldhead
== newhead
) fr
->header_change
= 0;
654 /* Headers that match in this test behave the same for the outside world.
655 namely: same decoding routines, same amount of decoded data. */
656 if(head_compatible(fr
->oldhead
, newhead
))
657 fr
->header_change
= 1;
660 fr
->state_flags
|= FRAME_FRANKENSTEIN
;
662 fprintf(stderr
, "\nWarning: Big change (MPEG version, layer, rate). Frankenstein stream?\n");
665 else if(fr
->firsthead
&& !head_compatible(fr
->firsthead
, newhead
))
667 fr
->state_flags
|= FRAME_FRANKENSTEIN
;
669 fprintf(stderr
, "\nWarning: Big change from first (MPEG version, layer, rate). Frankenstein stream?\n");
673 fr
->oldhead
= newhead
;
677 /* Also if we searched for valid data in vein, we can forget skipped data.
678 Otherwise, the feeder would hold every dead old byte in memory until the first valid frame! */
679 if(fr
->rd
->forget
!= NULL
) fr
->rd
->forget(fr
);
681 fr
->silent_resync
= 0;
682 if(fr
->err
== MPG123_OK
) fr
->err
= MPG123_ERR_READER
;
683 fr
->framesize
= oldsize
;
684 fr
->halfphase
= oldphase
;
685 /* That return code might be inherited from some feeder action, or reader error. */
691 * read ahead and find the next MPEG header, to guess framesize
692 * return value: success code
693 * PARSE_GOOD: found a valid frame size (stored in the handle).
694 * <0: error codes, possibly from feeder buffer (NEED_MORE)
695 * PARSE_BAD: cannot get the framesize for some reason and shall silentry try the next possible header (if this is no free format stream after all...)
697 static int guess_freeformat_framesize(mpg123_handle
*fr
, unsigned long oldhead
)
702 if(!(fr
->rdat
.flags
& (READER_SEEKABLE
|READER_BUFFERED
)))
704 if(NOQUIET
) error("Cannot look for freeformat frame size with non-seekable and non-buffered stream!");
708 if((ret
=fr
->rd
->head_read(fr
,&head
))<=0)
711 /* We are already 4 bytes into it */
712 for(i
=4;i
<MAXFRAMESIZE
+4;i
++)
714 if((ret
=fr
->rd
->head_shift(fr
,&head
))<=0) return ret
;
716 /* No head_check needed, the mask contains all relevant bits. */
717 if((head
& HDR_SAMEMASK
) == (oldhead
& HDR_SAMEMASK
))
719 fr
->rd
->back_bytes(fr
,i
+1);
721 return PARSE_GOOD
; /* Success! */
724 fr
->rd
->back_bytes(fr
,i
);
730 * decode a header and write the information
731 * into the frame structure
732 * Return values are compatible with those of read_frame, namely:
736 * You are required to do a head_check() before calling!
738 static int decode_header(mpg123_handle
*fr
,unsigned long newhead
, int *freeformat_count
)
740 #ifdef DEBUG /* Do not waste cycles checking the header twice all the time. */
741 if(!head_check(newhead
))
743 error1("trying to decode obviously invalid header 0x%08lx", newhead
);
746 /* For some reason, the layer and sampling freq settings used to be wrapped
747 in a weird conditional including MPG123_NO_RESYNC. What was I thinking?
748 This information has to be consistent. */
749 fr
->lay
= 4 - HDR_LAYER_VAL(newhead
);
751 if(HDR_VERSION_VAL(newhead
) & 0x2)
753 fr
->lsf
= (HDR_VERSION_VAL(newhead
) & 0x1) ? 0 : 1;
755 fr
->sampling_frequency
= HDR_SAMPLERATE_VAL(newhead
) + (fr
->lsf
*3);
761 fr
->sampling_frequency
= 6 + HDR_SAMPLERATE_VAL(newhead
);
765 /* seen a file where this varies (old lame tag without crc, track with crc) */
766 if((HDR_CRC_VAL(newhead
)^0x1) != fr
->error_protection
) debug("changed crc bit!");
768 fr
->error_protection
= HDR_CRC_VAL(newhead
)^0x1;
769 fr
->bitrate_index
= HDR_BITRATE_VAL(newhead
);
770 fr
->padding
= HDR_PADDING_VAL(newhead
);
771 fr
->extension
= HDR_PRIVATE_VAL(newhead
);
772 fr
->mode
= HDR_CHANNEL_VAL(newhead
);
773 fr
->mode_ext
= HDR_CHANEX_VAL(newhead
);
774 fr
->copyright
= HDR_COPYRIGHT_VAL(newhead
);
775 fr
->original
= HDR_ORIGINAL_VAL(newhead
);
776 fr
->emphasis
= HDR_EMPHASIS_VAL(newhead
);
777 fr
->freeformat
= !(newhead
& HDR_BITRATE
);
779 fr
->stereo
= (fr
->mode
== MPG_MD_MONO
) ? 1 : 2;
781 /* we can't use tabsel_123 for freeformat, so trying to guess framesize... */
784 /* when we first encounter the frame with freeformat, guess framesize */
785 if(fr
->freeformat_framesize
< 0)
788 *freeformat_count
+= 1;
789 if(*freeformat_count
> 5)
791 if(VERBOSE3
) error("You fooled me too often. Refusing to guess free format frame size _again_.");
794 ret
= guess_freeformat_framesize(fr
, newhead
);
795 if(ret
== PARSE_GOOD
)
797 fr
->freeformat_framesize
= fr
->framesize
- fr
->padding
;
799 fprintf(stderr
, "Note: free format frame size %li\n", fr
->freeformat_framesize
);
803 if(ret
== MPG123_NEED_MORE
)
804 debug("Need more data to guess free format frame size.");
806 error("Encountered free format header, but failed to guess frame size.");
811 /* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */
814 fr
->framesize
= fr
->freeformat_framesize
+ fr
->padding
;
823 fr
->do_layer
= do_layer1
;
826 fr
->framesize
= (long) tabsel_123
[fr
->lsf
][0][fr
->bitrate_index
] * 12000;
827 fr
->framesize
/= freqs
[fr
->sampling_frequency
];
828 fr
->framesize
= ((fr
->framesize
+fr
->padding
)<<2)-4;
835 fr
->do_layer
= do_layer2
;
838 debug2("bitrate index: %i (%i)", fr
->bitrate_index
, tabsel_123
[fr
->lsf
][1][fr
->bitrate_index
] );
839 fr
->framesize
= (long) tabsel_123
[fr
->lsf
][1][fr
->bitrate_index
] * 144000;
840 fr
->framesize
/= freqs
[fr
->sampling_frequency
];
841 fr
->framesize
+= fr
->padding
- 4;
847 fr
->spf
= fr
->lsf
? 576 : 1152; /* MPEG 2.5 implies LSF.*/
848 fr
->do_layer
= do_layer3
;
850 fr
->ssize
= (fr
->stereo
== 1) ? 9 : 17;
852 fr
->ssize
= (fr
->stereo
== 1) ? 17 : 32;
854 if(fr
->error_protection
)
859 fr
->framesize
= (long) tabsel_123
[fr
->lsf
][2][fr
->bitrate_index
] * 144000;
860 fr
->framesize
/= freqs
[fr
->sampling_frequency
]<<(fr
->lsf
);
861 fr
->framesize
= fr
->framesize
+ fr
->padding
- 4;
866 if(NOQUIET
) error1("Layer type %i not supported in this build!", fr
->lay
);
870 if (fr
->framesize
> MAXFRAMESIZE
)
872 if(NOQUIET
) error1("Frame size too big: %d", fr
->framesize
+4-fr
->padding
);
879 void set_pointer(mpg123_handle
*fr
, long backstep
)
881 fr
->wordpointer
= fr
->bsbuf
+ fr
->ssize
- backstep
;
883 memcpy(fr
->wordpointer
,fr
->bsbufold
+fr
->fsizeold
-backstep
,backstep
);
888 /********************************/
890 double compute_bpf(mpg123_handle
*fr
)
897 bpf
= tabsel_123
[fr
->lsf
][0][fr
->bitrate_index
];
898 bpf
*= 12000.0 * 4.0;
899 bpf
/= freqs
[fr
->sampling_frequency
] <<(fr
->lsf
);
903 bpf
= tabsel_123
[fr
->lsf
][fr
->lay
-1][fr
->bitrate_index
];
905 bpf
/= freqs
[fr
->sampling_frequency
] << (fr
->lsf
);
914 int attribute_align_arg
mpg123_spf(mpg123_handle
*mh
)
916 if(mh
== NULL
) return MPG123_ERR
;
918 return mh
->firsthead
? mh
->spf
: MPG123_ERR
;
921 double attribute_align_arg
mpg123_tpf(mpg123_handle
*fr
)
923 static int bs
[4] = { 0,384,1152,1152 };
925 if(fr
== NULL
|| !fr
->firsthead
) return MPG123_ERR
;
927 tpf
= (double) bs
[fr
->lay
];
928 tpf
/= freqs
[fr
->sampling_frequency
] << (fr
->lsf
);
932 int attribute_align_arg
mpg123_position(mpg123_handle
*fr
, off_t no
, off_t buffsize
,
933 off_t
*current_frame
, off_t
*frames_left
,
934 double *current_seconds
, double *seconds_left
)
941 if(!fr
|| !fr
->rd
) return MPG123_ERR
;
943 no
+= fr
->num
; /* no starts out as offset */
945 tpf
= mpg123_tpf(fr
);
946 if(buffsize
> 0 && fr
->af
.rate
> 0 && fr
->af
.channels
> 0)
948 dt
= (double) buffsize
/ fr
->af
.rate
/ fr
->af
.channels
;
949 if(fr
->af
.encoding
& MPG123_ENC_16
) dt
*= 0.5;
954 if((fr
->track_frames
!= 0) && (fr
->track_frames
>= fr
->num
)) left
= no
< fr
->track_frames
? fr
->track_frames
- no
: 0;
956 if(fr
->rdat
.filelen
>= 0)
959 off_t t
= fr
->rd
->tell(fr
);
960 bpf
= fr
->mean_framesize
? fr
->mean_framesize
: compute_bpf(fr
);
961 left
= (off_t
)((double)(fr
->rdat
.filelen
-t
)/bpf
);
962 /* no can be different for prophetic purposes, file pointer is always associated with fr->num! */
965 if(fr
->num
> no
) left
+= fr
->num
- no
;
968 if(left
>= (no
- fr
->num
)) left
-= no
- fr
->num
;
969 else left
= 0; /* uh, oh! */
972 /* I totally don't understand why we should re-estimate the given correct(?) value */
973 /* fr->num = (unsigned long)((double)t/bpf); */
976 /* beginning with 0 or 1?*/
977 curs
= (double) no
*tpf
-dt
;
978 lefts
= (double)left
*tpf
+dt
;
980 curs
= curs
< 0 ? 0.0 : curs
;
982 if(left
< 0 || lefts
< 0)
983 { /* That is the case for non-seekable streams. */
987 if(current_frame
!= NULL
) *current_frame
= cur
;
988 if(frames_left
!= NULL
) *frames_left
= left
;
989 if(current_seconds
!= NULL
) *current_seconds
= curs
;
990 if(seconds_left
!= NULL
) *seconds_left
= lefts
;
994 int get_songlen(mpg123_handle
*fr
,int no
)
1002 if(!fr
->rd
|| fr
->rdat
.filelen
< 0)
1004 no
= (int) ((double) fr
->rdat
.filelen
/ compute_bpf(fr
));
1007 tpf
= mpg123_tpf(fr
);
1008 return (int) (no
*tpf
);
1011 /* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */
1012 static int do_readahead(mpg123_handle
*fr
, unsigned long newhead
)
1014 unsigned long nexthead
= 0;
1019 if( ! (!fr
->firsthead
&& fr
->rdat
.flags
& (READER_SEEKABLE
|READER_BUFFERED
)) )
1022 start
= fr
->rd
->tell(fr
);
1024 debug2("doing ahead check with BPF %d at %"OFF_P
, fr
->framesize
+4, (off_p
)start
);
1025 /* step framesize bytes forward and read next possible header*/
1026 if((oret
=fr
->rd
->skip_bytes(fr
, fr
->framesize
))<0)
1028 if(oret
==READER_ERROR
&& NOQUIET
) error("cannot seek!");
1030 return oret
== MPG123_NEED_MORE
? PARSE_MORE
: PARSE_ERR
;
1033 /* Read header, seek back. */
1034 hd
= fr
->rd
->head_read(fr
,&nexthead
);
1035 if( fr
->rd
->back_bytes(fr
, fr
->rd
->tell(fr
)-start
) < 0 )
1037 if(NOQUIET
) error("Cannot seek back!");
1041 if(hd
== MPG123_NEED_MORE
) return PARSE_MORE
;
1043 debug1("After fetching next header, at %"OFF_P
, (off_p
)fr
->rd
->tell(fr
));
1046 if(NOQUIET
) warning("Cannot read next header, a one-frame stream? Duh...");
1050 debug2("does next header 0x%08lx match first 0x%08lx?", nexthead
, newhead
);
1051 if(!head_check(nexthead
) || !head_compatible(newhead
, nexthead
))
1053 debug("No, the header was not valid, start from beginning...");
1054 fr
->oldhead
= 0; /* start over */
1055 /* try next byte for valid header */
1056 if((ret
=fr
->rd
->back_bytes(fr
, 3))<0)
1058 if(NOQUIET
) error("Cannot seek 3 bytes back!");
1064 else return PARSE_GOOD
;
1067 static int handle_id3v2(mpg123_handle
*fr
, unsigned long newhead
)
1070 fr
->oldhead
= 0; /* Think about that. Used to be present only for skipping of junk, not resync-style wetwork. */
1071 ret
= parse_new_id3(fr
, newhead
);
1072 if (ret
< 0) return ret
;
1074 else if(ret
> 0){ debug("got ID3v2"); fr
->metaflags
|= MPG123_NEW_ID3
|MPG123_ID3
; }
1075 else debug("no useful ID3v2");
1080 /* Advance a byte in stream to get next possible header and forget
1081 buffered data if possible (for feed reader). */
1082 #define FORGET_INTERVAL 1024 /* Used by callers to set forget flag each <n> bytes. */
1083 static int forget_head_shift(mpg123_handle
*fr
, unsigned long *newheadp
, int forget
)
1086 if((ret
=fr
->rd
->head_shift(fr
,newheadp
))<=0) return ret
;
1087 /* Try to forget buffered data as early as possible to speed up parsing where
1088 new data needs to be added for resync (and things would be re-parsed again
1089 and again because of the start from beginning after hitting end). */
1090 if(forget
&& fr
->rd
->forget
!= NULL
)
1092 /* Ensure that the last 4 bytes stay in buffers for reading the header
1094 if(!fr
->rd
->back_bytes(fr
, 4))
1097 fr
->rd
->back_bytes(fr
, -4);
1100 return ret
; /* No surprise here, error already triggered early return. */
1103 /* watch out for junk/tags on beginning of stream by invalid header */
1104 static int skip_junk(mpg123_handle
*fr
, unsigned long *newheadp
, long *headcount
)
1107 int freeformat_count
= 0;
1109 unsigned long newhead
= *newheadp
;
1110 unsigned int forgetcount
= 0;
1111 /* check for id3v2; first three bytes (of 4) are "ID3" */
1112 if((newhead
& (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1114 return handle_id3v2(fr
, newhead
);
1116 else if(VERBOSE2
&& fr
->silent_resync
== 0) fprintf(stderr
,"Note: Junk at the beginning (0x%08lx)\n",newhead
);
1118 /* I even saw RIFF headers at the beginning of MPEG streams ;( */
1119 if(newhead
== ('R'<<24)+('I'<<16)+('F'<<8)+'F')
1121 if(VERBOSE2
&& fr
->silent_resync
== 0) fprintf(stderr
, "Note: Looks like a RIFF header.\n");
1123 if((ret
=fr
->rd
->head_read(fr
,&newhead
))<=0) return ret
;
1125 while(newhead
!= ('d'<<24)+('a'<<16)+('t'<<8)+'a')
1127 if(++forgetcount
> FORGET_INTERVAL
) forgetcount
= 0;
1128 if((ret
=forget_head_shift(fr
,&newhead
,!forgetcount
))<=0) return ret
;
1130 if((ret
=fr
->rd
->head_read(fr
,&newhead
))<=0) return ret
;
1132 if(VERBOSE2
&& fr
->silent_resync
== 0) fprintf(stderr
,"Note: Skipped RIFF header!\n");
1135 *newheadp
= newhead
;
1140 Unhandled junk... just continue search for a header, stepping in single bytes through next 64K.
1141 This is rather identical to the resync loop.
1143 debug("searching for header...");
1144 *newheadp
= 0; /* Invalidate the external value. */
1145 ret
= 0; /* We will check the value after the loop. */
1147 /* We prepare for at least the 64K bytes as usual, unless
1148 user explicitly wanted more (even infinity). Never less. */
1149 if(fr
->p
.resync_limit
< 0 || fr
->p
.resync_limit
> limit
)
1150 limit
= fr
->p
.resync_limit
;
1155 if(limit
>= 0 && *headcount
>= limit
) break;
1157 if(++forgetcount
> FORGET_INTERVAL
) forgetcount
= 0;
1158 if((ret
=forget_head_shift(fr
, &newhead
, !forgetcount
))<=0) return ret
;
1160 if(head_check(newhead
) && (ret
=decode_header(fr
, newhead
, &freeformat_count
))) break;
1162 if(ret
<0) return ret
;
1164 if(limit
>= 0 && *headcount
>= limit
)
1166 if(NOQUIET
) error1("Giving up searching valid MPEG header after %li bytes of junk.", *headcount
);
1169 else debug1("hopefully found one at %"OFF_P
, (off_p
)fr
->rd
->tell(fr
));
1171 /* If the new header ist good, it is already decoded. */
1172 *newheadp
= newhead
;
1176 /* The newhead is bad, so let's check if it is something special, otherwise just resync. */
1177 static int wetwork(mpg123_handle
*fr
, unsigned long *newheadp
)
1179 int ret
= PARSE_ERR
;
1180 unsigned long newhead
= *newheadp
;
1183 /* Classic ID3 tags. Read, then start parsing again. */
1184 if((newhead
& 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8))
1186 fr
->id3buf
[0] = (unsigned char) ((newhead
>> 24) & 0xff);
1187 fr
->id3buf
[1] = (unsigned char) ((newhead
>> 16) & 0xff);
1188 fr
->id3buf
[2] = (unsigned char) ((newhead
>> 8) & 0xff);
1189 fr
->id3buf
[3] = (unsigned char) ( newhead
& 0xff);
1191 if((ret
=fr
->rd
->fullread(fr
,fr
->id3buf
+4,124)) < 0) return ret
;
1193 fr
->metaflags
|= MPG123_NEW_ID3
|MPG123_ID3
;
1194 fr
->rdat
.flags
|= READER_ID3TAG
; /* that marks id3v1 */
1195 if(VERBOSE3
) fprintf(stderr
,"Note: Skipped ID3v1 tag.\n");
1199 /* This is similar to initial junk skipping code... */
1200 /* Check for id3v2; first three bytes (of 4) are "ID3" */
1201 if((newhead
& (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1203 return handle_id3v2(fr
, newhead
);
1205 else if(NOQUIET
&& fr
->silent_resync
== 0)
1207 fprintf(stderr
,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset %"OFF_P
".\n",
1208 newhead
, (off_p
)fr
->rd
->tell(fr
)-4);
1211 /* Now we got something bad at hand, try to recover. */
1213 if(NOQUIET
&& (newhead
& 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr
,"Note: Could be a BMP album art.\n");
1215 if( !(fr
->p
.flags
& MPG123_NO_RESYNC
) )
1218 long limit
= fr
->p
.resync_limit
;
1219 unsigned int forgetcount
= 0;
1221 /* If a resync is needed the bitreservoir of previous frames is no longer valid */
1222 fr
->bitreservoir
= 0;
1224 if(NOQUIET
&& fr
->silent_resync
== 0) fprintf(stderr
, "Note: Trying to resync...\n");
1226 do /* ... shift the header with additional single bytes until be found something that could be a header. */
1229 if(limit
>= 0 && try >= limit
) break;
1231 if(++forgetcount
> FORGET_INTERVAL
) forgetcount
= 0;
1232 if((ret
=forget_head_shift(fr
,&newhead
,!forgetcount
)) <= 0)
1234 *newheadp
= newhead
;
1235 if(NOQUIET
) fprintf (stderr
, "Note: Hit end of (available) data during resync.\n");
1237 return ret
? ret
: PARSE_END
;
1239 if(VERBOSE3
) debug3("resync try %li at %"OFF_P
", got newhead 0x%08lx", try, (off_p
)fr
->rd
->tell(fr
), newhead
);
1240 } while(!head_check(newhead
));
1242 *newheadp
= newhead
;
1243 if(NOQUIET
&& fr
->silent_resync
== 0) fprintf (stderr
, "Note: Skipped %li bytes in input.\n", try);
1245 /* Now we either got something that could be a header, or we gave up. */
1246 if(limit
>= 0 && try >= limit
)
1249 error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try);
1251 fr
->err
= MPG123_RESYNC_FAIL
;
1256 debug1("Found possibly valid header 0x%lx... unsetting oldhead to reinit stream.", newhead
);
1258 return PARSE_RESYNC
;
1263 if(NOQUIET
) error("not attempting to resync...");
1265 fr
->err
= MPG123_OUT_OF_SYNC
;
1268 /* Control never goes here... we return before that. */