Coverage Report

Created: 2026-02-14 06:44

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mpg123/src/libmpg123/parse.c
Line
Count
Source
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
305
#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.03M
{
82
1.03M
  return freqs[fr->hdr.sampling_frequency];
83
1.03M
}
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
113M
{
88
113M
  if
89
113M
  (
90
113M
    ((head & HDR_SYNC) != HDR_SYNC)
91
5.31M
    ||
92
    /* layer: 01,10,11 is 1,2,3; 00 is reserved */
93
5.31M
    (!(HDR_LAYER_VAL(head)))
94
5.31M
    ||
95
    /* 1111 means bad bitrate */
96
5.31M
    (HDR_BITRATE_VAL(head) == 0xf)
97
4.05M
    ||
98
    /* sampling freq: 11 is reserved */
99
4.05M
    (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
113M
  )
102
109M
  {
103
109M
    return FALSE;
104
109M
  }
105
  /* if no check failed, the header is valid (hopefully)*/
106
3.98M
  else
107
3.98M
  {
108
3.98M
    return TRUE;
109
3.98M
  }
110
113M
}
111
112
/* This is moderately sized buffers. Int offset is enough. */
113
static unsigned long bit_read_long(unsigned char *buf, int *offset)
114
916
{
115
916
  unsigned long val =  /* 32 bit value */
116
916
    (((unsigned long) buf[*offset])   << 24)
117
916
  | (((unsigned long) buf[*offset+1]) << 16)
118
916
  | (((unsigned long) buf[*offset+2]) << 8)
119
916
  |  ((unsigned long) buf[*offset+3]);
120
916
  *offset += 4;
121
916
  return val;
122
916
}
123
124
static unsigned short bit_read_short(unsigned char *buf, int *offset)
125
422
{
126
422
  unsigned short val = /* 16 bit value */
127
422
    (((unsigned short) buf[*offset]  ) << 8)
128
422
  |  ((unsigned short) buf[*offset+1]);
129
422
  *offset += 2;
130
422
  return val;
131
422
}
132
133
static int check_lame_tag(mpg123_handle *fr)
134
1.53k
{
135
1.53k
  int i;
136
1.53k
  unsigned long xing_flags;
137
1.53k
  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.53k
  int lame_offset = (fr->stereo == 2)
145
1.53k
  ? (fr->hdr.lsf ? 17 : 32)
146
1.53k
  : (fr->hdr.lsf ? 9  : 17);
147
148
1.53k
  if(fr->p.flags & MPG123_IGNORE_INFOFRAME) goto check_lame_tag_no;
149
150
1.53k
  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.53k
  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.34k
  for(i=2; i < lame_offset; ++i) if(fr->bsbuf[i] != 0) goto check_lame_tag_no;
162
163
513
  debug("possibly...");
164
513
  if
165
513
  (
166
513
       (fr->bsbuf[lame_offset]   == 'I')
167
479
    && (fr->bsbuf[lame_offset+1] == 'n')
168
466
    && (fr->bsbuf[lame_offset+2] == 'f')
169
460
    && (fr->bsbuf[lame_offset+3] == 'o')
170
513
  )
171
453
  {
172
    /* We still have to see what there is */
173
453
  }
174
60
  else if
175
60
  (
176
60
       (fr->bsbuf[lame_offset]   == 'X')
177
21
    && (fr->bsbuf[lame_offset+1] == 'i')
178
19
    && (fr->bsbuf[lame_offset+2] == 'n')
179
12
    && (fr->bsbuf[lame_offset+3] == 'g')
180
60
  )
181
4
  {
182
4
    fr->vbr = MPG123_VBR; /* Xing header means always VBR */
183
4
  }
184
56
  else goto check_lame_tag_no;
185
186
  /* we have one of these headers... */
187
457
  if(VERBOSE2) fprintf(stderr, "Note: Xing/Lame/Info header detected\n");
188
457
  lame_offset += 4; 
189
457
  xing_flags = bit_read_long(fr->bsbuf, &lame_offset);
190
457
  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
960
  #define check_bytes_left(n) if(fr->hdr.framesize < lame_offset+n) \
195
960
    goto check_lame_tag_yes
196
457
  if(xing_flags & 1) /* total bitstream frames */
197
307
  {
198
307
    check_bytes_left(4); long_tmp = bit_read_long(fr->bsbuf, &lame_offset);
199
305
    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
305
    else
205
305
    {
206
      /* Check for endless stream, but: TRACK_MAX_FRAMES sensible at all? */
207
305
      fr->track_frames = long_tmp > TRACK_MAX_FRAMES ? 0 : (int64_t) long_tmp;
208
305
#ifdef GAPLESS
209
      /* All or nothing: Only if encoder delay/padding is known, we'll cut
210
         samples for gapless. */
211
305
      if(fr->p.flags & MPG123_GAPLESS)
212
305
      INT123_frame_gapless_init(fr, fr->track_frames, 0, 0);
213
305
#endif
214
305
      if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu frames\n", long_tmp);
215
305
    }
216
305
  }
217
455
  if(xing_flags & 0x2) /* total bitstream bytes */
218
237
  {
219
237
    check_bytes_left(4); long_tmp = bit_read_long(fr->bsbuf, &lame_offset);
220
105
    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
105
    else
226
105
    {
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
105
      if(fr->rdat.filelen < 1)
232
105
      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
105
      if(VERBOSE3) fprintf(stderr, "Note: Xing: %lu bytes\n", long_tmp);
252
105
    }
253
105
  }
254
323
  if(xing_flags & 0x4) /* TOC */
255
112
  {
256
112
    check_bytes_left(100);
257
44
    INT123_frame_fill_toc(fr, fr->bsbuf+lame_offset);
258
44
    lame_offset += 100;
259
44
  }
260
255
  if(xing_flags & 0x8) /* VBR quality */
261
65
  {
262
65
    check_bytes_left(4); long_tmp = bit_read_long(fr->bsbuf, &lame_offset);
263
49
    if(VERBOSE3) fprintf(stderr, "Note: Xing: quality = %lu\n", long_tmp);
264
49
  }
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
239
  check_bytes_left(24); /* I'm interested in 24 B of extra info. */
276
224
  if(fr->bsbuf[lame_offset] != 0)
277
211
  {
278
211
    unsigned char lame_vbr;
279
211
    float replay_gain[2] = {0,0};
280
211
    float peak = 0;
281
211
    float gain_offset = 0; /* going to be +6 for old lame that used 83dB */
282
211
    char nb[10];
283
211
    int64_t pad_in;
284
211
    int64_t pad_out;
285
211
    memcpy(nb, fr->bsbuf+lame_offset, 9);
286
211
    nb[9] = 0;
287
211
    if(VERBOSE3) fprintf(stderr, "Note: Info: Encoder: %s\n", nb);
288
211
    if(!strncmp("LAME", nb, 4))
289
30
    {
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
30
      unsigned int major, minor;
294
30
      char rest[6];
295
30
      rest[0] = 0;
296
30
      if(sscanf(nb+4, "%u.%u%s", &major, &minor, rest) >= 2)
297
27
      {
298
27
        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
27
        if(major < 3 || (major == 3 && minor < 95))
303
10
        {
304
10
          gain_offset = 6;
305
10
          if(VERBOSE3) fprintf(stderr
306
0
          , "Note: Info: Old LAME detected, using ReplayGain preamp of %f dB.\n"
307
0
          , gain_offset);
308
10
        }
309
27
      }
310
3
      else if(VERBOSE3) fprintf(stderr
311
0
      , "Note: Info: Cannot determine LAME version.\n");
312
30
    }
313
211
    lame_offset += 9; /* 9 in */ 
314
315
    /* The 4 big bits are tag revision, the small bits vbr method. */
316
211
    lame_vbr = fr->bsbuf[lame_offset] & 15;
317
211
    lame_offset += 1; /* 10 in */
318
211
    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
211
    switch(lame_vbr)
324
211
    {
325
      /* from rev1 proposal... not sure if all good in practice */
326
16
      case 1:
327
26
      case 8: fr->vbr = MPG123_CBR; break;
328
23
      case 2:
329
51
      case 9: fr->vbr = MPG123_ABR; break;
330
134
      default: fr->vbr = MPG123_VBR; /* 00==unknown is taken as VBR */
331
211
    }
332
211
    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
211
    if
338
211
    (
339
211
         (fr->bsbuf[lame_offset]   != 0)
340
72
      || (fr->bsbuf[lame_offset+1] != 0)
341
54
      || (fr->bsbuf[lame_offset+2] != 0)
342
41
      || (fr->bsbuf[lame_offset+3] != 0)
343
211
    )
344
187
    {
345
187
      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
187
    }
351
211
    if(VERBOSE3) fprintf(stderr
352
0
    , "Note: Info: peak = %f (I won't use this)\n", peak);
353
211
    peak = 0; /* until better times arrived */
354
211
    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
633
    for(i =0; i < 2; ++i)
363
422
    {
364
422
      unsigned char gt     =  fr->bsbuf[lame_offset] >> 5;
365
422
      unsigned char origin = (fr->bsbuf[lame_offset] >> 2) & 0x7;
366
422
      float factor         = (fr->bsbuf[lame_offset] & 0x2) ? -0.1f : 0.1f;
367
422
      unsigned short gain  = bit_read_short(fr->bsbuf, &lame_offset) & 0x1ff; /* 19 in (2 cycles) */
368
422
      if(origin == 0 || gt < 1 || gt > 2) continue;
369
370
125
      --gt;
371
125
      replay_gain[gt] = factor * (float) gain;
372
      /* Apply gain offset for automatic origin. */
373
125
      if(origin == 3) replay_gain[gt] += gain_offset;
374
125
    }
375
211
    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
633
    for(i=0; i < 2; ++i)
383
422
    {
384
422
      if(fr->rva.level[i] <= 0)
385
415
      {
386
415
        fr->rva.peak[i] = 0; /* TODO: use parsed peak? */
387
415
        fr->rva.gain[i] = replay_gain[i];
388
415
        fr->rva.level[i] = 0;
389
415
      }
390
422
    }
391
392
211
    lame_offset += 1; /* 20 in, skipping encoding flags byte */
393
394
    /* ABR rate */
395
211
    if(fr->vbr == MPG123_ABR)
396
51
    {
397
51
      fr->abr_rate = fr->bsbuf[lame_offset];
398
51
      if(VERBOSE3) fprintf(stderr, "Note: Info: ABR rate = %u\n"
399
0
      , fr->abr_rate);
400
51
    }
401
211
    lame_offset += 1; /* 21 in */
402
  
403
    /* Encoder delay and padding, two 12 bit values
404
       ... lame does write them from int. */
405
211
    pad_in  = ( (((int) fr->bsbuf[lame_offset])   << 4)
406
211
              | (((int) fr->bsbuf[lame_offset+1]) >> 4) );
407
211
    pad_out = ( (((int) fr->bsbuf[lame_offset+1]) << 8)
408
211
              |  ((int) fr->bsbuf[lame_offset+2])       ) & 0xfff;
409
211
    lame_offset += 3; /* 24 in */
410
211
    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
211
    fr->enc_delay   = (int)pad_in;
414
211
    fr->enc_padding = (int)pad_out;
415
211
    #ifdef GAPLESS
416
211
    if(fr->p.flags & MPG123_GAPLESS)
417
211
    INT123_frame_gapless_init(fr, fr->track_frames, pad_in, pad_out);
418
211
    #endif
419
    /* final: 24 B LAME data */
420
211
  }
421
422
457
check_lame_tag_yes:
423
  /* switch buffer back ... */
424
457
  fr->bsbuf = fr->bsspace[fr->bsnum]+512;
425
457
  fr->bsnum = (fr->bsnum + 1) & 1;
426
457
  return 1;
427
1.08k
check_lame_tag_no:
428
1.08k
  return 0;
429
224
}
430
431
/* Just tell if the header is some mono. */
432
static int header_mono(unsigned long newhead)
433
518k
{
434
518k
  return HDR_CHANNEL_VAL(newhead) == MPG_MD_MONO ? TRUE : FALSE;
435
518k
}
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
675k
{
440
675k
  return ( (fred & HDR_CMPMASK) == (bret & HDR_CMPMASK)
441
259k
    &&       header_mono(fred) == header_mono(bret)    );
442
675k
}
443
444
static void halfspeed_prepare(mpg123_handle *fr)
445
1.08M
{
446
  /* save for repetition */
447
1.08M
  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.08M
}
453
454
/* If this returns 1, the next frame is the repetition. */
455
static int halfspeed_do(mpg123_handle *fr)
456
2.22M
{
457
  /* Speed-down hack: Play it again, Sam (the frame, I mean). */
458
2.22M
  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.22M
  return 0;
476
2.22M
}
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
3.95M
#define JUMP_CONCLUSION(ret) \
484
3.95M
{ \
485
3.95M
if(ret < 0){ debug1("%s", ret == MPG123_NEED_MORE ? "need more" : "read error"); goto read_frame_bad; } \
486
3.95M
else if(ret == PARSE_AGAIN) goto read_again; \
487
3.73M
else if(ret == PARSE_RESYNC) goto init_resync; \
488
3.66M
else if(ret == PARSE_END){ ret=0; goto read_frame_bad; } \
489
3.95M
}
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.22M
{
497
  /* TODO: rework this thing */
498
2.22M
  int freeformat_count = 0;
499
2.22M
  unsigned long newhead;
500
   // Start with current frame header state as copy for roll-back ability.
501
2.22M
  struct frame_header nhdr = fr->hdr;
502
2.22M
  int64_t framepos;
503
2.22M
  int ret;
504
  /* stuff that needs resetting if complete frame reading fails */
505
2.22M
  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.22M
  long headcount = 0;
511
512
2.22M
  fr->fsizeold=fr->hdr.framesize;       /* for Layer3 */
513
514
2.22M
  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.22M
  fr->to_decode = fr->to_ignore = FALSE;
519
520
2.22M
  if( fr->p.flags & MPG123_NO_FRANKENSTEIN &&
521
0
    ( (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.28M
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.28M
  if(fr->rd->forget != NULL) fr->rd->forget(fr);
537
538
2.28M
  debug2("trying to get frame %"PRIi64" at %"PRIi64, fr->num+1, fr->rd->tell(fr));
539
2.28M
  if((ret = fr->rd->head_read(fr,&newhead)) <= 0){ debug1("need more? (%i)", ret); goto read_frame_bad;}
540
541
2.50M
init_resync:
542
543
2.50M
#ifdef SKIP_JUNK
544
2.50M
  if(!fr->firsthead && !head_check(newhead))
545
223k
  {
546
223k
    ret = skip_junk(fr, &newhead, &headcount, &nhdr);
547
223k
    JUMP_CONCLUSION(ret);
548
125k
  }
549
2.41M
#endif
550
551
2.41M
  ret = head_check(newhead);
552
2.41M
  if(ret) ret = decode_header(fr, &nhdr, newhead, &freeformat_count);
553
554
2.41M
  JUMP_CONCLUSION(ret); /* That only continues for ret == PARSE_BAD or PARSE_GOOD. */
555
2.40M
  if(ret == PARSE_BAD)
556
1.17M
  { /* Header was not good. */
557
1.17M
    ret = wetwork(fr, &newhead); /* Messy stuff, handle junk, resync ... */
558
1.17M
    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.23M
  if(!fr->firsthead)
564
138k
  {
565
138k
    ret = fr->p.flags & MPG123_NO_READAHEAD
566
138k
    ?  PARSE_GOOD
567
138k
    : 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
138k
    if(ret < 0) fr->rd->back_bytes(fr, 4);
570
138k
    JUMP_CONCLUSION(ret);
571
2.71k
  }
572
573
  /* Now we should have our valid header and proceed to reading the frame. */
574
575
1.09M
  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.09M
  framepos = fr->rd->tell(fr) - 4;
587
  /* flip/init buffer for Layer 3 */
588
1.09M
  {
589
1.09M
    unsigned char *newbuf = fr->bsspace[fr->bsnum]+512;
590
    /* read main data into memory */
591
1.09M
    debug2("read frame body of %i at %"PRIi64, nhdr.framesize, framepos+4);
592
1.09M
    if((ret=fr->rd->read_frame_body(fr,newbuf,nhdr.framesize))<0)
593
7.09k
    {
594
      /* if failed: flip back */
595
7.09k
      debug1("%s", ret == MPG123_NEED_MORE ? "need more" : "read error");
596
7.09k
      goto read_frame_bad;
597
7.09k
    }
598
1.08M
    fr->bsbufold = fr->bsbuf;
599
1.08M
    fr->bsbuf = newbuf;
600
1.08M
  }
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.08M
  apply_header(fr, &nhdr);
606
607
1.08M
  if(!fr->firsthead)
608
2.71k
  {
609
2.71k
    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
2.71k
    if(fr->num < 0)
614
2.71k
    {
615
2.71k
      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
2.71k
      if(fr->hdr.lay == 3 && check_lame_tag(fr) == 1)
619
457
      { /* ...in practice, Xing/LAME tags are layer 3 only. */
620
457
        if(fr->rd->forget != NULL) fr->rd->forget(fr);
621
622
457
        fr->oldhead = 0;
623
457
        goto read_again;
624
457
      }
625
      /* now adjust volume */
626
2.26k
      INT123_do_rva(fr);
627
2.26k
    }
628
629
2.26k
    debug2("fr->firsthead: %08lx, audio_start: %li", fr->firsthead, (long int)fr->audio_start);
630
2.26k
  }
631
632
1.08M
  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.08M
  if(++fr->mean_frames != 0)
639
1.08M
  {
640
1.08M
    fr->mean_framesize = ((fr->mean_frames-1)*fr->mean_framesize+INT123_compute_bpf(fr)) / fr->mean_frames ;
641
1.08M
  }
642
1.08M
  ++fr->num; /* 0 for first frame! */
643
1.08M
  debug4("Frame %"PRIi64" %08lx %i, next filepos=%"PRIi64, fr->num, newhead, fr->hdr.framesize, fr->rd->tell(fr));
644
1.08M
  if(!(fr->state_flags & FRAME_FRANKENSTEIN) && (
645
15.3k
    (fr->track_frames > 0 && fr->num >= fr->track_frames)
646
15.3k
#ifdef GAPLESS
647
15.3k
    || (fr->gapless_frames > 0 && fr->num >= fr->gapless_frames)
648
15.3k
#endif
649
15.3k
  ))
650
1
  {
651
1
    fr->state_flags |= FRAME_FRANKENSTEIN;
652
1
    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
1
  }
660
661
1.08M
  halfspeed_prepare(fr);
662
663
  /* index the position */
664
1.08M
  fr->input_offset = framepos;
665
1.08M
#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.08M
  if((fr->state_flags & FRAME_ACCURATE) && FI_NEXT(fr->index, fr->num))
669
348k
  INT123_fi_add(&fr->index, framepos);
670
1.08M
#endif
671
672
1.08M
  if(fr->silent_resync > 0) --fr->silent_resync;
673
674
1.08M
  if(fr->rd->forget != NULL) fr->rd->forget(fr);
675
676
1.08M
  fr->to_decode = fr->to_ignore = TRUE;
677
1.08M
  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.08M
  if(fr->header_change < 2)
689
1.08M
  {
690
1.08M
    fr->header_change = 2; /* output format change is possible... */
691
1.08M
    if(fr->oldhead)        /* check a following header for change */
692
740k
    {
693
740k
      if(fr->oldhead == newhead) fr->header_change = 0;
694
323k
      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
323k
      if(head_compatible(fr->oldhead, newhead))
698
153k
      fr->header_change = 1;
699
169k
      else
700
169k
      {
701
169k
        fr->state_flags |= FRAME_FRANKENSTEIN;
702
169k
        if(NOQUIET)
703
0
        fprintf(stderr, "\nWarning: Big change (MPEG version, layer, rate). Frankenstein stream?\n");
704
169k
      }
705
740k
    }
706
348k
    else if(fr->firsthead && !head_compatible(fr->firsthead, newhead))
707
273k
    {
708
273k
      fr->state_flags |= FRAME_FRANKENSTEIN;
709
273k
      if(NOQUIET)
710
0
      fprintf(stderr, "\nWarning: Big change from first (MPEG version, layer, rate). Frankenstein stream?\n");
711
273k
    }
712
1.08M
  }
713
714
1.08M
  fr->oldhead = newhead;
715
716
1.08M
  return 1;
717
1.13M
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.13M
  if(fr->rd->forget != NULL) fr->rd->forget(fr);
721
722
1.13M
  fr->silent_resync = 0;
723
1.13M
  if(fr->err == MPG123_OK) fr->err = MPG123_ERR_READER;
724
1.13M
  fr->halfphase = oldphase;
725
  /* That return code might be inherited from some feeder action, or reader error. */
726
1.13M
  return ret;
727
1.08M
}
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
7.57k
{
739
7.57k
  int i;
740
7.57k
  int ret;
741
7.57k
  unsigned long head;
742
7.57k
  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
7.57k
  if((ret=fr->rd->head_read(fr,&head))<=0)
749
479
  return ret;
750
751
  /* We are already 4 bytes into it */
752
3.35M
  for(i=4;i<MAXFRAMESIZE+4;i++)
753
3.35M
  {
754
3.35M
    if((ret=fr->rd->head_shift(fr,&head))<=0) return ret;
755
756
    /* No head_check needed, the mask contains all relevant bits. */
757
3.35M
    if((head & HDR_SAMEMASK) == (oldhead & HDR_SAMEMASK))
758
4.55k
    {
759
4.55k
      fr->rd->back_bytes(fr,i+1);
760
4.55k
      *framesize = i-3;
761
4.55k
      return PARSE_GOOD; /* Success! */
762
4.55k
    }
763
3.35M
  }
764
447
  fr->rd->back_bytes(fr,i);
765
447
  return PARSE_BAD;
766
7.09k
}
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
2.17M
{
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
2.17M
  fh->lay = 4 - HDR_LAYER_VAL(newhead);
795
796
2.17M
  if(HDR_VERSION_VAL(newhead) & 0x2)
797
1.21M
  {
798
1.21M
    fh->lsf = (HDR_VERSION_VAL(newhead) & 0x1) ? 0 : 1;
799
1.21M
    fh->mpeg25 = 0;
800
1.21M
    fh->sampling_frequency = HDR_SAMPLERATE_VAL(newhead) + (fh->lsf*3);
801
1.21M
  }
802
956k
  else
803
956k
  {
804
956k
    fh->lsf = 1;
805
956k
    fh->mpeg25 = 1;
806
956k
    fh->sampling_frequency = 6 + HDR_SAMPLERATE_VAL(newhead);
807
956k
  }
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
2.17M
  fh->error_protection = HDR_CRC_VAL(newhead)^0x1;
814
2.17M
  fh->bitrate_index    = HDR_BITRATE_VAL(newhead);
815
2.17M
  fh->padding          = HDR_PADDING_VAL(newhead);
816
2.17M
  fh->extension        = HDR_PRIVATE_VAL(newhead);
817
2.17M
  fh->mode             = HDR_CHANNEL_VAL(newhead);
818
2.17M
  fh->mode_ext         = HDR_CHANEX_VAL(newhead);
819
2.17M
  fh->copyright        = HDR_COPYRIGHT_VAL(newhead);
820
2.17M
  fh->original         = HDR_ORIGINAL_VAL(newhead);
821
2.17M
  fh->emphasis         = HDR_EMPHASIS_VAL(newhead);
822
2.17M
  fh->freeformat       = !(newhead & HDR_BITRATE);
823
824
825
  /* we can't use tabsel_123 for freeformat, so trying to guess framesize... */
826
2.17M
  if(fh->freeformat)
827
1.90M
  {
828
    /* when we first encounter the frame with freeformat, guess framesize */
829
1.90M
    if(fh->freeformat_framesize < 0)
830
193k
    {
831
193k
      int ret;
832
193k
      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
193k
      *freeformat_count += 1;
839
193k
      if(*freeformat_count > 5)
840
186k
      {
841
186k
        if(VERBOSE3) error("You fooled me too often. Refusing to guess free format frame size _again_.");
842
186k
        return PARSE_BAD;
843
186k
      }
844
7.57k
      ret = guess_freeformat_framesize(fr, newhead, &(fh->framesize));
845
7.57k
      if(ret == PARSE_GOOD)
846
4.55k
      {
847
4.55k
        fh->freeformat_framesize = fh->framesize - fh->padding;
848
4.55k
        if(VERBOSE2)
849
0
        fprintf(stderr, "Note: free format frame size %i\n", fh->freeformat_framesize);
850
4.55k
      }
851
3.02k
      else
852
3.02k
      {
853
3.02k
        if(ret == MPG123_NEED_MORE)
854
3.02k
        debug("Need more data to guess free format frame size.");
855
447
        else if(VERBOSE3)
856
0
        error("Encountered free format header, but failed to guess frame size.");
857
858
3.02k
        return ret;
859
3.02k
      }
860
7.57k
    }
861
    /* freeformat should be CBR, so the same framesize can be used at the 2nd reading or later */
862
1.70M
    else
863
1.70M
    {
864
1.70M
      fh->framesize = fh->freeformat_framesize + fh->padding;
865
1.70M
    }
866
1.90M
  }
867
1.98M
  switch(fh->lay)
868
1.98M
  {
869
0
#ifndef NO_LAYER1
870
473k
    case 1:
871
473k
      if(!fh->freeformat)
872
139k
      {
873
139k
        long fs = (long) tabsel_123[fh->lsf][0][fh->bitrate_index] * 12000;
874
139k
        fs /= freqs[fh->sampling_frequency];
875
139k
        fs = ((fs+fh->padding)<<2)-4;
876
139k
        fh->framesize = (int)fs;
877
139k
      }
878
473k
    break;
879
0
#endif
880
0
#ifndef NO_LAYER2
881
752k
    case 2:
882
752k
      if(!fh->freeformat)
883
88.0k
      {
884
88.0k
        debug2("bitrate index: %i (%i)", fh->bitrate_index, tabsel_123[fh->lsf][1][fh->bitrate_index] );
885
88.0k
        long fs = (long) tabsel_123[fh->lsf][1][fh->bitrate_index] * 144000;
886
88.0k
        fs /= freqs[fh->sampling_frequency];
887
88.0k
        fs += fh->padding - 4;
888
88.0k
        fh->framesize = (int)fs;
889
88.0k
      }
890
752k
    break;
891
0
#endif
892
0
#ifndef NO_LAYER3
893
754k
    case 3:
894
754k
      if(fh->lsf)
895
675k
      fh->ssize = (fh->mode == MPG_MD_MONO) ? 9 : 17;
896
78.6k
      else
897
78.6k
      fh->ssize = (fh->mode == MPG_MD_MONO) ? 17 : 32;
898
899
754k
      if(fh->error_protection)
900
42.6k
      fh->ssize += 2;
901
902
754k
      if(!fh->freeformat)
903
41.9k
      {
904
41.9k
        long fs = (long) tabsel_123[fh->lsf][2][fh->bitrate_index] * 144000;
905
41.9k
        fs /= freqs[fh->sampling_frequency]<<(fh->lsf);
906
41.9k
        fs += fh->padding - 4;
907
41.9k
        fh->framesize = fs;
908
41.9k
      }
909
754k
      if(fh->framesize < fh->ssize)
910
623k
      {
911
623k
        if(NOQUIET)
912
623k
          error2( "Frame smaller than mandatory side info (%i < %i)!"
913
623k
          , fh->framesize, fh->ssize );
914
623k
        return PARSE_BAD;
915
623k
      }
916
131k
    break;
917
131k
#endif 
918
131k
    default:
919
0
      if(NOQUIET) error1("Layer type %i not supported in this build!", fh->lay); 
920
921
0
      return PARSE_BAD;
922
1.98M
  }
923
1.35M
  if (fh->framesize > MAXFRAMESIZE)
924
222
  {
925
222
    if(NOQUIET) error1("Frame size too big: %d", fh->framesize+4-fh->padding);
926
927
222
    return PARSE_BAD;
928
222
  }
929
1.35M
  return PARSE_GOOD;
930
1.35M
}
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.08M
{
936
  // copy the whole struct, do some postprocessing
937
1.08M
  fr->hdr = *hdr;
938
1.08M
  fr->stereo = (fr->hdr.mode == MPG_MD_MONO) ? 1 : 2;
939
1.08M
  switch(fr->hdr.lay)
940
1.08M
  {
941
0
#ifndef NO_LAYER1
942
348k
    case 1:
943
348k
      fr->spf = 384;
944
348k
      fr->do_layer = INT123_do_layer1;
945
348k
    break;
946
0
#endif
947
0
#ifndef NO_LAYER2
948
649k
    case 2:
949
649k
      fr->spf = 1152;
950
649k
      fr->do_layer = INT123_do_layer2;
951
649k
    break;
952
0
#endif
953
0
#ifndef NO_LAYER3
954
91.1k
    case 3:
955
91.1k
      fr->spf = fr->hdr.lsf ? 576 : 1152; /* MPEG 2.5 implies LSF.*/
956
91.1k
      fr->do_layer = INT123_do_layer3;
957
91.1k
#endif 
958
91.1k
    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.08M
  }
964
1.08M
}
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.17M
{
977
1.17M
  fr->bitindex = 0;
978
1.17M
  if(fr->hdr.lay == 3)
979
177k
  {
980
177k
    if(part2)
981
87.1k
    {
982
87.1k
      fr->wordpointer = fr->bsbuf + fr->hdr.ssize - backstep;
983
87.1k
      if(backstep)
984
2.04k
        memcpy( fr->wordpointer, fr->bsbufold+fr->fsizeold-backstep
985
2.04k
        , backstep );
986
87.1k
      fr->bits_avail = (long)(fr->hdr.framesize - fr->hdr.ssize + backstep)*8;
987
87.1k
    }
988
90.7k
    else
989
90.7k
    {
990
90.7k
      fr->wordpointer = fr->bsbuf;
991
90.7k
      fr->bits_avail  = fr->hdr.ssize*8;
992
90.7k
    }
993
177k
  }
994
998k
  else
995
998k
  {
996
998k
    fr->wordpointer = fr->bsbuf;
997
998k
    fr->bits_avail  = fr->hdr.framesize*8;
998
998k
  }
999
1.17M
}
1000
1001
/********************************/
1002
1003
double INT123_compute_bpf(mpg123_handle *fr)
1004
1.08M
{
1005
1.08M
  return (fr->hdr.framesize > 0) ? fr->hdr.framesize + 4.0 : 1.0;
1006
1.08M
}
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
138k
{
1091
138k
  unsigned long nexthead = 0;
1092
138k
  int hd = 0;
1093
138k
  int64_t start, oret;
1094
138k
  int ret;
1095
1096
138k
  if( ! (!fr->firsthead && fr->rdat.flags & (READER_SEEKABLE|READER_BUFFERED)) )
1097
0
  return PARSE_GOOD;
1098
1099
138k
  start = fr->rd->tell(fr);
1100
1101
138k
  debug2("doing ahead check with BPF %d at %"PRIi64, nhdr->framesize+4, start);
1102
  /* step framesize bytes forward and read next possible header*/
1103
138k
  if((oret=fr->rd->skip_bytes(fr, nhdr->framesize))<0)
1104
121k
  {
1105
121k
    if(oret==READER_ERROR && NOQUIET) error("cannot seek!");
1106
1107
121k
    return oret == MPG123_NEED_MORE ? PARSE_MORE : PARSE_ERR;
1108
121k
  }
1109
1110
  /* Read header, seek back. */
1111
16.5k
  hd = fr->rd->head_read(fr,&nexthead);
1112
16.5k
  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
16.5k
  if(hd == MPG123_NEED_MORE) return PARSE_MORE;
1119
1120
16.2k
  debug1("After fetching next header, at %"PRIi64, fr->rd->tell(fr));
1121
16.2k
  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
16.2k
  debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead);
1128
16.2k
  if(!head_check(nexthead) || !head_compatible(newhead, nexthead))
1129
13.5k
  {
1130
13.5k
    debug("No, the header was not valid, start from beginning...");
1131
13.5k
    fr->oldhead = 0; /* start over */
1132
    /* try next byte for valid header */
1133
13.5k
    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
13.5k
    return PARSE_AGAIN;
1140
13.5k
  }
1141
2.71k
  else return PARSE_GOOD;
1142
16.2k
}
1143
1144
static int handle_id3v2(mpg123_handle *fr, unsigned long newhead)
1145
50.0k
{
1146
50.0k
  int ret;
1147
50.0k
  fr->oldhead = 0; /* Think about that. Used to be present only for skipping of junk, not resync-style wetwork. */
1148
50.0k
  ret = INT123_parse_new_id3(fr, newhead);
1149
50.0k
  if     (ret < 0) return ret;
1150
35.2k
#ifndef NO_ID3V2
1151
35.2k
  else if(ret > 0){ debug("got ID3v2"); fr->metaflags  |= MPG123_NEW_ID3|MPG123_ID3; }
1152
4.72k
  else debug("no useful ID3v2");
1153
35.2k
#endif
1154
35.2k
  return PARSE_AGAIN;
1155
50.0k
}
1156
1157
static int handle_apetag(mpg123_handle *fr, unsigned long newhead)
1158
13.0k
{
1159
13.0k
  unsigned char apebuf[28];
1160
13.0k
  unsigned long val;
1161
13.0k
  int i, ret;
1162
  /* How many bytes to backpedal to get back to just after the first byte of */
1163
  /* the supposed header. */
1164
13.0k
  int back_bytes = 3;
1165
13.0k
  fr->oldhead = 0;
1166
1167
13.0k
  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
13.0k
  if((ret=fr->rd->fullread(fr,apebuf,28)) < 0)
1170
396
    return ret;
1171
12.6k
  back_bytes += ret;
1172
12.6k
  if(ret < 28)
1173
0
    goto apetag_bad;
1174
  
1175
12.6k
  debug1("trying to parse APE header at %"PRIi64, fr->rd->tell(fr));
1176
  /* Apetags start with "APETAGEX", "APET" is already tested. */
1177
12.6k
  if(strncmp((char *)apebuf,"AGEX",4) != 0)
1178
2.12k
    goto apetag_bad;
1179
1180
  /* Version must be 2.000 / 2000 */
1181
10.5k
  val = ((unsigned long)apebuf[7]<<24)
1182
10.5k
  | ((unsigned long)apebuf[6]<<16)
1183
10.5k
  | ((unsigned long)apebuf[5]<<8)
1184
10.5k
  | apebuf[4];
1185
10.5k
  if(val != 2000)
1186
2.15k
    goto apetag_bad;
1187
1188
  /* Last 8 bytes must be 0 */
1189
44.0k
  for(i=20; i<28; i++)
1190
40.0k
    if(apebuf[i])
1191
4.40k
      goto apetag_bad;
1192
1193
  /* Looks good, skip the rest. */
1194
3.96k
  val = ((unsigned long)apebuf[11]<<24)
1195
3.96k
  | ((unsigned long)apebuf[10]<<16)
1196
3.96k
  | ((unsigned long)apebuf[9]<<8)
1197
3.96k
  | apebuf[8];
1198
3.96k
  debug2( "skipping %lu bytes of APE data at %"PRIi64
1199
3.96k
  , val, fr->rd->tell(fr) );
1200
  /* If encountering EOF here, things are just at an end. */
1201
3.96k
  if((ret=fr->rd->skip_bytes(fr,val)) < 0)
1202
242
    return ret;
1203
1204
3.72k
  return PARSE_AGAIN;
1205
1206
8.67k
apetag_bad: 
1207
8.67k
  debug("no proper APE tag found, seeking back");
1208
8.67k
  if(fr->rd->back_bytes(fr,back_bytes) < 0 && NOQUIET)
1209
8.67k
    error1("Cannot seek %d bytes back!", back_bytes);
1210
1211
8.67k
  return PARSE_AGAIN; /* Give the resync code a chance to fix things */
1212
3.96k
}
1213
1214
/* Advance a byte in stream to get next possible header and forget 
1215
   buffered data if possible (for feed reader). */
1216
111M
#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
111M
{
1219
111M
  int ret;
1220
111M
  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
111M
  if(forget && fr->rd->forget != NULL)
1225
2.77k
  {
1226
    /* Ensure that the last 4 bytes stay in buffers for reading the header
1227
       anew. */
1228
2.77k
    if(!fr->rd->back_bytes(fr, 4))
1229
2.77k
    {
1230
2.77k
      fr->rd->forget(fr);
1231
2.77k
      fr->rd->back_bytes(fr, -4);
1232
2.77k
    }
1233
2.77k
  }
1234
111M
  return ret; /* No surprise here, error already triggered early return. */
1235
111M
}
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
223k
{
1240
223k
  int ret;
1241
223k
  int freeformat_count = 0;
1242
223k
  long limit = 65536;
1243
223k
  unsigned long newhead = *newheadp;
1244
223k
  unsigned int forgetcount = 0;
1245
  /* check for id3v2; first three bytes (of 4) are "ID3" */
1246
223k
  if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1247
22.6k
  {
1248
22.6k
    return handle_id3v2(fr, newhead);
1249
22.6k
  }
1250
201k
  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
201k
  if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F')
1254
1.21k
  {
1255
1.21k
    if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr, "Note: Looks like a RIFF header.\n");
1256
1257
1.21k
    if((ret=fr->rd->head_read(fr,&newhead))<=0) return ret;
1258
1259
1.66M
    while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a')
1260
1.66M
    {
1261
1.66M
      if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1262
1.66M
      if((ret=forget_head_shift(fr,&newhead,!forgetcount))<=0) return ret;
1263
1.66M
    }
1264
386
    if((ret=fr->rd->head_read(fr,&newhead))<=0) return ret;
1265
1266
200
    if(VERBOSE2 && fr->silent_resync == 0) fprintf(stderr,"Note: Skipped RIFF header!\n");
1267
1268
200
    fr->oldhead = 0;
1269
200
    *newheadp = newhead;
1270
200
    return PARSE_AGAIN;
1271
386
  }
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
200k
  debug("searching for header...");
1278
200k
  *newheadp = 0; /* Invalidate the external value. */
1279
200k
  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
200k
  if(fr->p.resync_limit < 0 || fr->p.resync_limit > limit)
1284
0
  limit = fr->p.resync_limit;
1285
1286
200k
  do
1287
56.4M
  {
1288
56.4M
    ++(*headcount);
1289
56.4M
    if(limit >= 0 && *headcount >= limit) break;        
1290
1291
56.4M
    if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1292
56.4M
    if((ret=forget_head_shift(fr, &newhead, !forgetcount))<=0) return ret;
1293
1294
56.4M
    if(head_check(newhead) && (ret=decode_header(fr, nhdr, newhead, &freeformat_count))) break;
1295
56.4M
  } while(1);
1296
126k
  if(ret<0) return ret;
1297
1298
125k
  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
125k
  else debug1("hopefully found one at %"PRIi64, fr->rd->tell(fr));
1305
1306
  /* If the new header ist good, it is already decoded. */
1307
125k
  *newheadp = newhead;
1308
125k
  return PARSE_GOOD;
1309
125k
}
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
1.17M
{
1314
1.17M
  int ret = PARSE_ERR;
1315
1.17M
  unsigned long newhead = *newheadp;
1316
1.17M
  *newheadp = 0;
1317
1318
  /* Classic ID3 tags. Read, then start parsing again. */
1319
1.17M
  if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8))
1320
968
  {
1321
968
    fr->id3buf[0] = (unsigned char) ((newhead >> 24) & 0xff);
1322
968
    fr->id3buf[1] = (unsigned char) ((newhead >> 16) & 0xff);
1323
968
    fr->id3buf[2] = (unsigned char) ((newhead >> 8)  & 0xff);
1324
968
    fr->id3buf[3] = (unsigned char) ( newhead        & 0xff);
1325
1326
968
    if((ret=fr->rd->fullread(fr,fr->id3buf+4,124)) < 0) return ret;
1327
1328
700
    fr->metaflags  |= MPG123_NEW_ID3|MPG123_ID3;
1329
700
    fr->rdat.flags |= READER_ID3TAG; /* that marks id3v1 */
1330
700
    if(VERBOSE3) fprintf(stderr,"Note: Skipped ID3v1 tag.\n");
1331
1332
700
    return PARSE_AGAIN;
1333
968
  }
1334
  /* This is similar to initial junk skipping code... */
1335
  /* Check for id3v2; first three bytes (of 4) are "ID3" */
1336
1.17M
  if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
1337
27.3k
  {
1338
27.3k
    return handle_id3v2(fr, newhead);
1339
27.3k
  }
1340
  /* Check for an apetag header */
1341
1.14M
  if(newhead == ('A'<<24)+('P'<<16)+('E'<<8)+'T')
1342
13.0k
  {
1343
13.0k
    return handle_apetag(fr, newhead);
1344
13.0k
  }
1345
1.13M
  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
1.13M
  if(NOQUIET && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n");
1354
1355
1.13M
  if( !(fr->p.flags & MPG123_NO_RESYNC) )
1356
1.13M
  {
1357
1.13M
    long try = 0;
1358
1.13M
    long limit = fr->p.resync_limit;
1359
1.13M
    unsigned int forgetcount = 0;
1360
1361
    /* If a resync is needed the bitreservoir of previous frames is no longer valid */
1362
1.13M
    fr->bitreservoir = 0;
1363
1364
1.13M
    if(NOQUIET && fr->silent_resync == 0) fprintf(stderr, "Note: Trying to resync...\n");
1365
1366
1.13M
    do /* ... shift the header with additional single bytes until be found something that could be a header. */
1367
53.2M
    {
1368
53.2M
      ++try;
1369
53.2M
      if(limit >= 0 && try >= limit) break;        
1370
1371
53.2M
      if(++forgetcount > FORGET_INTERVAL) forgetcount = 0;
1372
53.2M
      if((ret=forget_head_shift(fr,&newhead,!forgetcount)) <= 0)
1373
4.80k
      {
1374
4.80k
        *newheadp = newhead;
1375
4.80k
        if(NOQUIET) fprintf (stderr, "Note: Hit end of (available) data during resync.\n");
1376
1377
4.80k
        return ret ? ret : PARSE_END;
1378
4.80k
      }
1379
53.2M
      if(VERBOSE3) debug3("resync try %li at %"PRIi64", got newhead 0x%08lx", try, fr->rd->tell(fr),  newhead);
1380
53.2M
    } while(!head_check(newhead));
1381
1382
1.13M
    *newheadp = newhead;
1383
1.13M
    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
1.13M
    if(limit >= 0 && try >= limit)
1387
69
    {
1388
69
      if(NOQUIET)
1389
69
      error1("Giving up resync after %li bytes - your stream is not nice... (maybe increasing resync limit could help).", try);
1390
1391
69
      fr->err = MPG123_RESYNC_FAIL;
1392
69
      return PARSE_ERR;
1393
69
    }
1394
1.13M
    else
1395
1.13M
    {
1396
1.13M
      debug1("Found possibly valid header 0x%lx... unsetting oldhead to reinit stream.", newhead);
1397
1.13M
      fr->oldhead = 0;
1398
1.13M
      return PARSE_RESYNC;
1399
1.13M
    }
1400
1.13M
  }
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
1.13M
}