Coverage Report

Created: 2025-11-16 06:07

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