1 /*
2     MPEG Maaate: An Australian MPEG audio analysis toolkit
3     Copyright (C) 2000 Commonwealth Scientific and Industrial Research Organisation
4     (CSIRO), Australia.
5 
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10 
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15 
16     You should have received a copy of the GNU General Public License
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 */
20 
21 #if HAVE_CONFIG_H
22 #include <config.h>
23 #endif
24 
25 #include "MPEGfile.H"
26 
27 #include "layer1.H"
28 #include "layer2.H"
29 #include "layer3.H"
30 
31 #include "byteOrder.h"
32 
33 /*---------- constructor and destructor ---------------*/
34 
35 // constructor
36 CSAPI_MPEG
MPEGfile(string filenm)37 MPEGfile::MPEGfile(string filenm) {
38 
39   //MPEG specifics attributs
40   analysed   = false;
41   decoded    = dec_fields;
42   audio      = 0;
43   lastlayer  = RESERVED;
44   frameNo    = 0;
45   gr_current = -1;
46 
47   // call the common constructor in AllFormat class
48   // which initialises the variables
49   //   filename, windowNo, fileDuration, windowDuration
50   if(!common_constr(filenm))
51     return;
52 
53   // open file and save file descriptor in AllFormat's fd variable
54   if ((fd = fopen (filename.c_str(), "rb")) == NULL) {
55     cerr << "MaaateMPEG: Cannot open file ";
56     cerr  << filename.c_str() << "." << endl;
57     return;
58   }
59 
60   if (!skip_frame()) //not a MPEG file
61     return;
62 
63   // calculate the duration of the file and store it
64   while (skip_frame());
65   fileDuration = frameNo * nb_granules();
66   windowNo     = fileDuration;
67 
68   //calculate windowDuration
69   windowDuration = timeticks(LOW) * sample_duration(LOW);
70 
71   // reset to start of file
72   seek_window(0);
73   if (layer()==III) {
74 	((Layer3*) audio)->clearinterbuffer();
75   }
76 
77   return;
78 }
79 
80 // destructor
81 CSAPI_MPEG
~MPEGfile()82 MPEGfile::~MPEGfile() {
83 
84   common_destr();
85 
86   if (fd)
87     fclose (fd);
88 
89   if (audio) delete audio;
90   audio=0;
91 }
92 
93 
94 /*---------------- About this file -----------------*/
95 
96 CSAPI_MPEG bool
file_ok()97 MPEGfile::file_ok() {
98   if (fd == NULL) {
99     return false;
100   }
101   if (fileDuration <=0) {
102     return false;
103   }
104   return true;
105 }
106 
107 CSAPI_MPEG bool
is_stereo()108 MPEGfile::is_stereo() {
109   return  ( mode() <= jstereo); //either stereo or jstereo
110 }
111 
112 CSAPI_MPEG int
channel()113 MPEGfile::channel() {
114   return channels();
115 }
116 
117 CSAPI_MPEG double
sampling_rate()118 MPEGfile::sampling_rate() {
119   return samplingrate();
120 }
121 
122 
123 /*---------------- time functions --------------------*/
124 
125 CSAPI_MPEG float
sample_duration(Resolution res)126 MPEGfile::sample_duration( Resolution res ) {
127   //duration of one MPEG frame
128   double frameDur = (1.0*samples_per_frame() / (1000.0 * samplingrate()));
129 
130   if ( res == PCM ) {
131     return 1.0 / (1000.0 * samplingrate() ); //return the duration of one pcm sample
132   }
133 
134   if (layer()==I) {
135     return frameDur / 12.0; //there is one granule of 12 samples
136   } else if (layer()==II || (layer()==III && res == LOW)) {
137     return frameDur / 36.0; // three granules of 12 samples each
138   } else { // layer==III HIGH res
139     return frameDur/((Layer3*)audio)->granules(); // one or  two granule(s) of 1 sample each.
140   }
141 }
142 
143 
144 /*---------------- window function --------------------*/
145 
146 CSAPI_MPEG bool
seek_window(long w_nb)147 MPEGfile::seek_window( long w_nb ) {
148   int nb_gr = nb_granules();
149   // frame no to stop
150   long stopframe = w_nb / (long) nb_gr;
151   // update current granule number after seeking
152   gr_current = (w_nb == 0) ? -1 : (w_nb - 1) % nb_gr;
153 
154   if ( w_nb < windowNo ) {
155     // position file pointer at beginning
156     rewind(fd);
157     frameNo = 0;
158     bitsread = 0;
159     analysed = false;
160   }
161 
162   // skip frames until specified frame is reached
163   while ( frameNo < stopframe ) {
164     if (!skip_frame()) {
165       windowNo = frameNo * nb_gr;
166       return false;
167     }
168     analysed = false;
169   }
170 
171   windowNo = w_nb;
172   return true;
173 }
174 
175 CSAPI_MPEG unsigned int
timeticks(Resolution res)176 MPEGfile::timeticks( Resolution res ) {
177   if ( layer() == III  ) {
178     if ( res == LOW || res == PCM) {
179       return 18;
180     } else {
181       return 1;
182     }
183   } else {
184     return 12;
185   }
186 
187 }
188 
189 
190 /*------------------- skip and analyse function -----------*/
191 
192 CSAPI_MPEG bool
next_window(Resolution res)193 MPEGfile::next_window( Resolution res ) {
194   int nb_gr = nb_granules();
195   DecodeLevel touse = dec_subbands;
196   //future current window
197   long act = windowNo;
198 
199   // matching resolution and decodelevel
200   switch (res) {
201   case NO:
202     touse = dec_fields; break;
203   case LOW:
204     touse = dec_subbands; break;
205   case HIGH:
206     if ( layer() == III) {
207       touse = dec_subsubbands;
208     } else {
209       touse = dec_subbands;
210     }; break;
211   case PCM:
212     touse = dec_pcm; break;
213   default:
214     break;
215   }
216 
217   // also works for gr_current == -1, at the begining
218   if ( gr_current < (nb_gr - 1)) {
219     //that is not the last granule of the current frame
220 
221     if ( analysed && touse < decoded ) {
222       //the current frame has been analysed before, but with a wrong resolution
223       //so we come back to the current window, but without analysis
224       windowNo++;
225       seek_window (act);
226     }
227 
228     if ( !analysed || touse < decoded ) {
229       //the current window is not in the current frame!
230       //because no analyse has been done
231       //so just analyse the next frame with the right decodeLevel
232       if (!parse_frame(touse))
233 	return false;
234       //now the current window is in the current frame
235       decoded = touse;
236       analysed = true;
237     }
238     //just go to the next granule to go the next window
239     gr_current++;
240 
241   } else {
242     //last granule of a frame
243 
244     if ( !analysed ) {
245       //the current window is not in the current frame!
246       //because no analyse has been done
247       //so must skip the frame containing the current window
248       //before parsing the next one
249       if (!skip_frame())
250 	return false;
251     }
252 
253     //now parse the next frame, the next window will be granule 0 of that frame
254     if (!parse_frame(touse))
255       return false;
256     decoded = touse;
257     analysed = true;
258     gr_current = 0;
259   }
260 
261   windowNo++;
262   return true;
263 }
264 
265 CSAPI_MPEG bool
skip_window()266 MPEGfile::skip_window(){
267   int nb_gr = nb_granules();
268 
269  // also works for gr_current == -1, at the begining
270   if ( gr_current < (nb_gr - 1) ) {
271     //that is not the last granule of the current frame
272     gr_current++;
273 
274   } else {
275     //last granule of a frame
276 
277     if (!data_available()) return false;
278     if ( (windowNo / nb_gr) > frameNo) {
279       //that means that the current window is not in the current frame because
280       //of skipping windows
281       if (!skip_frame())
282 	return false;
283       if (!data_available())
284 	return false;
285       //means this is the end of the file
286     }
287     //new window won`t be in the current frame,
288     //but in the next frame at granule 0
289     gr_current = 0;
290     analysed = false;
291   }
292 
293   windowNo++;
294   return true;
295 }
296 
297 
298 /*------------- access function ----------------*/
299 
300 CSAPI_MPEG double
freq_value(unsigned int ch,unsigned int sb,unsigned int nb=0,Resolution res)301 MPEGfile::freq_value( unsigned int ch, unsigned int sb, unsigned int nb = 0,
302 		      Resolution res) {
303   // I don't believe this was correct...
304   // ...but it works
305   if ( res == HIGH && layer() == III) {
306     return mdct_sample (ch,sb); //576 subbands
307   } else {
308     return restored_sample (ch,sb,nb); // 32 subbands
309   }
310   /* This might be correct, but it doesn't work well
311 
312   if (layer() != III) {
313     return restored_sample (ch, sb, nb); // 32 subbands
314   }
315   // layer III needs extra treatment
316   if (res == HIGH) {
317     int subb = sb/SSLIMIT;
318     int ss   = sb%SSLIMIT;
319     return restored_sample(ch,subb,ss); //576 subbands
320   } else {
321     return mdct_sample(ch,sb,nb); //32 subbands in 18 windows
322   }
323   */
324 
325 }
326 
327 CSAPI_MPEG unsigned int
nb_subbands(Resolution res)328 MPEGfile::nb_subbands( Resolution res ) {
329   if ( layer() == III && res == HIGH ) {
330     return 576;
331   } else {
332     return 32;
333   }
334 
335 }
336 
337 
338 /*--------------- pcm decoder --------------------*/
339 // returns number of samples in buffer
340 CSAPI_MPEG long
decode(short * buffer,long window,Channels ch)341 MPEGfile::decode (short *buffer, long window, Channels ch) {
342   // check space in buffer
343   if (buffer == NULL) {
344     return -1;
345   }
346 
347   // check channels requested
348   if ( ch != LEFT && channels()==1) {
349     cerr << "MaaateMPEG: wrong channel to be decoded, will decode LEFT channel." << endl;
350     ch = LEFT;
351   }
352 
353   //number of samples in buffer
354   long samps = 0;
355 
356   int bd,sub,gr,tot;
357   int nb_g;
358   long act_win, act_w;
359 
360   switch (layer()) {
361   case I:
362     // from one window to another
363     for (act_win = 0; act_win < window; act_win++ )  {
364       if (!next_window(PCM)) break;
365       // from one sample to another
366       for (int bandsample = 0; bandsample < 12; bandsample++) {
367 	// from one subband to another
368 	for (int subband = 0; subband < SBLIMIT; subband++) {
369 	  if (ch != RIGHT) {
370 	    buffer[samps++] = pcm_sample(0, subband,
371 					 bandsample,
372 					 gr_current);
373 	  }
374 	  if (ch != LEFT) {
375 	    buffer[samps++] = pcm_sample(1, subband,
376 					 bandsample,
377 					 gr_current);
378 	  }
379 	}
380       }
381     }
382     break;
383 
384   case II:
385     // from one window to another
386     for (act_win = 0; act_win < window; act_win++ )  {
387       if (!next_window(PCM)) break;
388       // from one sample to another
389       for (int bandsample = 0; bandsample < 12; bandsample++) {
390 	// from one subband to another
391 	for (int subband = 0; subband < SBLIMIT; subband++) {
392 	  if (ch != RIGHT) {
393 	    //special mapping because layer II has a special way to
394 	    //store the pcm samples
395 	    tot = subband + bandsample * SBLIMIT + gr_current * 384;
396 	    bd = tot / 96;
397 	    sub = tot % 96;
398 	    gr = sub / SBLIMIT;
399 	    sub = sub % SBLIMIT;
400 	    buffer[samps++] = pcm_sample(0, sub,
401 					 bd,
402 					 gr);
403 	  }
404 	  if (ch != LEFT) {
405 	    //special mapping because layer II has a special way to
406 	    //store the pcm samples
407 	    tot = subband + bandsample * SBLIMIT + gr_current * 384;
408 	    bd = tot / 96;
409 	    sub = tot % 96;
410 	    gr = sub / SBLIMIT;
411 	    sub = sub % SBLIMIT;
412 	    buffer[samps++] = pcm_sample(1, sub,
413 					 bd,
414 					 gr);
415 	  }
416 	}
417       }
418     }
419     break;
420 
421   case III:
422     nb_g = nb_granules() - 1;
423     act_w = 0;
424     while (act_w < window)  {
425       if (!next_window(PCM)) break;
426 
427       // from one sample to another
428       for (int bandsample = 0; bandsample < 18; bandsample++) {
429 	// from one subband to another
430 	for (int subband = 0; subband < SBLIMIT; subband++) {
431 	  if (ch != RIGHT) {
432 	    buffer[samps++] = pcm_sample(0, gr_current,
433 					 subband,
434 					 bandsample);
435 	  }
436 	  if (ch != LEFT) {
437 	    buffer[samps++] = pcm_sample(1, gr_current,
438 					 subband,
439 					 bandsample);
440 	  }
441 	}
442       }
443       act_w++;
444     }
445    break;
446   default: break;
447   }
448   return samps;
449 }
450 
451 
452 /*------------ MPEG specific functions ---------------------------*/
453 
454 //return gr_current
455 CSAPI_MPEG int
selected_granule()456 MPEGfile::selected_granule() {
457   return gr_current;
458 }
459 
460 //return frameNo
461 CSAPI_MPEG long
frame()462 MPEGfile::frame() {
463   return frameNo;
464 }
465 
466 //allow to parse next frame if available, keep windowNo up to date
467 CSAPI_MPEG bool
goTo_nextFrame(Resolution res)468 MPEGfile::goTo_nextFrame( Resolution res) {
469   if (!data_available()) return false;
470   long oldfr = frameNo;
471   while (frameNo == oldfr) {
472     if (!next_window(res))
473       return false;
474   }
475   return true;
476 }
477 
478 
479 // returns whether end of stream was/will be reached
480 CSAPI_MPEG bool
data_available()481 MPEGfile::data_available() {
482   if (!(fd))
483     return false;
484   static struct stat *buf = (struct stat *) malloc (sizeof(struct stat));
485   stat(filename.c_str(), buf);
486   if (((long)buf->st_size - ftell(fd)) < 5)
487     return false;
488   //fileDuration = windowNo;
489   return true;
490 }
491 
492 // reads and checks the header of a frame
493 CSAPI_MPEG bool
parse_header()494 MPEGfile::parse_header() {
495 
496 #define MAXSEARCH 2048
497   // read 4 bytes into header bitfield
498   register unsigned short buf=0;
499 
500   // read over initial junk to find header; give up after 2048 bytes
501   int i=-2;
502 
503   while (((buf & 0xfff0) != 0xfff0) && (i<MAXSEARCH)) {
504     if ((buf & 0x00ff) == 0x00ff) {
505       // only need to read next byte to try and get sync word
506       register unsigned char buf2=0;
507       if (fread(&buf2, sizeof (unsigned char), 1, fd) != 1) {
508 	return false;
509       }
510       buf = (buf << 8) | buf2;
511       i++;
512     } else {
513       // read next 4 bytes
514       if (fread(&buf, sizeof (unsigned short), 1, fd) != 1) {
515 	return false;
516       }
517       i+=2;
518 #ifndef WORDS_BIGENDIAN
519       // exchange the two bytes because of wrong byteorder
520       buf = (buf << 8) | (buf >> 8);
521 #endif
522     }
523   }
524   if (i>0) {
525     if (i==MAXSEARCH) {
526       cerr << "MaaateP: Gave up searching valid MPEG header after "
527 	   << MAXSEARCH << " bytes" << endl;
528       return false;
529     }
530     cerr << "MaaateP: Skipped " << i
531 	 << " byte(s) to find valid MPEG header at file position "
532 	 << ftell(fd)
533 	 << endl;
534   }
535 
536   // write first two bytes to header
537 #ifndef WORDS_BIGENDIAN
538   header.sync            = (buf >> 4) & 0xFFF;
539   header.version         = (buf >> 3) & 0x1;
540   header.layer           = (buf >> 1) & 0x3;
541   header.errorprotection = buf & 0x1;
542 #else
543   ((unsigned short*) (&header))[0] = buf;
544 #endif
545 
546   if (fread(&buf, sizeof (unsigned short), 1, fd) != 1) {
547     return false;
548   }
549 #ifndef WORDS_BIGENDIAN
550   // exchange the two bytes because of wrong byteorder
551   buf = (buf << 8) | (buf >> 8);
552   // write last two bytes to header
553   header.bitrate         = (buf >> 12) & 0xF;
554   header.samplingrate    = (buf >> 10) & 0x3;
555   header.padding         = (buf >> 9) & 0x1;
556   header.extension       = (buf >> 8) & 0x1;
557   header.mode            = (buf >> 6) & 0x3;
558   header.mode_ext        = (buf >> 4) & 0x3;
559   header.copyright       = (buf >> 3) & 0x1;
560   header.original        = (buf >> 2) & 0x1;
561   header.emphasis        = buf & 0x3;
562 #else
563   // write last two bytes to header
564   ((unsigned short*) (&header))[1] = buf;
565 #endif
566 
567   // update frame number
568   frameNo++;
569 
570   // check header
571   if (!checkheader()) {
572     cerr << "MaaateP: Error parsing header of frame "
573 	 << frameNo           << " of file "
574 	 << filename.c_str()  << "." << endl;
575     return false;
576   }
577 
578   return true;
579 }
580 
581 
582 // reads the header of a frame, decides about the layer,
583 // creates a layer-object accordingly, reads the checksum (if required),
584 // and reads the data (via the layer-object)
585 CSAPI_MPEG bool
parse_data(DecodeLevel decode)586 MPEGfile::parse_data(DecodeLevel decode) {
587 
588   // create layerspecific object
589   if (!create_layer())
590     return false;
591 
592   // read checksum
593   if (!read_checksum())
594     return false;
595 
596   // buffer data
597   if (!buffer_data())
598     return false;
599 
600   // parse buffered audio data via layer object
601   if (!audio->parse_data(decode)) {
602     cerr << "MaaateP: Error parsing audio data."<<endl;
603     return false;
604   }
605 
606   return true;
607 }
608 
609 
610 // reads the header of a frame, decides about the layer,
611 // creates a layer-object accordingly, reads the checksum (if required),
612 // and reads the data (via the layer-object)
613 CSAPI_MPEG bool
parse_frame(DecodeLevel decode)614 MPEGfile::parse_frame(DecodeLevel decode) {
615 
616   // calls parse_header
617   if (!parse_header())
618     return false;
619 
620   // calls parse_data
621   if (!parse_data(decode))
622     return false;
623 
624 
625   return true;
626 }
627 
628 
629 // skips over the data of a frame by reading its data into an unused buffer
630 // doesn't parse the data (but: LAYER 3 should remember some!!! - MISSING!!!)
631 CSAPI_MPEG bool
skip_data()632 MPEGfile::skip_data() {
633 
634   // create layerspecific object
635   if (!create_layer())
636     return false;
637 
638   // read checksum
639   if (!read_checksum())
640     return false;
641 
642   // buffer data
643   if (!buffer_data())
644     return false;
645 
646   if ( layer() == III) { //this is a way to fix the problem with buffering in layer III
647     // parse buffered audio data via layer object
648     if (!audio->parse_data(dec_fields)) {
649       cerr << "MaaateP: Error parsing audio data."<<endl;
650       return false;
651     }
652   }
653 
654   return true;
655 }
656 
657 
658 // skips over a frame by reading its haeder & data into an unused buffer
659 // doesn't parse the data (but: LAYER 3 should remember some!!! - MISSING!!!)
660 CSAPI_MPEG bool
skip_frame()661 MPEGfile::skip_frame() {
662 
663   // calls parse_header
664   if (!parse_header())
665     return false;
666 
667   // calls parse_data
668   if (!skip_data())
669     return false;
670 
671 
672   return true;
673 }
674 
675 
676 // create layerspecific object (first time or when layer switiching occurs)
677 CSAPI_MPEG bool
create_layer()678 MPEGfile::create_layer() {
679   if (audio==0 || (layer() != lastlayer)) {
680     if (audio != 0) delete audio;
681     if (layer() == I) {
682       audio = new Layer1(this);
683     } else if (layer() == II) {
684       audio = new Layer2(this);
685     } else if (layer() == III) {
686       audio = new Layer3(this);
687     } else {
688       cerr << "MaaateP: Unknown Layer, cannot create object. " << endl;
689       return false;
690     }
691     lastlayer = layer();
692   }
693   return true;
694 }
695 
696 
697 // read checksum
698 CSAPI_MPEG bool
read_checksum()699 MPEGfile::read_checksum() {
700   if (crcprotected()) {
701     short chktmp;
702     // read 2 bytes (=16bit) into checksum bitfield
703     if (fread (&chktmp, sizeof (unsigned char), 2, fd) != 2) {
704       cerr << "MaaateP: Error reading checksum." << endl;
705       return false;
706     }
707     checksum = chktmp;
708 #ifndef WORDS_BIGENDIAN
709     // exchange the two bytes because of wrong byteorder
710     checksum = (checksum << 8) | (checksum >> 8);
711 #endif
712   }
713   return true;
714 }
715 
716 
717 // read audio data into buffer
718 CSAPI_MPEG bool
buffer_data()719 MPEGfile::buffer_data() {
720   bitsread=0;
721   unsigned int nobytes = framesize();
722   if (fread((char*)buffer, sizeof(unsigned char), nobytes, fd) != nobytes) {
723     if (feof(fd)) { // end of file
724       //	    cerr << "MaaateP: WARNING: End of file reached." << endl;
725     } else {
726       cerr << "MaaateP: Error buffering stream." << endl;
727       return false;
728     }
729   }
730 #ifndef WORDS_BIGENDIAN
731   // swap the bytes
732   for (unsigned int i=0; i < ((nobytes/4)+1); i++) {
733     swap_int((unsigned char *) &(buffer[i]));
734   }
735 #endif
736   return true;
737 }
738 
739 
740 /*------------- layer-specific access to audio data -------------------*/
741 CSAPI_MPEG int
bitallocation(unsigned int ch,unsigned int sb)742 MPEGfile::bitallocation (unsigned int ch, unsigned int sb) {
743   if (layer()==III) {
744     cerr << "MaaateP: Layer 3 has no bitallocation scheme\n";
745     return 0;
746   } else {
747     return audio->bitallocation(ch, sb);
748   }
749 }
750 
751 CSAPI_MPEG int
scfsi(unsigned int ch,unsigned int sb)752 MPEGfile::scfsi (unsigned int ch, unsigned int sb) {
753   if (layer()==I) {
754     cerr << "MaaateP: Layer 1 has no scale factor selection information\n";
755     return 0;
756   } else {
757     return audio->scfsi(ch, sb);
758   }
759 }
760 
761 CSAPI_MPEG float
scalefactor(unsigned int ch,unsigned int sb)762 MPEGfile::scalefactor (unsigned int ch, unsigned int sb) {
763   return audio->scalefactor(ch, sb, gr_current);
764 }
765 
766 CSAPI_MPEG int
sample(unsigned int ch,unsigned int sb,unsigned int no)767 MPEGfile::sample (unsigned int ch, unsigned int sb, unsigned int no) {
768   return audio->sample(ch, sb, no, gr_current);
769 }
770 
771 CSAPI_MPEG double
restored_sample(unsigned int ch,unsigned int sb,unsigned int no)772 MPEGfile::restored_sample (unsigned int ch, unsigned int sb, unsigned int no) {
773   return audio->restored_sample(ch, sb, no, gr_current);
774 }
775 
776 CSAPI_MPEG short
pcm_sample(unsigned int ch,unsigned int sb,unsigned int no,unsigned int ss)777 MPEGfile::pcm_sample (unsigned int ch, unsigned int sb, unsigned int no, unsigned int ss) {
778   return audio->pcm_sample(ch, sb, no, ss);
779 }
780 
781 /* get a pcm sample of the current frame
782    this does not continue reading to a requested position*/
783 CSAPI_MPEG short
pcm(unsigned int ch,unsigned int number)784 MPEGfile::pcm (unsigned int ch, unsigned int number) {
785   // make sure it's in the current frame
786   if (number > samples_per_frame()) {
787     number = samples_per_frame();
788   }
789 
790   // XXX: THIS IS UNTESTED!
791   // calculate sb, no and ss from number
792   unsigned int sb = 0 , gr = 0, ss = 0;
793   if (layer() == I) {
794     gr = 0;
795     sb = number % 32;
796     ss = number / 32;
797   }
798   if (layer() == II) {
799     sb = number % 32;
800     gr = (number / 32 ) % 2;
801     ss = (number / 32 ) / 2;
802   }
803   if (layer() == III) { //TESTED
804     ss = number % 32;
805     gr = (number / 32) % 18;
806     sb = (number / 32) / 18;
807   }
808   return audio->pcm_sample(ch, sb, ss, gr);
809 }
810 
811 CSAPI_MPEG double
mdct_sample(unsigned int ch,unsigned int ssb)812 MPEGfile::mdct_sample (unsigned int ch, unsigned int ssb) {
813   if (layer() == III) {
814     return ((Layer3*) audio)->mdct_sample(ch, gr_current, ssb);
815   } else {
816     cerr << "MaaateP: Only Layer 3 has mdct_sample information\n";
817     return 0.0;
818   }
819 }
820 
821 CSAPI_MPEG void
printSideinfo()822 MPEGfile::printSideinfo () {
823   if (layer() != III) {
824     cerr << "MaaateP: Side information not available for Layer"
825 	 << layer()+1 << "." << endl;
826     cerr << "Only Layer III has a side information header." << endl;
827   } else {
828     ((Layer3*) audio)->printSideinfo();
829   }
830 }
831 
832 CSAPI_MPEG unsigned int
part2_3_length(unsigned int ch)833 MPEGfile::part2_3_length (unsigned int ch) {
834   if (layer()!=III) {
835     cerr << "MaaateP: Only Layer 3 has part2_3_length information\n";
836     return 0;
837   } else {
838     return ((Layer3*) audio)->part2_3_length(ch,gr_current);
839   }
840 }
841 
842 CSAPI_MPEG unsigned int
big_values(unsigned int ch)843 MPEGfile::big_values (unsigned int ch) {
844   if (layer()!=III) {
845     cerr << "MaaateP: Only Layer 3 has big_values information\n";
846     return 0;
847   } else {
848     return ((Layer3*) audio)->big_values(ch,gr_current);
849   }
850 }
851 
852 CSAPI_MPEG unsigned int
count1_values(unsigned int ch)853 MPEGfile::count1_values (unsigned int ch) {
854   if (layer()!=III) {
855     cerr << "MaaateP: Only Layer 3 has count1_values information\n";
856     return 0;
857   } else {
858     return ((Layer3*) audio)->count1_values(ch,gr_current);
859   }
860 }
861 
862 CSAPI_MPEG unsigned int
global_gain(unsigned int ch)863 MPEGfile::global_gain (unsigned int ch) {
864   if (layer()!=III) {
865     cerr << "MaaateP: Only Layer 3 has global_gain information\n";
866     return 0;
867   } else {
868     return ((Layer3*) audio)->global_gain(ch,gr_current);
869   }
870 }
871 
872 CSAPI_MPEG unsigned int
scalefac_compress(unsigned int ch)873 MPEGfile::scalefac_compress (unsigned int ch) {
874   if (layer()!=III) {
875     cerr << "MaaateP: Only Layer 3 has scalefac_compress information\n";
876     return 0;
877   } else {
878     return ((Layer3*) audio)->scalefac_compress(ch,gr_current);
879   }
880 }
881 
882 CSAPI_MPEG bool
window_switching(unsigned int ch)883 MPEGfile::window_switching (unsigned int ch) {
884   if (layer()!=III) {
885     cerr << "MaaateP: Only Layer 3 has window_switching information\n";
886     return 0;
887   } else {
888     return ((Layer3*) audio)->window_switching(ch,gr_current);
889   }
890 }
891 
892 CSAPI_MPEG unsigned int
blocktype(unsigned int ch)893 MPEGfile::blocktype (unsigned int ch) {
894   if (layer()!=III) {
895     cerr << "MaaateP: Only Layer 3 has blocktype information\n";
896     return 0;
897   } else {
898     return ((Layer3*) audio)->blocktype(ch,gr_current);
899   }
900 }
901 
902 CSAPI_MPEG bool
mixedblock(unsigned int ch)903 MPEGfile::mixedblock (unsigned int ch) {
904   if (layer()!=III) {
905     cerr << "MaaateP: Only Layer 3 has mixedblock information\n";
906     return 0;
907   } else {
908     return ((Layer3*) audio)->mixedblock(ch,gr_current);
909   }
910 }
911 
912 CSAPI_MPEG unsigned int
table_select(unsigned int ch,unsigned int area)913 MPEGfile::table_select (unsigned int ch, unsigned int area) {
914   if (layer()!=III) {
915     cerr << "MaaateP: Only Layer 3 has table_select information\n";
916     return 0;
917   } else {
918     return ((Layer3*) audio)->table_select(ch,gr_current, area);
919   }
920 }
921 
922 CSAPI_MPEG unsigned int
subblock_gain(unsigned int ch,unsigned int area)923 MPEGfile::subblock_gain (unsigned int ch, unsigned int area) {
924   if (layer()!=III) {
925     cerr << "MaaateP: Only Layer 3 has subblock_gain information\n";
926     return 0;
927   } else {
928     return ((Layer3*) audio)->subblock_gain(ch,gr_current, area);
929   }
930 }
931 
932 CSAPI_MPEG unsigned int
region0_samps(unsigned int ch)933 MPEGfile::region0_samps (unsigned int ch) {
934   if (layer()!=III) {
935     cerr << "MaaateP: Only Layer 3 has region0_samps information\n";
936     return 0;
937   } else {
938     return ((Layer3*) audio)->region0_samps(ch,gr_current);
939   }
940 }
941 
942 CSAPI_MPEG unsigned int
region1_samps(unsigned int ch)943 MPEGfile::region1_samps (unsigned int ch) {
944   if (layer()!=III) {
945     cerr << "MaaateP: Only Layer 3 has region1_samps information\n";
946     return 0;
947   } else {
948     return ((Layer3*) audio)->region1_samps(ch,gr_current);
949   }
950 }
951 
952 CSAPI_MPEG unsigned int
region2_samps(unsigned int ch)953 MPEGfile::region2_samps (unsigned int ch) {
954   if (layer()!=III) {
955     cerr << "MaaateP: Only Layer 3 has region2_samps information\n";
956     return 0;
957   } else {
958     return ((Layer3*) audio)->region2_samps(ch,gr_current);
959   }
960 }
961 
962 CSAPI_MPEG unsigned int
preflag(unsigned int ch)963 MPEGfile::preflag (unsigned int ch) {
964   if (layer()!=III) {
965     cerr << "MaaateP: Only Layer 3 has preflag information\n";
966     return 0;
967   } else {
968     return ((Layer3*) audio)->preflag(ch,gr_current);
969   }
970 }
971 
972 CSAPI_MPEG unsigned int
scalefac_scale(unsigned int ch)973 MPEGfile::scalefac_scale (unsigned int ch) {
974   if (layer()!=III) {
975     cerr << "MaaateP: Only Layer 3 has scalefac_scale information\n";
976     return 0;
977   } else {
978     return ((Layer3*) audio)->scalefac_scale(ch,gr_current);
979   }
980 }
981 
982 CSAPI_MPEG unsigned int
count1table_select(unsigned int ch)983 MPEGfile::count1table_select(unsigned int ch) {
984   if (layer()!=III) {
985     cerr << "MaaateP: Only Layer 3 has count1table_select information\n";
986     return 0;
987   } else {
988     return ((Layer3*) audio)->count1table_select(ch,gr_current);
989   }
990 }
991 
992 CSAPI_MPEG unsigned int
scf_band_bound_l(unsigned int subbandindex)993 MPEGfile::scf_band_bound_l(unsigned int subbandindex) {
994   if (layer()!=III) {
995     cerr << "MaaateP: Only Layer 3 has scf_band_bound_l information\n";
996     return 0;
997   } else {
998     return ((Layer3*) audio)->scf_band_bound_l(subbandindex);
999   }
1000 }
1001 
1002 CSAPI_MPEG unsigned int
scf_band_bound_s(unsigned int subbandindex)1003 MPEGfile::scf_band_bound_s(unsigned int subbandindex) {
1004   if (layer()!=III) {
1005     cerr << "MaaateP: Only Layer 3 has scf_band_bound_s information\n";
1006     return 0;
1007   } else {
1008     return ((Layer3*) audio)->scf_band_bound_s(subbandindex);
1009   }
1010 }
1011 
1012 CSAPI_MPEG unsigned int
slen1(unsigned int ch)1013 MPEGfile::slen1(unsigned int ch) {
1014   if (layer()!=III) {
1015     cerr << "MaaateP: Only Layer 3 has slen1 information\n";
1016     return 0;
1017   } else {
1018     return ((Layer3*) audio)->slen1(ch,gr_current);
1019   }
1020 }
1021 
1022 CSAPI_MPEG unsigned int
slen2(unsigned int ch)1023 MPEGfile::slen2(unsigned int ch) {
1024   if (layer()!=III) {
1025     cerr << "MaaateP: Only Layer 3 has slen2 information\n";
1026     return 0;
1027   } else {
1028     return ((Layer3*) audio)->slen2(ch,gr_current);
1029   }
1030 }
1031 
1032 
1033 // returns to the layer-specific parser the number of requested bits
1034 // from the audio file
1035 CSAPI_MPEG unsigned int
readbitsfrombuffer(unsigned int nobits)1036 MPEGfile::readbitsfrombuffer(unsigned int nobits) {
1037   static unsigned int bitmask[33] = {
1038     0,  // dummy
1039     0x00000001, 0x00000003, 0x00000007, 0x0000000F,
1040     0x0000001F, 0x0000003F, 0x0000007F, 0x000000FF,
1041     0x000001FF, 0x000003FF, 0x000007FF, 0x00000FFF,
1042     0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF,
1043     0x0001FFFF, 0x0003FFFF, 0x0007FFFF, 0x000FFFFF,
1044     0x001FFFFF, 0x003FFFFF, 0x007FFFFF, 0x00FFFFFF,
1045     0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF,
1046     0x1FFFFFFF, 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF
1047   };
1048 
1049   unsigned int val = 0; // resulting value
1050   unsigned int bufferindex = bitsread / 32; // index of current word
1051   unsigned int whichbit = bitsread % 32;    // current bitnumber within word
1052   unsigned int intlength = whichbit+nobits; // last bit to be read
1053   bitsread += nobits; // remember until where read
1054 
1055   if (nobits > 32 || bufferindex>=MAX_BUFSIZE) {
1056     cerr << "MaaateP: Error reading from bitstream ("
1057 	 << nobits << "," << bufferindex << ")" << endl;
1058     return 0;
1059   }
1060 
1061   if (intlength <= 32)  {
1062     // all bits contained in buffer[bufferindex]
1063     val = (buffer[bufferindex] >> (32 - intlength)) & bitmask[nobits];
1064   } else {
1065     // bits are in buffer[bufferindex] and buffer[bufferindex+1]
1066     unsigned int fromfirst = 32-whichbit;
1067     unsigned int fromsec   = intlength-32;
1068     val = (buffer[bufferindex] & bitmask[fromfirst]) << fromsec;
1069     val |= (buffer[bufferindex+1] >> (32-fromsec)) & bitmask[fromsec];
1070   }
1071 
1072   return val;
1073 }
1074 
1075 CSAPI_MPEG int
nb_granules()1076 MPEGfile::nb_granules() {
1077  if (layer()==I) {
1078     return 1;
1079   } else if (layer()==II) {
1080     return 3; // three granules
1081   } else { // layer==III HIGH res
1082     return ((Layer3*)audio)->granules();
1083   }
1084 }
1085