Subversion Repositories Kolibri OS

Rev

Rev 1905 | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

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