Subversion Repositories Kolibri OS

Rev

Rev 228 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
228 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;
286 serge 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));
228 serge 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
   { rd->strpos-=3;
285
      rd->stream-=3;
286
      rd->strremain+=3;
287
      goto read_again;
288
   };
289
 
290
#if 0
291
  if(1 || oldhead != newhead || !oldhead)
292
  {
293
 
294
init_resync:
295
 
296
#ifdef SKIP_JUNK
297
	/* watch out for junk/tags on beginning of stream by invalid header */
298
	if(!firsthead && !head_check(newhead) && !free_format_header(newhead)) {
299
		int i;
300
 
301
		/* check for id3v2; first three bytes (of 4) are "ID3" */
302
		if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
303
		{
304
			int id3length = 0;
305
			id3length = parse_new_id3(newhead, rd);
306
			goto read_again;
307
		}
308
		else if(param.verbose > 1) fprintf(stderr,"Note: Junk at the beginning (0x%08lx)\n",newhead);
309
 
310
		/* I even saw RIFF headers at the beginning of MPEG streams ;( */
311
		if(newhead == ('R'<<24)+('I'<<16)+('F'<<8)+'F') {
312
			if(param.verbose > 1) fprintf(stderr, "Note: Looks like a RIFF header.\n");
313
			if(!rd->head_read(rd,&newhead))
314
				return 0;
315
			while(newhead != ('d'<<24)+('a'<<16)+('t'<<8)+'a') {
316
				if(!rd->head_shift(rd,&newhead))
317
					return 0;
318
			}
319
			if(!rd->head_read(rd,&newhead))
320
				return 0;
321
			if(param.verbose > 1) fprintf(stderr,"Note: Skipped RIFF header!\n");
322
			goto read_again;
323
		}
324
		/* unhandled junk... just continue search for a header */
325
		/* step in byte steps through next 64K */
326
		for(i=0;i<65536;i++) {
327
			if(!rd->head_shift(rd,&newhead))
328
				return 0;
329
			/* if(head_check(newhead)) */
330
			if(head_check(newhead) && decode_header(fr, newhead))
331
			break;
332
		}
333
		if(i == 65536) {
334
			if(!param.quiet) error("Giving up searching valid MPEG header after 64K of junk.");
335
			return 0;
336
		}
337
		/*
338
		 * should we additionaly check, whether a new frame starts at
339
		 * the next expected position? (some kind of read ahead)
340
		 * We could implement this easily, at least for files.
341
		 */
342
	}
343
#endif
344
 
345
	/* first attempt of read ahead check to find the real first header; cannot believe what junk is out there! */
346
	/* for now, a spurious first free format header screws up here; need free format support for detecting false free format headers... */
347
	if(!firsthead && rd->flags & READER_SEEKABLE && head_check(newhead) && decode_header(fr, newhead))
348
	{
349
		unsigned long nexthead = 0;
350
		int hd = 0;
351
		off_t start = rd->tell(rd);
352
		debug1("doing ahead check with BPF %d", fr->framesize+4);
353
		/* step framesize bytes forward and read next possible header*/
354
		if(rd->back_bytes(rd, -fr->framesize))
355
		{
356
			error("cannot seek!");
357
			return 0;
358
		}
359
		hd = rd->head_read(rd,&nexthead);
360
		if(rd->back_bytes(rd, rd->tell(rd)-start))
361
		{
362
			error("cannot seek!");
363
			return 0;
364
		}
365
		if(!hd)
366
		{
367
			warning("cannot read next header, a one-frame stream? Duh...");
368
		}
369
		else
370
		{
371
			debug2("does next header 0x%08lx match first 0x%08lx?", nexthead, newhead);
372
			/* not allowing free format yet */
373
			if(!head_check(nexthead) || (nexthead & HDRCMPMASK) != (newhead & HDRCMPMASK))
374
			{
375
				debug("No, the header was not valid, start from beginning...");
376
				/* try next byte for valid header */
377
				if(rd->back_bytes(rd, 3))
378
				{
379
					error("cannot seek!");
380
					return 0;
381
				}
382
				goto read_again;
383
			}
384
		}
385
	}
386
 
387
    /* why has this head check been avoided here before? */
388
    if(!head_check(newhead))
389
    {
390
      if(!firsthead && free_format_header(newhead))
391
      {
392
        error1("Header 0x%08lx seems to indicate a free format stream; I do not handle that yet", newhead);
393
        goto read_again;
394
        return 0;
395
      }
396
    /* and those ugly ID3 tags */
397
      if((newhead & 0xffffff00) == ('T'<<24)+('A'<<16)+('G'<<8)) {
398
           rd->skip_bytes(rd,124);
399
	   if (param.verbose > 1) fprintf(stderr,"Note: Skipped ID3 Tag!\n");
400
           goto read_again;
401
      }
402
      /* duplicated code from above! */
403
      /* check for id3v2; first three bytes (of 4) are "ID3" */
404
      if((newhead & (unsigned long) 0xffffff00) == (unsigned long) 0x49443300)
405
      {
406
        int id3length = 0;
407
        id3length = parse_new_id3(newhead, rd);
408
        goto read_again;
409
      }
410
      else if (give_note)
411
      {
412
        fprintf(stderr,"Note: Illegal Audio-MPEG-Header 0x%08lx at offset 0x%lx.\n", newhead,rd->tell(rd)-4);
413
      }
414
 
415
      if(give_note && (newhead & 0xffffff00) == ('b'<<24)+('m'<<16)+('p'<<8)) fprintf(stderr,"Note: Could be a BMP album art.\n");
416
      if (param.tryresync || do_recover) {
417
        int try = 0;
418
        /* 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. */
419
        if(give_note) fprintf(stderr, "Note: Trying to resync...\n");
420
            /* Read more bytes until we find something that looks
421
               reasonably like a valid header.  This is not a
422
               perfect strategy, but it should get us back on the
423
               track within a short time (and hopefully without
424
               too much distortion in the audio output).  */
425
        do {
426
          if(!rd->head_shift(rd,&newhead))
427
		return 0;
428
          /* debug2("resync try %i, got newhead 0x%08lx", try, newhead); */
429
          if (!oldhead)
430
          {
431
            debug("going to init_resync...");
432
            goto init_resync;       /* "considered harmful", eh? */
433
          }
434
         /* we should perhaps collect a list of valid headers that occured in file... there can be more */
435
         /* Michael's new resync routine seems to work better with the one frame readahead (and some input buffering?) */
436
         } while
437
         (
438
           ++try < RESYNC_LIMIT
439
           && (newhead & HDRCMPMASK) != (oldhead & HDRCMPMASK)
440
           && (newhead & HDRCMPMASK) != (firsthead & HDRCMPMASK)
441
         );
442
         /* too many false positives
443
         }while (!(head_check(newhead) && decode_header(fr, newhead))); */
444
         if(try == RESYNC_LIMIT)
445
         {
446
           error("giving up resync - your stream is not nice... perhaps an improved routine could catch up");
447
           return 0;
448
         }
449
 
450
        if (give_note)
451
          fprintf (stderr, "Note: Skipped %d bytes in input.\n", try);
452
      }
453
      else
454
      {
455
        error("not attempting to resync...");
456
        return (0);
457
      }
458
    }
459
 
460
    if (!firsthead) {
461
      if(!decode_header(fr,newhead))
462
      {
463
         error("decode header failed before first valid one, going to read again");
464
         goto read_again;
465
      }
466
    }
467
    else
468
      if(!decode_header(fr,newhead))
469
      {
470
        error("decode header failed - goto resync");
471
        /* return 0; */
472
        goto init_resync;
473
      }
474
  }
475
  else
476
    fr->header_change = 0;
477
#endif
478
 
479
  bsbufold = bsbuf;
480
  bsbuf = bsspace[bsnum]+512;
481
  bsnum = (bsnum + 1) & 1;
482
	/* if filepos is invalid, so is framepos */
483
	//framepos = rd->filepos - 4;
484
  /* read main data into memory */
485
	/* 0 is error! */
486
 
487
	if(!rd->read_frame_body(rd,bsbuf,fr->framesize))
488
		return 0;
489
 
490
#if 0
491
	if(!firsthead)
492
	{
493
		/* following stuff is actually layer3 specific (in practice, not in theory) */
494
		if(fr->lay == 3)
495
		{
496
			/*
497
				going to look for Xing or Info at some position after the header
498
				                                    MPEG 1  MPEG 2/2.5 (LSF)
499
				Stereo, Joint Stereo, Dual Channel  32      17
500
				Mono                                17       9
501
 
502
				Also, how to avoid false positives? I guess I should interpret more of the header to rule that out(?).
503
				I hope that ensuring all zeros until tag start is enough.
504
			*/
505
			size_t lame_offset = (fr->stereo == 2) ? (fr->lsf ? 17 : 32 ) : (fr->lsf ? 9 : 17);
506
			if(fr->framesize >= 120+lame_offset) /* traditional Xing header is 120 bytes */
507
			{
508
				size_t i;
509
				int lame_type = 0;
510
				/* only search for tag when all zero before it (apart from checksum) */
511
				for(i=2; i < lame_offset; ++i) if(bsbuf[i] != 0) break;
512
				if(i == lame_offset)
513
				{
514
					if
515
					(
516
					       (bsbuf[lame_offset] == 'I')
517
						&& (bsbuf[lame_offset+1] == 'n')
518
						&& (bsbuf[lame_offset+2] == 'f')
519
						&& (bsbuf[lame_offset+3] == 'o')
520
					)
521
					{
522
						lame_type = 1; /* We still have to see what there is */
523
					}
524
					else if
525
					(
526
					       (bsbuf[lame_offset] == 'X')
527
						&& (bsbuf[lame_offset+1] == 'i')
528
						&& (bsbuf[lame_offset+2] == 'n')
529
						&& (bsbuf[lame_offset+3] == 'g')
530
					)
531
					{
532
						lame_type = 2;
533
						vbr = VBR; /* Xing header means always VBR */
534
					}
535
					if(lame_type)
536
					{
537
						unsigned long xing_flags;
538
 
539
						/* we have one of these headers... */
540
						if(param.verbose > 1) fprintf(stderr, "Note: Xing/Lame/Info header detected\n");
541
						/* now interpret the Xing part, I have 120 bytes total for sure */
542
						/* there are 4 bytes for flags, but only the last byte contains known ones */
543
						lame_offset += 4; /* now first byte after Xing/Name */
544
						/* 4 bytes dword for flags */
545
						#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]))
546
						/* 16 bit */
547
						#define make_short(a,o) ((((unsigned short) a[o]) << 8) | ((unsigned short) a[o+1]))
548
						xing_flags = make_long(bsbuf, lame_offset);
549
						lame_offset += 4;
550
						debug1("Xing: flags 0x%08lx", xing_flags);
551
						if(xing_flags & 1) /* frames */
552
						{
553
							/*
554
								In theory, one should use that value for skipping...
555
								When I know the exact number of samples I could simply count in audio_flush,
556
								but that's problematic with seeking and such.
557
								I still miss the real solution for detecting the end.
558
							*/
559
							track_frames = make_long(bsbuf, lame_offset);
560
							if(track_frames > TRACK_MAX_FRAMES) track_frames = 0; /* endless stream? */
561
							#ifdef GAPLESS
562
							/* if no further info there, remove/add at least the decoder delay */
563
							if(param.gapless)
564
							{
565
								unsigned long length = track_frames * spf(fr);
566
								if(length > 1)
567
								layer3_gapless_init(DECODER_DELAY+GAP_SHIFT, length+DECODER_DELAY+GAP_SHIFT);
568
							}
569
							#endif
570
							debug1("Xing: %lu frames", track_frames);
571
							lame_offset += 4;
572
						}
573
						if(xing_flags & 0x2) /* bytes */
574
						{
575
							#ifdef DEBUG
576
							unsigned long xing_bytes = make_long(bsbuf, lame_offset);
577
							debug1("Xing: %lu bytes", xing_bytes);
578
							#endif
579
							lame_offset += 4;
580
						}
581
						if(xing_flags & 0x4) /* TOC */
582
						{
583
							lame_offset += 100; /* just skip */
584
						}
585
						if(xing_flags & 0x8) /* VBR quality */
586
						{
587
							#ifdef DEBUG
588
							unsigned long xing_quality = make_long(bsbuf, lame_offset);
589
							debug1("Xing: quality = %lu", xing_quality);
590
							#endif
591
							lame_offset += 4;
592
						}
593
						/* I guess that either 0 or LAME extra data follows */
594
						/* there may this crc16 be floating around... (?) */
595
						if(bsbuf[lame_offset] != 0)
596
						{
597
							unsigned char lame_vbr;
598
							float replay_gain[2] = {0,0};
599
							float peak = 0;
600
							float gain_offset = 0; /* going to be +6 for old lame that used 83dB */
601
							char nb[10];
602
							memcpy(nb, bsbuf+lame_offset, 9);
603
							nb[9] = 0;
604
							debug1("Info: Encoder: %s", nb);
605
							if(!strncmp("LAME", nb, 4))
606
							{
607
								gain_offset = 6;
608
								debug("TODO: finish lame detetcion...");
609
							}
610
							lame_offset += 9;
611
							/* the 4 big bits are tag revision, the small bits vbr method */
612
							lame_vbr = bsbuf[lame_offset] & 15;
613
							debug1("Info: rev %u", bsbuf[lame_offset] >> 4);
614
							debug1("Info: vbr mode %u", lame_vbr);
615
							lame_offset += 1;
616
							switch(lame_vbr)
617
							{
618
								/* from rev1 proposal... not sure if all good in practice */
619
								case 1:
620
								case 8: vbr = CBR; break;
621
								case 2:
622
								case 9: vbr = ABR; break;
623
								default: vbr = VBR; /* 00==unknown is taken as VBR */
624
							}
625
							/* skipping: lowpass filter value */
626
							lame_offset += 1;
627
							/* replaygain */
628
							/* 32bit float: peak amplitude -- why did I parse it as int before??*/
629
							/* Ah, yes, lame seems to store it as int since some day in 2003; I've only seen zeros anyway until now, bah! */
630
							if
631
							(
632
								   (bsbuf[lame_offset] != 0)
633
								|| (bsbuf[lame_offset+1] != 0)
634
								|| (bsbuf[lame_offset+2] != 0)
635
								|| (bsbuf[lame_offset+3] != 0)
636
							)
637
							{
638
								debug("Wow! Is there _really_ a non-zero peak value? Now is it stored as float or int - how should I know?");
639
								peak = *(float*) (bsbuf+lame_offset);
640
							}
641
							debug1("Info: peak = %f (I won't use this)", peak);
642
							peak = 0; /* until better times arrived */
643
							lame_offset += 4;
644
							/*
645
								ReplayGain values - lame only writes radio mode gain...
646
								16bit gain, 3 bits name, 3 bits originator, sign (1=-, 0=+), dB value*10 in 9 bits (fixed point)
647
								ignore the setting if name or originator == 000!
648
								radio 0 0 1 0 1 1 1 0 0 1 1 1 1 1 0 1
649
								audiophile 0 1 0 0 1 0 0 0 0 0 0 1 0 1 0 0
650
							*/
651
 
652
							for(i =0; i < 2; ++i)
653
							{
654
								unsigned char origin = (bsbuf[lame_offset] >> 2) & 0x7; /* the 3 bits after that... */
655
								if(origin != 0)
656
								{
657
									unsigned char gt = bsbuf[lame_offset] >> 5; /* only first 3 bits */
658
									if(gt == 1) gt = 0; /* radio */
659
									else if(gt == 2) gt = 1; /* audiophile */
660
									else continue;
661
									/* get the 9 bits into a number, divide by 10, multiply sign... happy bit banging */
662
									replay_gain[0] = ((bsbuf[lame_offset] & 0x2) ? -0.1 : 0.1) * (make_short(bsbuf, lame_offset) & 0x1f);
663
								}
664
								lame_offset += 2;
665
							}
666
							debug1("Info: Radio Gain = %03.1fdB", replay_gain[0]);
667
							debug1("Info: Audiophile Gain = %03.1fdB", replay_gain[1]);
668
							for(i=0; i < 2; ++i)
669
							{
670
								if(rva_level[i] <= 0)
671
								{
672
									rva_peak[i] = 0; /* at some time the parsed peak should be used */
673
									rva_gain[i] = replay_gain[i];
674
									rva_level[i] = 0;
675
								}
676
							}
677
							lame_offset += 1; /* skipping encoding flags byte */
678
							if(vbr == ABR)
679
							{
680
								abr_rate = bsbuf[lame_offset];
681
								debug1("Info: ABR rate = %u", abr_rate);
682
							}
683
							lame_offset += 1;
684
							/* encoder delay and padding, two 12 bit values... lame does write them from int ...*/
685
							#ifdef GAPLESS
686
							if(param.gapless)
687
							{
688
								/*
689
									Temporary hack that doesn't work with seeking and also is not waterproof but works most of the time;
690
									in future the lame delay/padding and frame number info should be passed to layer3.c and the junk samples avoided at the source.
691
								*/
692
								unsigned long length = track_frames * spf(fr);
693
								unsigned long skipbegin = DECODER_DELAY + ((((int) bsbuf[lame_offset]) << 4) | (((int) bsbuf[lame_offset+1]) >> 4));
694
								unsigned long skipend = -DECODER_DELAY + (((((int) bsbuf[lame_offset+1]) << 8) | (((int) bsbuf[lame_offset+2]))) & 0xfff);
695
								debug3("preparing gapless mode for layer3: length %lu, skipbegin %lu, skipend %lu", length, skipbegin, skipend);
696
								if(length > 1)
697
								layer3_gapless_init(skipbegin+GAP_SHIFT, (skipend < length) ? length-skipend+GAP_SHIFT : length+GAP_SHIFT);
698
							}
699
							#endif
700
						}
701
						/* switch buffer back ... */
702
						bsbuf = bsspace[bsnum]+512;
703
						bsnum = (bsnum + 1) & 1;
704
						goto read_again;
705
					}
706
				}
707
			}
708
		} /* end block for Xing/Lame/Info tag */
709
		firsthead = newhead; /* _now_ it's time to store it... the first real header */
710
		debug1("firsthead: %08lx", firsthead);
711
		/* now adjust volume */
712
		do_rva();
713
		/* and print id3 info */
714
		if(!param.quiet) print_id3_tag(rd->flags & READER_ID3TAG ? rd->id3buf : NULL);
715
	}
716
#endif
717
 
718
  bsi.bitindex = 0;
719
  bsi.wordpointer = (unsigned char *) bsbuf;
720
  set_synth_functions(fr);
721
  if (fr->error_protection)
722
    getbits(16);
723
  return 1;
724
}
725
 
726
 
286 serge 727
#if 0
228 serge 728
 
729
static int stream_back_bytes(struct reader *rds, off_t bytes)
730
{
731
  if(stream_lseek(rds,-bytes,SEEK_CUR) < 0)
732
    return -1;
733
	/* you sure you want the buffer to resync here? */
734
  if(param.usebuffer)
735
	  buffer_resync();
736
  return 0;
737
}
738
 
739
 
740
/* this function strangely is define to seek num frames _back_ (and is called with -offset - duh!) */
741
/* also... let that int be a long in future! */
742
static int stream_back_frame(struct reader *rds,struct frame *fr,long num)
743
{
744
	if(rds->flags & READER_SEEKABLE)
745
	{
746
		unsigned long newframe, preframe;
747
		if(num > 0) /* back! */
748
		{
749
			if(num > fr->num) newframe = 0;
750
			else newframe = fr->num-num;
751
		}
752
		else newframe = fr->num-num;
753
 
754
		/* two leading frames? hm, doesn't seem to be really needed... */
755
		/*if(newframe > 1) newframe -= 2;
756
		else newframe = 0;*/
757
 
758
		/* now seek to nearest leading index position and read from there until newframe is reached */
759
		if(stream_lseek(rds,frame_index_find(newframe, &preframe),SEEK_SET) < 0)
760
		return -1;
761
 
762
		debug2("going to %lu; just got %lu", newframe, preframe);
763
 
764
		fr->num = preframe;
765
 
766
		while(fr->num < newframe)
767
		{
768
			/* try to be non-fatal now... frameNum only gets advanced on success anyway */
769
			if(!read_frame(fr)) break;
770
		}
771
 
772
		/* this is not needed at last? */
773
		/*read_frame(fr);
774
		read_frame(fr);*/
775
 
776
		if(fr->lay == 3) {
777
			set_pointer(512);
778
		}
779
 
780
		debug1("arrived at %lu", fr->num);
781
 
782
		if(param.usebuffer)
783
			buffer_resync();
784
 
785
		return 0;
786
 
787
	}
788
	else return -1; /* invalid, no seek happened */
789
}
790
 
791
static int stream_head_read(struct reader *rds,unsigned long *newhead)
792
{
793
  unsigned char hbuf[4];
794
 
795
  if(fullread(rds,hbuf,4) != 4)
796
    return FALSE;
797
 
798
  *newhead = ((unsigned long) hbuf[0] << 24) |
799
    ((unsigned long) hbuf[1] << 16) |
800
    ((unsigned long) hbuf[2] << 8)  |
801
    (unsigned long) hbuf[3];
802
 
803
  return TRUE;
804
}
805
 
806
static int stream_head_shift(struct reader *rds,unsigned long *head)
807
{
808
  unsigned char hbuf;
809
 
810
  if(fullread(rds,&hbuf,1) != 1)
811
    return 0;
812
  *head <<= 8;
813
  *head |= hbuf;
814
  *head &= 0xffffffff;
815
  return 1;
816
}
817
 
818
static off_t stream_skip_bytes(struct reader *rds,off_t len)
819
{
820
  if (rds->filelen >= 0) {
821
    off_t ret = stream_lseek(rds, len, SEEK_CUR);
822
    if (param.usebuffer)
823
      buffer_resync();
824
    return ret;
825
  } else if (len >= 0) {
826
    unsigned char buf[1024]; /* ThOr: Compaq cxx complained and it makes sense to me... or should one do a cast? What for? */
827
    off_t ret;
828
    while (len > 0) {
829
      off_t num = len < sizeof(buf) ? len : sizeof(buf);
830
      ret = fullread(rds, buf, num);
831
      if (ret < 0)
832
	return ret;
833
      len -= ret;
834
    }
835
    return rds->filepos;
836
  } else
837
    return -1;
838
}
839
 
840
static int stream_read_frame_body(struct reader *rds,unsigned char *buf,
841
				  int size)
842
{
843
  long l;
844
 
845
  if( (l=fullread(rds,buf,size)) != size)
846
  {
847
    if(l <= 0)
848
      return 0;
849
    memset(buf+l,0,size-l);
850
  }
851
 
852
  return 1;
853
}
854
 
855
static off_t stream_tell(struct reader *rds)
856
{
857
  return rds->filepos;
858
}
859
 
860
static void stream_rewind(struct reader *rds)
861
{
862
  stream_lseek(rds,0,SEEK_SET);
863
  if(param.usebuffer)
864
	  buffer_resync();
865
}
866
 
867
static off_t get_fileinfo(struct reader *rds,char *buf)
868
{
869
	off_t len;
870
 
871
        if((len=lseek(rds->filept,0,SEEK_END)) < 0) {
872
                return -1;
873
        }
874
        if(lseek(rds->filept,-128,SEEK_END) < 0)
875
                return -1;
876
        if(fullread(rds,(unsigned char *)buf,128) != 128) {
877
                return -1;
878
        }
879
        if(!strncmp(buf,"TAG",3)) {
880
                len -= 128;
881
        }
882
        if(lseek(rds->filept,0,SEEK_SET) < 0)
883
                return -1;
884
        if(len <= 0)
885
                return -1;
886
	return len;
887
}
888
 
889
#endif