Coverage Report

Created: 2025-07-18 06:28

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