Subversion Repositories Kolibri OS

Rev

Rev 646 | Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
576 serge 1
#include "mpg123.h"
2
#include "..\kolibri.h"
3
 
4
#define MAXFRAMESIZE 3456
5
 
6
static int fsizeold=0,ssize;
7
static unsigned char bsspace[2][MAXFRAMESIZE+512]; /* MAXFRAMESIZE */
8
static unsigned char *bsbuf=bsspace[1],*bsbufold;
9
static int bsnum=0;
10
 
11
static unsigned long oldhead = 0;
12
unsigned long firsthead=0;
13
 
14
struct bitstream_info bsi;
15
 
16
int tabsel_123[2][3][16] = {
17
   { {0,32,64,96,128,160,192,224,256,288,320,352,384,416,448,},
18
     {0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384,},
19
     {0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320,} },
20
 
21
   { {0,32,48,56,64,80,96,112,128,144,160,176,192,224,256,},
22
     {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,},
23
     {0,8,16,24,32,40,48,56,64,80,96,112,128,144,160,} }
24
};
25
 
26
int freqs[9] = { 44100, 48000, 32000, 22050, 24000, 16000 , 11025 , 12000 , 8000 };
27
 
28
int stream_head_read(struct reader *rd,unsigned long *newhead);
29
int stream_read_raw(struct reader *rd,unsigned char *buf, int size);
30
 
31
void set_synth_functions(struct frame *fr)
32
{
33
#ifdef USE_3DNOW
34
	static func_dct36 funcs_dct36[2] = {dct36 , dct36_3dnow};
35
#endif
36
 
37
	fr->synth = synth_1to1;
38
	fr->synth_mono = synth_1to1_mono2stereo;;
39
 
40
/* TODO: make autodetection for _all_ x86 optimizations (maybe just for i586+ and keep separate 486 build?) */
41
#ifdef USE_3DNOW
42
	/* check cpuflags bit 31 (3DNow!) and 23 (MMX) */
43
	if((param.stat_3dnow < 2) &&
44
	   ((param.stat_3dnow == 1) ||
45
	    (getcpuflags() & 0x80800000) == 0x80800000))
46
      	{
47
	  fr->synth = funcs[2][ds]; /* 3DNow! optimized synth_1to1() */
48
	  fr->dct36 = funcs_dct36[1]; /* 3DNow! optimized dct36() */
49
	}
50
	else
51
	{
52
	       	  fr->dct36 = funcs_dct36[0];
53
      	}
54
#endif
55
}
56
 
57
int __stdcall create_reader(struct reader *rd,byte *buffer, int buffsize)
58
{  rd->head_read = stream_head_read;
59
    rd->read_frame_body = stream_read_raw;
60
 
61
    rd->buffer = buffer;
62
    rd->stream = buffer;
63
    rd->strpos = 0;
64
 
65
    rd->strremain = 0;
66
    rd->filepos = 0;
67
    return 1;
68
};
69
 
70
int __stdcall init_reader(struct reader *rd, char *file)
71
{  FILEINFO fileinfo;
72
    int retval;
73
    int bytes;
74
 
75
    rd->hFile = file;
76
    get_fileinfo(file, &fileinfo);
77
 
78
    rd->filelen = fileinfo.size;
79
    rd->strpos = 0;
80
    retval=read_file (file,rd->buffer,0,0x10000,&bytes);
81
 
82
    if (retval) return 0;
83
 
84
    rd->strremain = bytes;
85
    rd->filepos = bytes;
86
    return 1;
87
};
88
 
89
static int fill_reader(struct reader *rd)
90
{  int retval;
91
    int bytes;
92
 
93
    mem_cpy(rd->buffer,rd->stream,rd->strremain);
94
    rd->stream = rd->buffer;
95
 
96
    retval=read_file (rd->hFile,rd->buffer+rd->strremain,rd->filepos,
97
                             0x10000-rd->strremain,&bytes);
98
    if (retval) return 0;
99
    if(!bytes) return 0;
100
    rd->strremain+=bytes;
101
    rd->filepos+=bytes;
102
    rd->strpos = 0;
103
    return 1;
104
};
105
 
106
int __stdcall set_reader(struct reader *rd, unsigned int filepos)
107
{  int retval;
108
    unsigned int bytes;
109
    retval=read_file (rd->hFile,rd->buffer,filepos,0x10000,&bytes);
110
    if (retval) return 0;
111
    rd->stream = rd->buffer;
112
    rd->strremain=bytes;
113
    rd->filepos=filepos+bytes;
114
    rd->strpos = 0;
115
 
116
    fsizeold=0;
117
    firsthead=0;
118
    bsbufold = 0;
119
    bsbuf = bsspace[1];
120
    bsnum = 0;
121
    ssize=0;
122
    oldhead=0;
123
    memset(bsspace,0,sizeof(bsspace));
124
    return 1;
125
};
126
 
127
static int stream_head_read(struct reader *rd,unsigned long *newhead)
128
{
129
    if(rd->strremain < 4)
130
      if( !fill_reader(rd))
131
          return 0;
132
    *newhead = (rd->stream[0]<<24)|(rd->stream[1] << 16)|
133
                      (rd->stream[2] << 8)| rd->stream[3];
134
    rd->strpos+=4;
135
    rd->stream+=4;
136
    rd->strremain-=4;
137
    return TRUE;
138
};
139
 
140
int stream_read_raw(struct reader *rd,unsigned char *buf, int size)
141
{
142
    if(rd->strremain < size)
143
         if( !fill_reader(rd))
144
          return 0;
145
 
146
    mem_cpy(buf,rd->stream,size);
147
    rd->strpos+=size;
148
    rd->stream+=size;
149
    rd->strremain-=size;
150
    return 1;
151
};
152
 
153
void set_pointer(long backstep)
154
{
155
  bsi.wordpointer = bsbuf + ssize - backstep;
156
  if (backstep)
157
    mem_cpy(bsi.wordpointer,bsbufold+fsizeold-backstep,backstep);
158
  bsi.bitindex = 0;
159
}
160
 
161
int head_check(unsigned long head)
162
{ 	if
163
	  (
164
		/* first 11 bits are set to 1 for frame sync */
165
		((head & 0xffe00000) != 0xffe00000)
166
		||
167
		/* layer: 01,10,11 is 1,2,3; 00 is reserved */
168
		(!((head>>17)&3))
169
		||
170
		/* 1111 means bad bitrate */
171
		(((head>>12)&0xf) == 0xf)
172
		||
173
		/* 0000 means free format... */
174
		(((head>>12)&0xf) == 0x0)
175
		||
176
		/* sampling freq: 11 is reserved */
177
		(((head>>10)&0x3) == 0x3 )
178
		/* 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 */
179
	)
180
	{
181
		return FALSE;
182
	}
183
	/* if no check failed, the header is valid (hopefully)*/
184
	else
185
	{
186
		return TRUE;
187
	}
188
}
189
 
190
int __stdcall decode_header(struct frame *fr,unsigned long newhead)
191
{
192
    if(!head_check(newhead))
193
        return 0;
194
    if( newhead & (1<<20) )
195
    {  fr->lsf = (newhead & (1<<19)) ? 0x0 : 0x1;
196
        fr->mpeg25 = 0;
197
    }
198
    else
199
    {  fr->lsf = 1;
200
        fr->mpeg25 = 1;
201
    };
202
 
203
    fr->lay = 4-((newhead>>17)&3);
204
    if(fr->mpeg25)
205
        fr->sampling_frequency = 6 + ((newhead>>10)&0x3);
206
    else
207
        fr->sampling_frequency = ((newhead>>10)&0x3) + (fr->lsf*3);
208
        fr->error_protection = ((newhead>>16)&0x1)^0x1;
209
 
210
    fr->bitrate_index = ((newhead>>12)&0xf);
211
    fr->padding   = ((newhead>>9)&0x1);
212
    fr->extension = ((newhead>>8)&0x1);
213
    fr->mode      = ((newhead>>6)&0x3);
214
    fr->mode_ext  = ((newhead>>4)&0x3);
215
    fr->copyright = ((newhead>>3)&0x1);
216
    fr->original  = ((newhead>>2)&0x1);
217
    fr->emphasis  = newhead & 0x3;
218
 
219
    fr->stereo    = (fr->mode == MPG_MD_MONO) ? 1 : 2;
220
 
221
    oldhead = newhead;
222
 
223
    if(!fr->bitrate_index)
224
      return (0);
225
 
226
    switch(fr->lay)
227
    {  case 1:
228
	        fr->do_layer = do_layer1;
229
#ifdef VARMODESUPPORT
230
        if (varmode) {
231
          error("Sorry, layer-1 not supported in varmode.");
232
          return (0);
233
        }
234
#endif
235
        fr->framesize  = (long) tabsel_123[fr->lsf][0][fr->bitrate_index] * 12000;
236
        fr->framesize /= freqs[fr->sampling_frequency];
237
        fr->framesize  = ((fr->framesize+fr->padding)<<2)-4;
238
        break;
239
      case 2:
240
	fr->do_layer = do_layer2;
241
#ifdef VARMODESUPPORT
242
        if (varmode) {
243
          error("Sorry, layer-2 not supported in varmode.");
244
          return (0);
245
        }
246
#endif
247
        fr->framesize = (long) tabsel_123[fr->lsf][1][fr->bitrate_index] * 144000;
248
        fr->framesize /= freqs[fr->sampling_frequency];
249
        fr->framesize += fr->padding - 4;
250
        break;
251
      case 3:
252
        fr->do_layer = do_layer3;
253
        if(fr->lsf)
254
          ssize = (fr->stereo == 1) ? 9 : 17;
255
        else
256
          ssize = (fr->stereo == 1) ? 17 : 32;
257
        if(fr->error_protection)
258
          ssize += 2;
259
        fr->framesize  = (long) tabsel_123[fr->lsf][2][fr->bitrate_index] * 144000;
260
        fr->framesize /= freqs[fr->sampling_frequency]<<(fr->lsf);
261
        fr->framesize = fr->framesize + fr->padding - 4;
262
        break;
263
      default:
264
        return (0);
265
    }
266
    if (fr->framesize > MAXFRAMESIZE)
267
      return (0);
268
    return 1;
269
}
270
 
271
 
272
int read_frame(struct reader *rd, struct frame *fr)
273
{	  unsigned long newhead;
274
    static unsigned char ssave[34];
275
	  //off_t framepos;
276
    fsizeold=fr->framesize;       /* for Layer3 */
277
 
278
read_again:
279
 
280
    if(!rd->head_read(rd,&newhead))
281
      return FALSE;
282
 
283
    if(!decode_header(fr,newhead))
284
    {
285
      if((newhead & 0xffffff00) == 0x49443300)
286
 	  {
287
 		int id3length = 0;
288
		id3length = parse_new_id3(rd, newhead);
289
		goto read_again;
290
	  };
291
      rd->strpos-=3;
292
      rd->stream-=3;
293
      rd->strremain+=3;
294
      goto read_again;
295
   };
296
 
297
#if 0
298
  if(1 || oldhead != newhead || !oldhead)
299
  {
300
 
301
init_resync:
302
 
303
#ifdef SKIP_JUNK
304
	/* watch out for junk/tags on beginning of stream by invalid header */
305
	if(!firsthead && !head_check(newhead) && !free_format_header(newhead)) {
306
		int i;
307
 
308
		/* check for id3v2; first three bytes (of 4) are "ID3" */
309
		if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
310
		{
311
			int id3length = 0;
312
			id3length = parse_new_id3(newhead, rd);
313
			goto read_again;
314
		}
315
		else if(param.verbose > 1) fprintf(stderr,"Note: Junk at the beginning (0x%08lx)\n",newhead);
316
 
317
		/* I even saw RIFF headers at the beginning of MPEG streams ;( */
318
		if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F') {
319
			if(param.verbose > 1) fprintf(stderr, "Note: Looks like a RIFF header.\n");
320
			if(!rd->head_read(rd,&newhead))
321
				return 0;
322
			while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a') {
323
				if(!rd->head_shift(rd,&newhead))
324
					return 0;
325
			}
326
			if(!rd->head_read(rd,&newhead))
327
				return 0;
328
			if(param.verbose > 1) fprintf(stderr,"Note: Skipped RIFF header!\n");
329
			goto read_again;
330
		}
331
		/* unhandled junk... just continue search for a header */
332
		/* step in byte steps through next 64K */
333
		for(i=0;i<65536;i++) {
334
			if(!rd->head_shift(rd,&newhead))
335
				return 0;
336
			/* if(head_check(newhead)) */
337
			if(head_check(newhead) && decode_header(fr, newhead))
338
			break;
339
		}
340
		if(i == 65536) {
341
			if(!param.quiet) error("Giving up searching valid MPEG header after 64K of junk.");
342
			return 0;
343
		}
344
		/*
345
		 * should we additionaly check, whether a new frame starts at
346
		 * the next expected position? (some kind of read ahead)
347
		 * We could implement this easily, at least for files.
348
		 */
349
	}
350
#endif
351
 
352
	/* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */
353
	/* for now, a spurious first free format header screws up here; need free format support for detecting false free format headers... */
354
	if(!firsthead && rd->flags & READER_SEEKABLE && head_check(newhead) && decode_header(fr, newhead))
355
	{
356
		unsigned long nexthead = 0;
357
		int hd = 0;
358
		off_t start = rd->tell(rd);
359
		debug1("doing ahead check with BPF %d", fr->framesize+4);
360
		/* step framesize bytes forward and read next possible header*/
361
		if(rd->back_bytes(rd, -fr->framesize))
362
		{
363
			error("cannot seek!");
364
			return 0;
365
		}
366
		hd = rd->head_read(rd,&nexthead);
367
		if(rd->back_bytes(rd, rd->tell(rd)-start))
368
		{
369
			error("cannot seek!");
370
			return 0;
371
		}
372
		if(!hd)
373
		{
374
			warning("cannot read next header, a one-frame stream? Duh...");
375
		}
376
		else
377
		{
378
			debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead);
379
			/* not allowing free format yet */
380
			if(!head_check(nexthead) || (nexthead & HDRCMPMASK) != (newhead & HDRCMPMASK))
381
			{
382
				debug("No, the header was not valid, start from beginning...");
383
				/* try next byte for valid header */
384
				if(rd->back_bytes(rd, 3))
385
				{
386
					error("cannot seek!");
387
					return 0;
388
				}
389
				goto read_again;
390
			}
391
		}
392
	}
393
 
394
    /* why has this head check been avoided here before? */
395
    if(!head_check(newhead))
396
    {
397
      if(!firsthead && free_format_header(newhead))
398
      {
399
        error1("Header 0x%08lx seems to indicate a free format stream; I do not handle that yet", newhead);
400
        goto read_again;
401
        return 0;
402
      }
403
    /* and those ugly ID3 tags */
404
      if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8)) {
405
           rd->skip_bytes(rd,124);
406
	   if (param.verbose > 1) fprintf(stderr,"Note: Skipped ID3 Tag!\n");
407
           goto read_again;
408
      }
409
      /* duplicated code from above! */
410
      /* check for id3v2; first three bytes (of 4) are "ID3" */
411
      if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
412
      {
413
        int id3length = 0;
414
        id3length = parse_new_id3(newhead, rd);
415
        goto read_again;
416
      }
417
      else if (give_note)
418
      {
419
        fprintf(stderr,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset 0x%lx.\n", newhead,rd->tell(rd)-4);
420
      }
421
 
422
      if(give_note && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n");
423
      if (param.tryresync || do_recover) {
424
        int try = 0;
425
        /* TODO: make this more robust, I'd like to cat two mp3 fragments together (in a dirty way) and still have mpg123 beign able to decode all it somehow. */
426
        if(give_note) fprintf(stderr, "Note: Trying to resync...\n");
427
            /* Read more bytes until we find something that looks
428
               reasonably like a valid header.  This is not a
429
               perfect strategy, but it should get us back on the
430
               track within a short time (and hopefully without
431
               too much distortion in the audio output).  */
432
        do {
433
          if(!rd->head_shift(rd,&newhead))
434
		return 0;
435
          /* debug2("resync try %i, got newhead 0x%08lx", try, newhead); */
436
          if (!oldhead)
437
          {
438
            debug("going to init_resync...");
439
            goto init_resync;       /* "considered harmful", eh? */
440
          }
441
         /* we should perhaps collect a list of valid headers that occured in file... there can be more */
442
         /* Michael's new resync routine seems to work better with the one frame readahead (and some input buffering?) */
443
         } while
444
         (
445
           ++try < RESYNC_LIMIT
446
           && (newhead & HDRCMPMASK) != (oldhead & HDRCMPMASK)
447
           && (newhead & HDRCMPMASK) != (firsthead & HDRCMPMASK)
448
         );
449
         /* too many false positives
450
         }while (!(head_check(newhead) && decode_header(fr, newhead))); */
451
         if(try == RESYNC_LIMIT)
452
         {
453
           error("giving up resync - your stream is not nice... perhaps an improved routine could catch up");
454
           return 0;
455
         }
456
 
457
        if (give_note)
458
          fprintf (stderr, "Note: Skipped %d bytes in input.\n", try);
459
      }
460
      else
461
      {
462
        error("not attempting to resync...");
463
        return (0);
464
      }
465
    }
466
 
467
    if (!firsthead) {
468
      if(!decode_header(fr,newhead))
469
      {
470
         error("decode header failed before first valid one, going to read again");
471
         goto read_again;
472
      }
473
    }
474
    else
475
      if(!decode_header(fr,newhead))
476
      {
477
        error("decode header failed - goto resync");
478
        /* return 0; */
479
        goto init_resync;
480
      }
481
  }
482
  else
483
    fr->header_change = 0;
484
#endif
485
 
486
  bsbufold = bsbuf;
487
  bsbuf = bsspace[bsnum]+512;
488
  bsnum = (bsnum + 1) & 1;
489
	/* if filepos is invalid, so is framepos */
490
	//framepos = rd->filepos - 4;
491
  /* read main data into memory */
492
	/* 0 is error! */
493
 
494
	if(!rd->read_frame_body(rd,bsbuf,fr->framesize))
495
		return 0;
496
 
497
#if 0
498
	if(!firsthead)
499
	{
500
		/* following stuff is actually layer3 specific (in practice, not in theory) */
501
		if(fr->lay == 3)
502
		{
503
			/*
504
				going to look for Xing or Info at some position after the header
505
				                                    MPEG 1  MPEG 2/2.5 (LSF)
506
				Stereo, Joint Stereo, Dual Channel  32      17
507
				Mono                                17       9
508
 
509
				Also, how to avoid false positives? I guess I should interpret more of the header to rule that out(?).
510
				I hope that ensuring all zeros until tag start is enough.
511
			*/
512
			size_t lame_offset = (fr->stereo == 2) ? (fr->lsf ? 17 : 32 ) : (fr->lsf ? 9 : 17);
513
			if(fr->framesize >= 120+lame_offset) /* traditional Xing header is 120 bytes */
514
			{
515
				size_t i;
516
				int lame_type = 0;
517
				/* only search for tag when all zero before it (apart from checksum) */
518
				for(i=2; i < lame_offset; ++i) if(bsbuf[i] != 0) break;
519
				if(i == lame_offset)
520
				{
521
					if
522
					(
523
					       (bsbuf[lame_offset] == 'I')
524
						&& (bsbuf[lame_offset+1] == 'n')
525
						&& (bsbuf[lame_offset+2] == 'f')
526
						&& (bsbuf[lame_offset+3] == 'o')
527
					)
528
					{
529
						lame_type = 1; /* We still have to see what there is */
530
					}
531
					else if
532
					(
533
					       (bsbuf[lame_offset] == 'X')
534
						&& (bsbuf[lame_offset+1] == 'i')
535
						&& (bsbuf[lame_offset+2] == 'n')
536
						&& (bsbuf[lame_offset+3] == 'g')
537
					)
538
					{
539
						lame_type = 2;
540
						vbr = VBR; /* Xing header means always VBR */
541
					}
542
					if(lame_type)
543
					{
544
						unsigned long xing_flags;
545
 
546
						/* we have one of these headers... */
547
						if(param.verbose > 1) fprintf(stderr, "Note: Xing/Lame/Info header detected\n");
548
						/* now interpret the Xing part, I have 120 bytes total for sure */
549
						/* there are 4 bytes for flags, but only the last byte contains known ones */
550
						lame_offset += 4; /* now first byte after Xing/Name */
551
						/* 4 bytes dword for flags */
552
						#define make_long(a, o) ((((unsigned long) a[o]) << 24) | (((unsigned long) a[o+1]) << 16) | (((unsigned long) a[o+2]) << 8) | ((unsigned long) a[o+3]))
553
						/* 16 bit */
554
						#define make_short(a,o) ((((unsigned short) a[o]) << 8) | ((unsigned short) a[o+1]))
555
						xing_flags = make_long(bsbuf, lame_offset);
556
						lame_offset += 4;
557
						debug1("Xing: flags 0x%08lx", xing_flags);
558
						if(xing_flags & 1) /* frames */
559
						{
560
							/*
561
								In theory, one should use that value for skipping...
562
								When I know the exact number of samples I could simply count in audio_flush,
563
								but that's problematic with seeking and such.
564
								I still miss the real solution for detecting the end.
565
							*/
566
							track_frames = make_long(bsbuf, lame_offset);
567
							if(track_frames > TRACK_MAX_FRAMES) track_frames = 0; /* endless stream? */
568
							#ifdef GAPLESS
569
							/* if no further info there, remove/add at least the decoder delay */
570
							if(param.gapless)
571
							{
572
								unsigned long length = track_frames * spf(fr);
573
								if(length > 1)
574
								layer3_gapless_init(DECODER_DELAY+GAP_SHIFT, length+DECODER_DELAY+GAP_SHIFT);
575
							}
576
							#endif
577
							debug1("Xing: %lu frames", track_frames);
578
							lame_offset += 4;
579
						}
580
						if(xing_flags & 0x2) /* bytes */
581
						{
582
							#ifdef DEBUG
583
							unsigned long xing_bytes = make_long(bsbuf, lame_offset);
584
							debug1("Xing: %lu bytes", xing_bytes);
585
							#endif
586
							lame_offset += 4;
587
						}
588
						if(xing_flags & 0x4) /* TOC */
589
						{
590
							lame_offset += 100; /* just skip */
591
						}
592
						if(xing_flags & 0x8) /* VBR quality */
593
						{
594
							#ifdef DEBUG
595
							unsigned long xing_quality = make_long(bsbuf, lame_offset);
596
							debug1("Xing: quality = %lu", xing_quality);
597
							#endif
598
							lame_offset += 4;
599
						}
600
						/* I guess that either 0 or LAME extra data follows */
601
						/* there may this crc16 be floating around... (?) */
602
						if(bsbuf[lame_offset] != 0)
603
						{
604
							unsigned char lame_vbr;
605
							float replay_gain[2] = {0,0};
606
							float peak = 0;
607
							float gain_offset = 0; /* going to be +6 for old lame that used 83dB */
608
							char nb[10];
609
							memcpy(nb, bsbuf+lame_offset, 9);
610
							nb[9] = 0;
611
							debug1("Info: Encoder: %s", nb);
612
							if(!strncmp("LAME", nb, 4))
613
							{
614
								gain_offset = 6;
615
								debug("TODO: finish lame detetcion...");
616
							}
617
							lame_offset += 9;
618
							/* the 4 big bits are tag revision, the small bits vbr method */
619
							lame_vbr = bsbuf[lame_offset] & 15;
620
							debug1("Info: rev %u", bsbuf[lame_offset] >> 4);
621
							debug1("Info: vbr mode %u", lame_vbr);
622
							lame_offset += 1;
623
							switch(lame_vbr)
624
							{
625
								/* from rev1 proposal... not sure if all good in practice */
626
								case 1:
627
								case 8: vbr = CBR; break;
628
								case 2:
629
								case 9: vbr = ABR; break;
630
								default: vbr = VBR; /* 00==unknown is taken as VBR */
631
							}
632
							/* skipping: lowpass filter value */
633
							lame_offset += 1;
634
							/* replaygain */
635
							/* 32bit float: peak amplitude -- why did I parse it as int before??*/
636
							/* Ah, yes, lame seems to store it as int since some day in 2003; I've only seen zeros anyway until now, bah! */
637
							if
638
							(
639
								   (bsbuf[lame_offset] != 0)
640
								|| (bsbuf[lame_offset+1] != 0)
641
								|| (bsbuf[lame_offset+2] != 0)
642
								|| (bsbuf[lame_offset+3] != 0)
643
							)
644
							{
645
								debug("Wow! Is there _really_ a non-zero peak value? Now is it stored as float or int - how should I know?");
646
								peak = *(float*) (bsbuf+lame_offset);
647
							}
648
							debug1("Info: peak = %f (I won't use this)", peak);
649
							peak = 0; /* until better times arrived */
650
							lame_offset += 4;
651
							/*
652
								ReplayGain values - lame only writes radio mode gain...
653
								16bit gain, 3 bits name, 3 bits originator, sign (1=-, 0=+), dB value*10 in 9 bits (fixed point)
654
								ignore the setting if name or originator == 000!
655
								radio 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1
656
								audiophile 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0
657
							*/
658
 
659
							for(i =0; i < 2; ++i)
660
							{
661
								unsigned char origin = (bsbuf[lame_offset] >> 2) & 0x7; /* the 3 bits after that... */
662
								if(origin != 0)
663
								{
664
									unsigned char gt = bsbuf[lame_offset] >> 5; /* only first 3 bits */
665
									if(gt == 1) gt = 0; /* radio */
666
									else if(gt == 2) gt = 1; /* audiophile */
667
									else continue;
668
									/* get the 9 bits into a number, divide by 10, multiply sign... happy bit banging */
669
									replay_gain[0] = ((bsbuf[lame_offset] & 0x2) ? -0.1 : 0.1) * (make_short(bsbuf, lame_offset) & 0x1f);
670
								}
671
								lame_offset += 2;
672
							}
673
							debug1("Info: Radio Gain = %03.1fdB", replay_gain[0]);
674
							debug1("Info: Audiophile Gain = %03.1fdB", replay_gain[1]);
675
							for(i=0; i < 2; ++i)
676
							{
677
								if(rva_level[i] <= 0)
678
								{
679
									rva_peak[i] = 0; /* at some time the parsed peak should be used */
680
									rva_gain[i] = replay_gain[i];
681
									rva_level[i] = 0;
682
								}
683
							}
684
							lame_offset += 1; /* skipping encoding flags byte */
685
							if(vbr == ABR)
686
							{
687
								abr_rate = bsbuf[lame_offset];
688
								debug1("Info: ABR rate = %u", abr_rate);
689
							}
690
							lame_offset += 1;
691
							/* encoder delay and padding, two 12 bit values... lame does write them from int ...*/
692
							#ifdef GAPLESS
693
							if(param.gapless)
694
							{
695
								/*
696
									Temporary hack that doesn't work with seeking and also is not waterproof but works most of the time;
697
									in future the lame delay/padding and frame number info should be passed to layer3.c and the junk samples avoided at the source.
698
								*/
699
								unsigned long length = track_frames * spf(fr);
700
								unsigned long skipbegin = DECODER_DELAY + ((((int) bsbuf[lame_offset]) << 4) | (((int) bsbuf[lame_offset+1]) >> 4));
701
								unsigned long skipend = -DECODER_DELAY + (((((int) bsbuf[lame_offset+1]) << 8) | (((int) bsbuf[lame_offset+2]))) & 0xfff);
702
								debug3("preparing gapless mode for layer3: length %lu, skipbegin %lu, skipend %lu", length, skipbegin, skipend);
703
								if(length > 1)
704
								layer3_gapless_init(skipbegin+GAP_SHIFT, (skipend < length) ? length-skipend+GAP_SHIFT : length+GAP_SHIFT);
705
							}
706
							#endif
707
						}
708
						/* switch buffer back ... */
709
						bsbuf = bsspace[bsnum]+512;
710
						bsnum = (bsnum + 1) & 1;
711
						goto read_again;
712
					}
713
				}
714
			}
715
		} /* end block for Xing/Lame/Info tag */
716
		firsthead = newhead; /* _now_ it's time to store it... the first real header */
717
		debug1("firsthead: %08lx", firsthead);
718
		/* now adjust volume */
719
		do_rva();
720
		/* and print id3 info */
721
		if(!param.quiet) print_id3_tag(rd->flags & READER_ID3TAG ? rd->id3buf : NULL);
722
	}
723
#endif
724
 
725
  bsi.bitindex = 0;
726
  bsi.wordpointer = (unsigned char *) bsbuf;
727
  set_synth_functions(fr);
728
  if (fr->error_protection)
729
    getbits(16);
730
  return 1;
731
}
732
 
733
 
734
#if 0
735
 
736
static int stream_back_bytes(struct reader *rds, off_t bytes)
737
{
738
  if(stream_lseek(rds,-bytes,SEEK_CUR) < 0)
739
    return -1;
740
	/* you sure you want the buffer to resync here? */
741
  if(param.usebuffer)
742
	  buffer_resync();
743
  return 0;
744
}
745
 
746
 
747
/* this function strangely is define to seek num frames _back_ (and is called with -offset - duh!) */
748
/* also... let that int be a long in future! */
749
static int stream_back_frame(struct reader *rds,struct frame *fr,long num)
750
{
751
	if(rds->flags & READER_SEEKABLE)
752
	{
753
		unsigned long newframe, preframe;
754
		if(num > 0) /* back! */
755
		{
756
			if(num > fr->num) newframe = 0;
757
			else newframe = fr->num-num;
758
		}
759
		else newframe = fr->num-num;
760
 
761
		/* two leading frames? hm, doesn't seem to be really needed... */
762
		/*if(newframe > 1) newframe -= 2;
763
		else newframe = 0;*/
764
 
765
		/* now seek to nearest leading index position and read from there until newframe is reached */
766
		if(stream_lseek(rds,frame_index_find(newframe, &preframe),SEEK_SET) < 0)
767
		return -1;
768
 
769
		debug2("going to %lu; just got %lu", newframe, preframe);
770
 
771
		fr->num = preframe;
772
 
773
		while(fr->num < newframe)
774
		{
775
			/* try to be non-fatal now... frameNum only gets advanced on success anyway */
776
			if(!read_frame(fr)) break;
777
		}
778
 
779
		/* this is not needed at last? */
780
		/*read_frame(fr);
781
		read_frame(fr);*/
782
 
783
		if(fr->lay == 3) {
784
			set_pointer(512);
785
		}
786
 
787
		debug1("arrived at %lu", fr->num);
788
 
789
		if(param.usebuffer)
790
			buffer_resync();
791
 
792
		return 0;
793
 
794
	}
795
	else return -1; /* invalid, no seek happened */
796
}
797
 
798
static int stream_head_read(struct reader *rds,unsigned long *newhead)
799
{
800
  unsigned char hbuf[4];
801
 
802
  if(fullread(rds,hbuf,4) != 4)
803
    return FALSE;
804
 
805
  *newhead = ((unsigned long) hbuf[0] << 24) |
806
    ((unsigned long) hbuf[1] << 16) |
807
    ((unsigned long) hbuf[2] << 8)  |
808
    (unsigned long) hbuf[3];
809
 
810
  return TRUE;
811
}
812
 
813
static int stream_head_shift(struct reader *rds,unsigned long *head)
814
{
815
  unsigned char hbuf;
816
 
817
  if(fullread(rds,&hbuf,1) != 1)
818
    return 0;
819
  *head <<= 8;
820
  *head |= hbuf;
821
  *head &= 0xffffffff;
822
  return 1;
823
}
824
 
825
static off_t stream_skip_bytes(struct reader *rds,off_t len)
826
{
827
  if (rds->filelen >= 0) {
828
    off_t ret = stream_lseek(rds, len, SEEK_CUR);
829
    if (param.usebuffer)
830
      buffer_resync();
831
    return ret;
832
  } else if (len >= 0) {
833
    unsigned char buf[1024]; /* ThOr: Compaq cxx complained and it makes sense to me... or should one do a cast? What for? */
834
    off_t ret;
835
    while (len > 0) {
836
      off_t num = len < sizeof(buf) ? len : sizeof(buf);
837
      ret = fullread(rds, buf, num);
838
      if (ret < 0)
839
	return ret;
840
      len -= ret;
841
    }
842
    return rds->filepos;
843
  } else
844
    return -1;
845
}
846
 
847
static int stream_read_frame_body(struct reader *rds,unsigned char *buf,
848
				  int size)
849
{
850
  long l;
851
 
852
  if( (l=fullread(rds,buf,size)) != size)
853
  {
854
    if(l <= 0)
855
      return 0;
856
    memset(buf+l,0,size-l);
857
  }
858
 
859
  return 1;
860
}
861
 
862
static off_t stream_tell(struct reader *rds)
863
{
864
  return rds->filepos;
865
}
866
 
867
static void stream_rewind(struct reader *rds)
868
{
869
  stream_lseek(rds,0,SEEK_SET);
870
  if(param.usebuffer)
871
	  buffer_resync();
872
}
873
 
874
static off_t get_fileinfo(struct reader *rds,char *buf)
875
{
876
	off_t len;
877
 
878
        if((len=lseek(rds->filept,0,SEEK_END)) < 0) {
879
                return -1;
880
        }
881
        if(lseek(rds->filept,-128,SEEK_END) < 0)
882
                return -1;
883
        if(fullread(rds,(unsigned char *)buf,128) != 128) {
884
                return -1;
885
        }
886
        if(!strncmp(buf,"TAG",3)) {
887
                len -= 128;
888
        }
889
        if(lseek(rds->filept,0,SEEK_SET) < 0)
890
                return -1;
891
        if(len <= 0)
892
                return -1;
893
	return len;
894
}
895
 
896
#endif
897
 
898
	#define syncsafe_to_long(buf,res) \
899
	( \
900
		(((buf)[0]|(buf)[1]|(buf)[2]|(buf)[3]) & 0x80) ? 0 : \
901
		(res =  (((unsigned long) (buf)[0]) << 27) \
902
		     | (((unsigned long) (buf)[1]) << 14) \
903
		     | (((unsigned long) (buf)[2]) << 7) \
904
		     |  ((unsigned long) (buf)[3]) \
905
		,1) \
906
	)
907
 
908
int parse_new_id3(struct reader *rd, unsigned long header)
909
{
910
	#define UNSYNC_FLAG 128
911
	#define EXTHEAD_FLAG 64
912
	#define EXP_FLAG 32
913
	#define FOOTER_FLAG 16
914
	#define UNKNOWN_FLAGS 15 /* 00001111*/
915
	unsigned char buf[6];
916
	unsigned long length=0;
917
	unsigned char flags = 0;
918
	int ret = 1;
919
	unsigned char* tagdata = NULL;
920
	unsigned char major = header & 0xff;
921
 
922
	if(major == 0xff) return -1;
923
 
924
	if (!rd->read_frame_body(rd,buf,6))
925
   	  return 0;
926
	if(buf[0] == 0xff) /* major version, will never be 0xff */
927
	return -1;
928
 
929
	/* second new byte are some nice flags, if these are invalid skip the whole thing */
930
	flags = buf[1];
931
	/* use 4 bytes from buf to construct 28bit uint value and return 1; return 0 if bytes are not syncsafe */
932
 
933
	if(!syncsafe_to_long(buf+2,length))
934
	  return -1;
935
 
936
 
937
    rd->strpos+=length;
938
    rd->stream+=length;
939
    rd->strremain-=length;
940
 
941
#if 0
942
	/* skip if unknown version/scary flags, parse otherwise */
943
	if((flags & UNKNOWN_FLAGS) || (major > 4))
944
	{
945
		/* going to skip because there are unknown flags set */
946
		if(!rds->skip_bytes(rds,length)) /* will not store data in backbuff! */
947
 
948
        rd->strpos+=length;
949
        rd->stream+=length;
950
        rd->strremain-=length;
951
		ret = 0;
952
	};
953
#endif
954
  return length;
955
};