Coverage Report

Created: 2024-09-21 06:25

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