1 /**********************************************************************
2 Copyright (c) 1991 MPEG/audio software simulation group, All Rights Reserved
3 encode.c
4 **********************************************************************/
5 /**********************************************************************
6  * MPEG/audio coding/decoding software, work in progress              *
7  *   NOT for public distribution until verified and approved by the   *
8  *   MPEG/audio committee.  For further information, please contact   *
9  *   Davis Pan, 508-493-2241, e-mail: pan@3d.enet.dec.com             *
10  *                                                                    *
11  * VERSION 3.9t                                                       *
12  *   changes made since last update:                                  *
13  *   date   programmers         comment                               *
14  * 3/01/91  Douglas Wong,       start of version 1.1 records          *
15  *          Davis Pan                                                 *
16  * 3/06/91  Douglas Wong        rename: setup.h to endef.h            *
17  *                                      efilter to enfilter           *
18  *                                      ewindow to enwindow           *
19  *                              integrated "quantizer", "scalefactor",*
20  *                              and "transmission" files              *
21  *                              update routine "window_subband"       *
22  * 3/31/91  Bill Aspromonte     replaced read_filter by               *
23  *                              create_an_filter                      *
24  * 5/10/91  W. Joseph Carter    Ported to Macintosh and Unix.         *
25  *                              Incorporated Jean-Georges Fritsch's   *
26  *                              "bitstream.c" package.                *
27  *                              Incorporated Bill Aspromonte's        *
28  *                              filterbank coefficient matrix         *
29  *                              calculation routines and added        *
30  *                              roundoff to coincide with specs.      *
31  *                              Modified to strictly adhere to        *
32  *                              encoded bitstream specs, including    *
33  *                              "Berlin changes".                     *
34  *                              Modified PCM sound file handling to   *
35  *                              process all incoming samples and fill *
36  *                              out last encoded frame with zeros     *
37  *                              (silence) if needed.                  *
38  *                              Located and fixed numerous software   *
39  *                              bugs and table data errors.           *
40  * 19jun91  dpwe (Aware)        moved "alloc_*" reader to common.c    *
41  *                              Globals sblimit, alloc replaced by new*
42  *                              struct 'frame_params' passed as arg.  *
43  *                              Added JOINT STEREO coding, layers I,II*
44  *                              Affects: *_bit_allocation,            *
45  *                              subband_quantization, encode_bit_alloc*
46  *                              sample_encoding                       *
47  * 6/10/91  Earle Jennings      modified II_subband_quantization to   *
48  *                              resolve type cast problem for MS_DOS  *
49  * 6/11/91  Earle Jennings      modified to avoid overflow on MS_DOS  *
50  *                              in routine filter_subband             *
51  * 7/10/91  Earle Jennings      port to MsDos from MacIntosh version  *
52  * 8/ 8/91  Jens Spille         Change for MS-C6.00                   *
53  *10/ 1/91  S.I. Sudharsanan,   Ported to IBM AIX platform.           *
54  *          Don H. Lee,                                               *
55  *          Peter W. Farrett                                          *
56  *10/ 3/91  Don H. Lee          implemented CRC-16 error protection   *
57  *                              newly introduced function encode_CRC  *
58  *11/ 8/91  Kathy Wang          Documentation of code                 *
59  *                              All variablenames are referred to     *
60  *                              with surrounding pound (#) signs      *
61  * 2/11/92  W. Joseph Carter    Ported new code to Macintosh.  Most   *
62  *                              important fixes involved changing     *
63  *                              16-bit ints to long or unsigned in    *
64  *                              bit alloc routines for quant of 65535 *
65  *                              and passing proper function args.     *
66  *                              Removed "Other Joint Stereo" option   *
67  *                              and made bitrate be total channel     *
68  *                              bitrate, irrespective of the mode.    *
69  *                              Fixed many small bugs & reorganized.  *
70  * 6/16/92  Shaun Astarabadi    Changed I_scale_factor_calc() and     *
71  *                              II_scale_factor_calc() to use scale   *
72  *                              factor 0 thru 62 only and not to      *
73  *                              encode index 63 into the bit stream.  *
74  * 7/27/92  Mike Li             (re-)Port to MS-DOS                   *
75  * 9/22/92  jddevine@aware.com  Fixed _scale_factor_calc() defs       *
76  * 3/31/93  Giogio Dimino       changed II_a_bit_allocation() from:   *
77  *                              if( ad > ...) to if(ad >= ...)        *
78  * 8/05/93  TEST                changed I_a_bit_allocation() from:    *
79  *                              if( ad > ...) to if(ad >= ...)        *
80  **********************************************************************/
81 
82 #include "config.h"
83 
84 #include <stdlib.h>
85 #include <unistd.h>
86 #include "common.h"
87 #include "encoder.h"
88 
89 extern int freq_in;
90 extern int freq_out;
91 extern int chans_in;
92 extern int chans_out;
93 extern int audio_bits;
94 extern int32_t audio_bytes;
95 extern int raw_in;
96 
97 static unsigned long nseconds = 0;
98 static int num_out = -1;
99 static int buff_pos;
100 static int big_endian;
101 static unsigned char *in_buff;
102 static short *buf1, *buf2, *out_buff;
103 static double freq_quot;
104 
read_and_resample(void)105 static void read_and_resample(void)
106 {
107    int n, nbps, num_in, is;
108    double s, fs;
109 
110    /* Read 1 second of audio from stdin */
111 
112    nbps = chans_in*audio_bits/8; /* Bytes per sample in */
113 
114    if(num_out<0)
115    {
116       /* Initialize, read first sample to the end of the buffer */
117 
118       n = fread(in_buff+freq_in*nbps,1,nbps,stdin);
119       if(n!=nbps) {
120 		  mjpeg_error_exit1("Error reading wave data");
121 
122       }
123    }
124 
125    /* Copy last sample in input buffer to front,
126       read exactly 1 second */
127 
128    memcpy(in_buff,in_buff+freq_in*nbps,nbps);
129    n = fread(in_buff+nbps,1,freq_in*nbps,stdin);
130    num_in = n/nbps + 1;
131 
132    /* Step 1: Make little endian shorts from input */
133 
134    if(audio_bits==8)
135    {
136       for(n=0;n<num_in*chans_in;n++)
137          buf1[n] = (in_buff[n]-128)<<8;
138    }
139    else if(big_endian && !raw_in)
140    {
141       swab(in_buff,buf1,num_in*nbps);
142    }
143 
144    /* Step 2: Make mono from stereo or vice versa if wanted */
145 
146    if(chans_in==2 && chans_out==1)
147    {
148       for(n=0;n<num_in;n++)
149          buf2[n] = (buf1[2*n]+buf1[2*n+1]) >> 1;
150    }
151 
152    if(chans_in==1 && chans_out==2)
153    {
154       for(n=0;n<num_in;n++)
155          buf2[2*n] = buf2[2*n+1] = buf1[n];
156    }
157 
158    /* Step 3: Change sampling frequency if necessary */
159 
160    num_out = ((int64_t)num_in-1)*(int64_t)freq_out/(int64_t)freq_in;
161    if(freq_in != freq_out)
162    {
163       for(n=0;n<num_out;n++)
164       {
165          s = n*freq_quot;
166          is = s;
167          fs = s - is;
168 
169          if(chans_out==2)
170          {
171             out_buff[2*n  ] = (1.0-fs)*buf2[2*is  ] + fs*buf2[2*is+2];
172             out_buff[2*n+1] = (1.0-fs)*buf2[2*is+1] + fs*buf2[2*is+3];
173          }
174          else
175          {
176             out_buff[n] = (1.0-fs)*buf2[is] + fs*buf2[is+1];
177          }
178       }
179    }
180    num_out *= chans_out;
181 
182    nseconds++;
183    mjpeg_debug("%4ld seconds done",nseconds);
184 }
185 
get_samples(short * abuff,int num,int stereo)186 static int get_samples(short *abuff, int num, int stereo)
187 {
188    int n;
189 
190    if(num_out<0)
191    {
192       /* Initialize */
193       unsigned int fred;
194       char *pfred;
195       fred = 2 | (1 << (sizeof(int)*8-8));
196       pfred = (char *)&fred;
197 
198       if(*pfred == 1)
199       {
200          big_endian = 1;
201          mjpeg_info("System is big endian");
202       }
203       else if(*pfred == 2)
204       {
205          big_endian = 0;
206 		 mjpeg_info("System is little endian");
207       }
208       else
209       {
210          mjpeg_error("Can not determine if system is big/lttle endian");
211          mjpeg_error_exit1("Are you running on a Cray - or what?");
212       }
213 
214       freq_quot = (double)freq_in/(double)freq_out;
215 
216       in_buff = (unsigned char *) malloc((freq_in+1)*chans_in*audio_bits/8);
217       if(!in_buff)
218 		  mjpeg_error_exit1("Malloc failed");
219       if( audio_bits==8 || (audio_bits==16 && big_endian) )
220       {
221          buf1 = (short *)malloc((freq_in+1)*chans_in*sizeof(short));
222          if(!buf1)
223 			 mjpeg_error_exit1("Malloc failed");
224       }
225       else
226          buf1 = (short *)in_buff;
227 
228       if(chans_in!=chans_out)
229       {
230          buf2 = (short *)malloc((freq_in+1)*chans_out*sizeof(short));
231          if(!buf2)
232 			 mjpeg_error("Malloc failed");
233       }
234       else
235          buf2 = buf1;
236 
237       if(freq_in!=freq_out)
238       {
239          out_buff = (short *)malloc(freq_out*chans_out*sizeof(short));
240          if(!out_buff)
241 			 mjpeg_error("Malloc failed");
242       }
243       else
244          out_buff = buf2;
245 
246       /* Read first buffer with samples */
247 
248       read_and_resample();
249       buff_pos = 0;
250    }
251 
252    while(num)
253    {
254       if(buff_pos == num_out)
255       {
256         read_and_resample();
257         buff_pos = 0;
258         if(num_out==0) return 0;
259       }
260       n = num;
261       if(buff_pos+n>num_out)
262 		  n = num_out-buff_pos;
263       memcpy(abuff,out_buff+buff_pos,n*sizeof(short));
264       abuff += n;
265       buff_pos += n;
266       num -= n;
267    }
268 
269    return 1;
270 }
271 
272 /*=======================================================================\
273 |                                                                       |
274 | This segment contains all the core routines of the encoder,           |
275 | except for the psychoacoustic models.                                 |
276 |                                                                       |
277 | The user can select either one of the two psychoacoustic              |
278 | models. Model I is a simple tonal and noise masking threshold         |
279 | generator, and Model II is a more sophisticated cochlear masking      |
280 | threshold generator. Model I is recommended for lower complexity      |
281 | applications whereas Model II gives better subjective quality at low  |
282 | bit rates.                                                            |
283 |                                                                       |
284 | Layers I and II of mono, stereo, and joint stereo modes are supported.|
285 | Routines associated with a given layer are prefixed by "I_" for layer |
286 | 1 and "II_" for layer 2.                                              |
287 \=======================================================================*/
288 
289 
290 /************************************************************************
291  *
292  * get_audio()
293  *
294  * PURPOSE:  reads a frame of audio data from a file to the buffer,
295  *   aligns the data for future processing, and separates the
296  *   left and right channels
297  *
298  *  SEMANTICS:
299  * Calls read_samples() to read a frame of audio data from filepointer
300  * #musicin# to #insampl[]#.  The data is shifted to make sure the data
301  * is centered for the 1024pt window to be used by the psychoacoustic model,
302  * and to compensate for the 256 sample delay from the filter bank. For
303  * stereo, the channels are also demultiplexed into #buffer[0][]# and
304  * #buffer[1][]#
305  *
306  ************************************************************************/
307 
get_audio(musicin,buffer,num_samples,stereo,lay)308 unsigned long get_audio(musicin, buffer, num_samples, stereo, lay)
309 FILE *musicin;
310 short buffer[2][1152];
311 unsigned long num_samples;
312 int stereo, lay;
313 {
314    int j, res;
315    short insamp[2304];
316 
317    if (lay == 1){
318       if(stereo == 2){ /* layer 1, stereo */
319          res = get_samples(insamp, 384*2, stereo);
320          for(j=0;j<448;j++) {
321             if(j<64) {
322                buffer[0][j] = buffer[0][j+384];
323                buffer[1][j] = buffer[1][j+384];
324             }
325             else {
326                buffer[0][j] = insamp[2*j-128];
327                buffer[1][j] = insamp[2*j-127];
328             }
329          }
330       }
331       else { /* layer 1, mono */
332          res = get_samples(insamp, 384, stereo);
333          for(j=0;j<448;j++){
334             if(j<64) {
335                buffer[0][j] = buffer[0][j+384];
336                buffer[1][j] = 0;
337             }
338             else {
339                buffer[0][j] = insamp[j-64];
340                buffer[1][j] = 0;
341             }
342          }
343       }
344    }
345    else {
346       if(stereo == 2){ /* layer 2 (or 3), stereo */
347          res = get_samples(insamp, 1152*2, stereo);
348          for(j=0;j<1152;j++) {
349             buffer[0][j] = insamp[2*j];
350             buffer[1][j] = insamp[2*j+1];
351          }
352       }
353       else { /* layer 2 (or 3), mono */
354          res = get_samples(insamp, 1152, stereo);
355          for(j=0;j<1152;j++){
356             buffer[0][j] = insamp[j];
357             buffer[1][j] = 0;
358          }
359       }
360    }
361    return res;
362 }
363 
364 /************************************************************************
365  *
366  * window_subband()
367  *
368  * PURPOSE:  Overlapping window on PCM samples
369  *
370  * SEMANTICS:
371  * 32 16-bit pcm samples are scaled to fractional 2's complement and
372  * concatenated to the end of the window buffer #x#. The updated window
373  * buffer #x# is then windowed by the analysis window #c# to produce the
374  * windowed sample #z#
375  *
376  ************************************************************************/
377 
window_subband(buffer,z,k)378 void window_subband(buffer, z, k)
379 short **buffer;
380 double z[HAN_SIZE];
381 int k;
382 {
383     typedef double XX[2][HAN_SIZE];
384     static XX *x;
385     int i, j;
386     static int off[2] = {0,0};
387     static char init = 0;
388     static double *c;
389     if (!init) {
390         c = (double *) mem_alloc(sizeof(double) * HAN_SIZE, "window");
391         read_ana_window(c);
392         x = (XX *) mem_alloc(sizeof(XX),"x");
393         for (i=0;i<2;i++)
394             for (j=0;j<HAN_SIZE;j++)
395                 (*x)[i][j] = 0;
396         init = 1;
397     }
398 
399     /* replace 32 oldest samples with 32 new samples */
400     for (i=0;i<32;i++) (*x)[k][31-i+off[k]] = (double) *(*buffer)++/SCALE;
401     /* shift samples into proper window positions */
402     for (i=0;i<HAN_SIZE;i++) z[i] = (*x)[k][(i+off[k])&(HAN_SIZE-1)] * c[i];
403     off[k] += 480;              /*offset is modulo (HAN_SIZE-1)*/
404     off[k] &= HAN_SIZE-1;
405 
406 }
407 
408 /************************************************************************
409  *
410  * create_ana_filter()
411  *
412  * PURPOSE:  Calculates the analysis filter bank coefficients
413  *
414  * SEMANTICS:
415  * Calculates the analysis filterbank coefficients and rounds to the
416  * 9th decimal place accuracy of the filterbank tables in the ISO
417  * document.  The coefficients are stored in #filter#
418  *
419  ************************************************************************/
420 
create_ana_filter(filter)421 void create_ana_filter(filter)
422 double filter[SBLIMIT][64];
423 {
424    register int i,k;
425 
426    for (i=0; i<32; i++)
427       for (k=0; k<64; k++) {
428           if ((filter[i][k] = 1e9*cos((double)((2*i+1)*(16-k)*PI64))) >= 0)
429              modf(filter[i][k]+0.5, &filter[i][k]);
430           else
431              modf(filter[i][k]-0.5, &filter[i][k]);
432           filter[i][k] *= 1e-9;
433    }
434 }
435 
436 /************************************************************************
437  *
438  * filter_subband()
439  *
440  * PURPOSE:  Calculates the analysis filter bank coefficients
441  *
442  * SEMANTICS:
443  *      The windowed samples #z# is filtered by the digital filter matrix #m#
444  * to produce the subband samples #s#. This done by first selectively
445  * picking out values from the windowed samples, and then multiplying
446  * them by the filter matrix, producing 32 subband samples.
447  *
448  ************************************************************************/
449 
filter_subband(z,s)450 void filter_subband(z,s)
451 double z[HAN_SIZE], s[SBLIMIT];
452 {
453    double y[64];
454    int i,j;
455    static char init = 0;
456    typedef double MM[SBLIMIT][64];
457    static MM *m;
458 
459    if (!init) {
460        m = (MM *) mem_alloc(sizeof(MM), "filter");
461        create_ana_filter(*m);
462        init = 1;
463    }
464 
465    for (i=0;i<64;i++) for (j=0, y[i] = 0;j<8;j++) y[i] += z[i+64*j];
466    for (i=0;i<SBLIMIT;i++)
467        for (j=0, s[i]= 0;j<64;j++) s[i] += (*m)[i][j] * y[j];
468 }
469 
470 /************************************************************************
471  *
472  * encode_info()
473  *
474  * PURPOSE:  Puts the syncword and header information on the output
475  * bitstream.
476  *
477  ************************************************************************/
478 
encode_info(fr_ps,bs)479 void encode_info(fr_ps,bs)
480 frame_params *fr_ps;
481 Bit_stream_struc *bs;
482 {
483         layer *info = fr_ps->header;
484 
485         putbits(bs,0xfff,12);                    /* syncword 12 bits */
486         put1bit(bs,info->version);               /* ID        1 bit  */
487         putbits(bs,4-info->lay,2);               /* layer     2 bits */
488         put1bit(bs,!info->error_protection);     /* bit set => no err prot */
489         putbits(bs,info->bitrate_index,4);
490         putbits(bs,info->sampling_frequency,2);
491         put1bit(bs,info->padding);
492         put1bit(bs,info->extension);             /* private_bit */
493         putbits(bs,info->mode,2);
494         putbits(bs,info->mode_ext,2);
495         put1bit(bs,info->copyright);
496         put1bit(bs,info->original);
497         putbits(bs,info->emphasis,2);
498 }
499 
500 /************************************************************************
501  *
502  * mod()
503  *
504  * PURPOSE:  Returns the absolute value of its argument
505  *
506  ************************************************************************/
507 
mod(a)508 double mod(a)
509 double a;
510 {
511     return (a > 0) ? a : -a;
512 }
513 
514 /************************************************************************
515  *
516  * I_combine_LR    (Layer I)
517  * II_combine_LR   (Layer II)
518  *
519  * PURPOSE:Combines left and right channels into a mono channel
520  *
521  * SEMANTICS:  The average of left and right subband samples is put into
522  * #joint_sample#
523  *
524  * Layer I and II differ in frame length and # subbands used
525  *
526  ************************************************************************/
527 
I_combine_LR(sb_sample,joint_sample)528 void I_combine_LR(sb_sample, joint_sample)
529 double sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
530 double joint_sample[3][SCALE_BLOCK][SBLIMIT];
531 {   /* make a filtered mono for joint stereo */
532     int sb, smp;
533 
534    for(sb = 0; sb<SBLIMIT; ++sb)
535       for(smp = 0; smp<SCALE_BLOCK; ++smp)
536         joint_sample[0][smp][sb] = .5 *
537                     (sb_sample[0][0][smp][sb] + sb_sample[1][0][smp][sb]);
538 }
539 
II_combine_LR(sb_sample,joint_sample,sblimit)540 void II_combine_LR(sb_sample, joint_sample, sblimit)
541 double sb_sample[2][3][SCALE_BLOCK][SBLIMIT];
542 double joint_sample[3][SCALE_BLOCK][SBLIMIT];
543 int sblimit;
544 {  /* make a filtered mono for joint stereo */
545    int sb, smp, sufr;
546 
547    for(sb = 0; sb<sblimit; ++sb)
548       for(smp = 0; smp<SCALE_BLOCK; ++smp)
549          for(sufr = 0; sufr<3; ++sufr)
550             joint_sample[sufr][smp][sb] = .5 * (sb_sample[0][sufr][smp][sb]
551                                            + sb_sample[1][sufr][smp][sb]);
552 }
553 
554 /************************************************************************
555  *
556  * I_scale_factor_calc     (Layer I)
557  * II_scale_factor_calc    (Layer II)
558  *
559  * PURPOSE:For each subband, calculate the scale factor for each set
560  * of the 12 subband samples
561  *
562  * SEMANTICS:  Pick the scalefactor #multiple[]# just larger than the
563  * absolute value of the peak subband sample of 12 samples,
564  * and store the corresponding scalefactor index in #scalar#.
565  *
566  * Layer II has three sets of 12-subband samples for a given
567  * subband.
568  *
569  ************************************************************************/
570 
I_scale_factor_calc(sb_sample,scalar,stereo)571 void I_scale_factor_calc(sb_sample,scalar,stereo)
572 double sb_sample[][3][SCALE_BLOCK][SBLIMIT];
573 unsigned int scalar[][3][SBLIMIT];
574 int stereo;
575 {
576    int i,j, k;
577    double s[SBLIMIT];
578 
579    for (k=0;k<stereo;k++) {
580      for (i=0;i<SBLIMIT;i++)
581        for (j=1, s[i] = mod(sb_sample[k][0][0][i]);j<SCALE_BLOCK;j++)
582          if (mod(sb_sample[k][0][j][i]) > s[i])
583             s[i] = mod(sb_sample[k][0][j][i]);
584 
585      for (i=0;i<SBLIMIT;i++)
586        for (j=SCALE_RANGE-2,scalar[k][0][i]=0;j>=0;j--) /* $A 6/16/92 */
587          if (s[i] <= multiple[j]) {
588             scalar[k][0][i] = j;
589             break;
590          }
591    }
592 }
593 
594 /******************************** Layer II ******************************/
595 
II_scale_factor_calc(sb_sample,scalar,stereo,sblimit)596 void II_scale_factor_calc(sb_sample,scalar,stereo,sblimit)
597 double sb_sample[][3][SCALE_BLOCK][SBLIMIT];
598 unsigned int scalar[][3][SBLIMIT];
599 int stereo,sblimit;
600 {
601   int i,j, k,t;
602   double s[SBLIMIT];
603 
604   for (k=0;k<stereo;k++) for (t=0;t<3;t++) {
605     for (i=0;i<sblimit;i++)
606       for (j=1, s[i] = mod(sb_sample[k][t][0][i]);j<SCALE_BLOCK;j++)
607         if (mod(sb_sample[k][t][j][i]) > s[i])
608              s[i] = mod(sb_sample[k][t][j][i]);
609 
610   for (i=0;i<sblimit;i++)
611     for (j=SCALE_RANGE-2,scalar[k][t][i]=0;j>=0;j--)    /* $A 6/16/92 */
612       if (s[i] <= multiple[j]) {
613          scalar[k][t][i] = j;
614          break;
615       }
616       for (i=sblimit;i<SBLIMIT;i++) scalar[k][t][i] = SCALE_RANGE-1;
617     }
618 }
619 
620 /************************************************************************
621  *
622  * pick_scale  (Layer II)
623  *
624  * PURPOSE:For each subband, puts the smallest scalefactor of the 3
625  * associated with a frame into #max_sc#.  This is used
626  * used by Psychoacoustic Model I.
627  * (I would recommend changin max_sc to min_sc)
628  *
629  ************************************************************************/
630 
pick_scale(scalar,fr_ps,max_sc)631 void pick_scale(scalar, fr_ps, max_sc)
632 unsigned int scalar[2][3][SBLIMIT];
633 frame_params *fr_ps;
634 double max_sc[2][SBLIMIT];
635 {
636   int i,j,k,max;
637   int stereo  = fr_ps->stereo;
638   int sblimit = fr_ps->sblimit;
639 
640   for (k=0;k<stereo;k++)
641     for (i=0;i<sblimit;max_sc[k][i] = multiple[max],i++)
642       for (j=1, max = scalar[k][0][i];j<3;j++)
643          if (max > scalar[k][j][i]) max = scalar[k][j][i];
644   for (i=sblimit;i<SBLIMIT;i++) max_sc[0][i] = max_sc[1][i] = 1E-20;
645 }
646 
647 /************************************************************************
648  *
649  * put_scale   (Layer I)
650  *
651  * PURPOSE:Sets #max_sc# to the scalefactor index in #scalar.
652  * This is used by Psychoacoustic Model I
653  *
654  ************************************************************************/
655 
put_scale(scalar,fr_ps,max_sc)656 void put_scale(scalar, fr_ps, max_sc)
657 unsigned int scalar[2][3][SBLIMIT];
658 frame_params *fr_ps;
659 double max_sc[2][SBLIMIT];
660 {
661    int i,k;
662    int stereo  = fr_ps->stereo;
663 
664    for (k=0;k<stereo;k++) for (i=0;i<SBLIMIT;i++)
665         max_sc[k][i] = multiple[scalar[k][0][i]];
666 }
667 
668 /************************************************************************
669  *
670  * II_transmission_pattern (Layer II only)
671  *
672  * PURPOSE:For a given subband, determines whether to send 1, 2, or
673  * all 3 of the scalefactors, and fills in the scalefactor
674  * select information accordingly
675  *
676  * SEMANTICS:  The subbands and channels are classified based on how much
677  * the scalefactors changes over its three values (corresponding
678  * to the 3 sets of 12 samples per subband).  The classification
679  * will send 1 or 2 scalefactors instead of three if the scalefactors
680  * do not change much.  The scalefactor select information,
681  * #scfsi#, is filled in accordingly.
682  *
683  ************************************************************************/
684 
II_transmission_pattern(scalar,scfsi,fr_ps)685 void II_transmission_pattern(scalar, scfsi, fr_ps)
686 unsigned int scalar[2][3][SBLIMIT];
687 unsigned int scfsi[2][SBLIMIT];
688 frame_params *fr_ps;
689 {
690    int stereo  = fr_ps->stereo;
691    int sblimit = fr_ps->sblimit;
692    int dscf[2];
693    int class[2],i,j,k;
694 static int pattern[5][5] = {{0x123, 0x122, 0x122, 0x133, 0x123},
695                             {0x113, 0x111, 0x111, 0x444, 0x113},
696                             {0x111, 0x111, 0x111, 0x333, 0x113},
697                             {0x222, 0x222, 0x222, 0x333, 0x123},
698                             {0x123, 0x122, 0x122, 0x133, 0x123}};
699 
700    for (k=0;k<stereo;k++)
701      for (i=0;i<sblimit;i++) {
702        dscf[0] =  (scalar[k][0][i]-scalar[k][1][i]);
703        dscf[1] =  (scalar[k][1][i]-scalar[k][2][i]);
704        for (j=0;j<2;j++) {
705          if (dscf[j]<=-3) class[j] = 0;
706          else if (dscf[j] > -3 && dscf[j] <0) class[j] = 1;
707               else if (dscf[j] == 0) class[j] = 2;
708                    else if (dscf[j] > 0 && dscf[j] < 3) class[j] = 3;
709                         else class[j] = 4;
710        }
711        switch (pattern[class[0]][class[1]]) {
712          case 0x123 :    scfsi[k][i] = 0;
713                          break;
714          case 0x122 :    scfsi[k][i] = 3;
715                          scalar[k][2][i] = scalar[k][1][i];
716                          break;
717          case 0x133 :    scfsi[k][i] = 3;
718                          scalar[k][1][i] = scalar[k][2][i];
719                          break;
720          case 0x113 :    scfsi[k][i] = 1;
721                          scalar[k][1][i] = scalar[k][0][i];
722                          break;
723          case 0x111 :    scfsi[k][i] = 2;
724                          scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
725                          break;
726          case 0x222 :    scfsi[k][i] = 2;
727                          scalar[k][0][i] = scalar[k][2][i] = scalar[k][1][i];
728                          break;
729          case 0x333 :    scfsi[k][i] = 2;
730                          scalar[k][0][i] = scalar[k][1][i] = scalar[k][2][i];
731                          break;
732          case 0x444 :    scfsi[k][i] = 2;
733                          if (scalar[k][0][i] > scalar[k][2][i])
734                               scalar[k][0][i] = scalar[k][2][i];
735                          scalar[k][1][i] = scalar[k][2][i] = scalar[k][0][i];
736       }
737    }
738 }
739 
740  /************************************************************************
741  *
742  * I_encode_scale  (Layer I)
743  * II_encode_scale (Layer II)
744  *
745  * PURPOSE:The encoded scalar factor information is arranged and
746  * queued into the output fifo to be transmitted.
747  *
748  * For Layer II, the three scale factors associated with
749  * a given subband and channel are transmitted in accordance
750  * with the scfsi, which is transmitted first.
751  *
752  ************************************************************************/
753 
I_encode_scale(scalar,bit_alloc,fr_ps,bs)754 void I_encode_scale(scalar, bit_alloc, fr_ps, bs)
755 unsigned int scalar[2][3][SBLIMIT];
756 unsigned int bit_alloc[2][SBLIMIT];
757 frame_params *fr_ps;
758 Bit_stream_struc *bs;
759 {
760    int stereo  = fr_ps->stereo;
761    int i,j;
762 
763    for (i=0;i<SBLIMIT;i++) for (j=0;j<stereo;j++)
764       if (bit_alloc[j][i]) putbits(bs,scalar[j][0][i],6);
765 }
766 
767 /***************************** Layer II  ********************************/
768 
II_encode_scale(bit_alloc,scfsi,scalar,fr_ps,bs)769 void II_encode_scale(bit_alloc, scfsi, scalar, fr_ps, bs)
770 unsigned int bit_alloc[2][SBLIMIT], scfsi[2][SBLIMIT];
771 unsigned int scalar[2][3][SBLIMIT];
772 frame_params *fr_ps;
773 Bit_stream_struc *bs;
774 {
775    int stereo  = fr_ps->stereo;
776    int sblimit = fr_ps->sblimit;
777    int i,j,k;
778 
779    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
780      if (bit_alloc[k][i])  putbits(bs,scfsi[k][i],2);
781 
782    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++)
783      if (bit_alloc[k][i])  /* above jsbound, bit_alloc[0][i] == ba[1][i] */
784         switch (scfsi[k][i]) {
785            case 0: for (j=0;j<3;j++)
786                      putbits(bs,scalar[k][j][i],6);
787                    break;
788            case 1:
789            case 3: putbits(bs,scalar[k][0][i],6);
790                    putbits(bs,scalar[k][2][i],6);
791                    break;
792            case 2: putbits(bs,scalar[k][0][i],6);
793         }
794 }
795 
796 /*=======================================================================\
797 |                                                                        |
798 |      The following routines are done after the masking threshold       |
799 | has been calculated by the fft analysis routines in the Psychoacoustic |
800 | model. Using the MNR calculated, the actual number of bits allocated   |
801 | to each subband is found iteratively.                                  |
802 |                                                                        |
803 \=======================================================================*/
804 
805 /************************************************************************
806  *
807  * I_bits_for_nonoise  (Layer I)
808  * II_bits_for_nonoise (Layer II)
809  *
810  * PURPOSE:Returns the number of bits required to produce a
811  * mask-to-noise ratio better or equal to the noise/no_noise threshold.
812  *
813  * SEMANTICS:
814  * bbal = # bits needed for encoding bit allocation
815  * bsel = # bits needed for encoding scalefactor select information
816  * banc = # bits needed for ancillary data (header info included)
817  *
818  * For each subband and channel, will add bits until one of the
819  * following occurs:
820  * - Hit maximum number of bits we can allocate for that subband
821  * - MNR is better than or equal to the minimum masking level
822  *   (NOISY_MIN_MNR)
823  * Then the bits required for scalefactors, scfsi, bit allocation,
824  * and the subband samples are tallied (#req_bits#) and returned.
825  *
826  * (NOISY_MIN_MNR) is the smallest MNR a subband can have before it is
827  * counted as 'noisy' by the logic which chooses the number of JS
828  * subbands.
829  *
830  * Joint stereo is supported.
831  *
832  ************************************************************************/
833 
834 static double snr[18] = {0.00, 7.00, 11.00, 16.00, 20.84,
835                          25.28, 31.59, 37.75, 43.84,
836                          49.89, 55.93, 61.96, 67.98, 74.01,
837                          80.03, 86.05, 92.01, 98.01};
838 
I_bits_for_nonoise(perm_smr,fr_ps)839 int I_bits_for_nonoise(perm_smr, fr_ps)
840 double perm_smr[2][SBLIMIT];
841 frame_params *fr_ps;
842 {
843    int i,j,k;
844    int stereo  = fr_ps->stereo;
845    int jsbound = fr_ps->jsbound;
846    int req_bits = 0;
847 
848    /* initial b_anc (header) allocation bits */
849    req_bits = 32 + 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
850 
851    for(i=0; i<SBLIMIT; ++i)
852      for(j=0; j<((i<jsbound)?stereo:1); ++j) {
853        for(k=0;k<14; ++k)
854          if( (-perm_smr[j][i] + snr[k]) >= NOISY_MIN_MNR)
855            break; /* we found enough bits */
856          if(stereo == 2 && i >= jsbound)     /* check other JS channel */
857            for(;k<14; ++k)
858              if( (-perm_smr[1-j][i] + snr[k]) >= NOISY_MIN_MNR) break;
859          if(k>0) req_bits += (k+1)*SCALE_BLOCK + 6*((i>=jsbound)?stereo:1);
860    }
861    return req_bits;
862 }
863 
864 /***************************** Layer II  ********************************/
865 
II_bits_for_nonoise(perm_smr,scfsi,fr_ps)866 int II_bits_for_nonoise(perm_smr, scfsi, fr_ps)
867 double perm_smr[2][SBLIMIT];
868 unsigned int scfsi[2][SBLIMIT];
869 frame_params *fr_ps;
870 {
871    int sb,ch,ba;
872    int stereo  = fr_ps->stereo;
873    int sblimit = fr_ps->sblimit;
874    int jsbound = fr_ps->jsbound;
875    al_table *alloc = fr_ps->alloc;
876    int req_bits = 0, bbal = 0, berr = 0, banc = 32;
877    int maxAlloc, sel_bits, sc_bits, smp_bits;
878 static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
879 
880    /* added 92-08-11 shn */
881    if (fr_ps->header->error_protection) berr=16; else berr=0;
882 
883    for (sb=0; sb<jsbound; ++sb)
884      bbal += stereo * (*alloc)[sb][0].bits;
885    for (sb=jsbound; sb<sblimit; ++sb)
886      bbal += (*alloc)[sb][0].bits;
887    req_bits = banc + bbal + berr;
888 
889    for(sb=0; sb<sblimit; ++sb)
890      for(ch=0; ch<((sb<jsbound)?stereo:1); ++ch) {
891        maxAlloc = (1<<(*alloc)[sb][0].bits)-1;
892        sel_bits = sc_bits = smp_bits = 0;
893        for(ba=0;ba<maxAlloc-1; ++ba)
894          if( (-perm_smr[ch][sb] + snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
895              >= NOISY_MIN_MNR)
896             break;      /* we found enough bits */
897        if(stereo == 2 && sb >= jsbound) /* check other JS channel */
898          for(;ba<maxAlloc-1; ++ba)
899            if( (-perm_smr[1-ch][sb]+ snr[(*alloc)[sb][ba].quant+((ba>0)?1:0)])
900                >= NOISY_MIN_MNR)
901              break;
902        if(ba>0) {
903          smp_bits = SCALE_BLOCK * ((*alloc)[sb][ba].group * (*alloc)[sb][ba].bits);
904          /* scale factor bits required for subband */
905          sel_bits = 2;
906          sc_bits  = 6 * sfsPerScfsi[scfsi[ch][sb]];
907          if(stereo == 2 && sb >= jsbound) {
908            /* each new js sb has L+R scfsis */
909            sel_bits += 2;
910            sc_bits  += 6 * sfsPerScfsi[scfsi[1-ch][sb]];
911          }
912          req_bits += smp_bits+sel_bits+sc_bits;
913        }
914    }
915    return req_bits;
916 }
917 
918 /************************************************************************
919  *
920  * I_main_bit_allocation   (Layer I)
921  * II_main_bit_allocation  (Layer II)
922  *
923  * PURPOSE:For joint stereo mode, determines which of the 4 joint
924  * stereo modes is needed.  Then calls *_a_bit_allocation(), which
925  * allocates bits for each of the subbands until there are no more bits
926  * left, or the MNR is at the noise/no_noise threshold.
927  *
928  * SEMANTICS:
929  *
930  * For joint stereo mode, joint stereo is changed to stereo if
931  * there are enough bits to encode stereo at or better than the
932  * no-noise threshold (NOISY_MIN_MNR).  Otherwise, the system
933  * iteratively allocates less bits by using joint stereo until one
934  * of the following occurs:
935  * - there are no more noisy subbands (MNR >= NOISY_MIN_MNR)
936  * - mode_ext has been reduced to 0, which means that all but the
937  *   lowest 4 subbands have been converted from stereo to joint
938  *   stereo, and no more subbands may be converted
939  *
940  *     This function calls *_bits_for_nonoise() and *_a_bit_allocation().
941  *
942  ************************************************************************/
943 
I_main_bit_allocation(perm_smr,bit_alloc,adb,fr_ps)944 void I_main_bit_allocation(perm_smr, bit_alloc, adb, fr_ps)
945 double perm_smr[2][SBLIMIT];
946 unsigned int bit_alloc[2][SBLIMIT];
947 int *adb;
948 frame_params *fr_ps;
949 {
950    int  noisy_sbs;
951    int  mode, mode_ext, lay, i;
952    int  rq_db;
953 static  int init = 0;
954 
955    if(init == 0) {
956      /* rearrange snr for layer I */
957      snr[2] = snr[3];
958      for (i=3;i<16;i++) snr[i] = snr[i+2];
959      init = 1;
960    }
961 
962    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
963      fr_ps->header->mode = MPG_MD_STEREO;
964      fr_ps->header->mode_ext = 0;
965      fr_ps->jsbound = fr_ps->sblimit;
966      if((rq_db = I_bits_for_nonoise(perm_smr, fr_ps)) > *adb) {
967        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
968        mode_ext = 4;           /* 3 is least severe reduction */
969        lay = fr_ps->header->lay;
970        do {
971           --mode_ext;
972           fr_ps->jsbound = js_bound(lay, mode_ext);
973           rq_db = I_bits_for_nonoise(perm_smr, fr_ps);
974        } while( (rq_db > *adb) && (mode_ext > 0));
975        fr_ps->header->mode_ext = mode_ext;
976      }    /* well we either eliminated noisy sbs or mode_ext == 0 */
977    }
978    noisy_sbs = I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps);
979 }
980 
981 /***************************** Layer II  ********************************/
982 
II_main_bit_allocation(perm_smr,scfsi,bit_alloc,adb,fr_ps)983 void II_main_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps)
984 double perm_smr[2][SBLIMIT];
985 unsigned int scfsi[2][SBLIMIT];
986 unsigned int bit_alloc[2][SBLIMIT];
987 int *adb;
988 frame_params *fr_ps;
989 {
990    int  noisy_sbs;
991    int  mode, mode_ext, lay;
992    int  rq_db;
993 
994    if((mode = fr_ps->actual_mode) == MPG_MD_JOINT_STEREO) {
995      fr_ps->header->mode = MPG_MD_STEREO;
996      fr_ps->header->mode_ext = 0;
997      fr_ps->jsbound = fr_ps->sblimit;
998      if((rq_db=II_bits_for_nonoise(perm_smr, scfsi, fr_ps)) > *adb) {
999        fr_ps->header->mode = MPG_MD_JOINT_STEREO;
1000        mode_ext = 4;           /* 3 is least severe reduction */
1001        lay = fr_ps->header->lay;
1002        do {
1003          --mode_ext;
1004          fr_ps->jsbound = js_bound(lay, mode_ext);
1005          rq_db = II_bits_for_nonoise(perm_smr, scfsi, fr_ps);
1006        } while( (rq_db > *adb) && (mode_ext > 0));
1007        fr_ps->header->mode_ext = mode_ext;
1008      }    /* well we either eliminated noisy sbs or mode_ext == 0 */
1009    }
1010    noisy_sbs = II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps);
1011 }
1012 
1013 /************************************************************************
1014  *
1015  * I_a_bit_allocation  (Layer I)
1016  * II_a_bit_allocation (Layer II)
1017  *
1018  * PURPOSE:Adds bits to the subbands with the lowest mask-to-noise
1019  * ratios, until the maximum number of bits for the subband has
1020  * been allocated.
1021  *
1022  * SEMANTICS:
1023  * 1. Find the subband and channel with the smallest MNR (#min_sb#,
1024  *    and #min_ch#)
1025  * 2. Calculate the increase in bits needed if we increase the bit
1026  *    allocation to the next higher level
1027  * 3. If there are enough bits available for increasing the resolution
1028  *    in #min_sb#, #min_ch#, and the subband has not yet reached its
1029  *    maximum allocation, update the bit allocation, MNR, and bits
1030  *    available accordingly
1031  * 4. Repeat until there are no more bits left, or no more available
1032  *    subbands. (A subband is still available until the maximum
1033  *    number of bits for the subband has been allocated, or there
1034  *    aren't enough bits to go to the next higher resolution in the
1035  *    subband.)
1036  *
1037  ************************************************************************/
1038 
I_a_bit_allocation(perm_smr,bit_alloc,adb,fr_ps)1039 int I_a_bit_allocation(perm_smr, bit_alloc, adb, fr_ps) /* return noisy sbs */
1040 double perm_smr[2][SBLIMIT];
1041 unsigned int bit_alloc[2][SBLIMIT];
1042 int *adb;
1043 frame_params *fr_ps;
1044 {
1045    int i, k, smpl_bits, scale_bits, min_sb, min_ch, oth_ch;
1046    int bspl, bscf, ad, noisy_sbs, bbal ;
1047    double mnr[2][SBLIMIT], small;
1048    char used[2][SBLIMIT];
1049    int stereo  = fr_ps->stereo;
1050    int jsbound = fr_ps->jsbound;
1051 static char init= 0;
1052 static int banc=32, berr=0;
1053 
1054    if (!init) {
1055       init = 1;
1056       if (fr_ps->header->error_protection) berr = 16;  /* added 92-08-11 shn */
1057    }
1058    bbal = 4 * ( (jsbound * stereo) + (SBLIMIT-jsbound) );
1059    *adb -= bbal + berr + banc;
1060    ad= *adb;
1061 
1062    for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++) {
1063      mnr[k][i]=snr[0]-perm_smr[k][i];
1064      bit_alloc[k][i] = 0;
1065      used[k][i] = 0;
1066    }
1067    bspl = bscf = 0;
1068 
1069    do  {
1070      /* locate the subband with minimum SMR */
1071      small = mnr[0][0]+1;    min_sb = -1; min_ch = -1;
1072      for (i=0;i<SBLIMIT;i++) for (k=0;k<stereo;k++)
1073        /* go on only if there are bits left */
1074        if (used[k][i] != 2 && small > mnr[k][i]) {
1075          small = mnr[k][i];
1076          min_sb = i;  min_ch = k;
1077        }
1078      if(min_sb > -1) {   /* there was something to find */
1079        /* first step of bit allocation is biggest */
1080        if (used[min_ch][min_sb])  { smpl_bits = SCALE_BLOCK; scale_bits = 0; }
1081        else                       { smpl_bits = 24; scale_bits = 6; }
1082        if(min_sb >= jsbound)        scale_bits *= stereo;
1083 
1084        /* check to see enough bits were available for */
1085        /* increasing resolution in the minimum band */
1086 
1087        if (ad >= bspl + bscf + scale_bits + smpl_bits) {
1088          bspl += smpl_bits; /* bit for subband sample */
1089          bscf += scale_bits; /* bit for scale factor */
1090          bit_alloc[min_ch][min_sb]++;
1091          used[min_ch][min_sb] = 1; /* subband has bits */
1092          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb]
1093                                + snr[bit_alloc[min_ch][min_sb]];
1094          /* Check if subband has been fully allocated max bits */
1095          if (bit_alloc[min_ch][min_sb] ==  14 ) used[min_ch][min_sb] = 2;
1096        }
1097        else            /* no room to improve this band */
1098          used[min_ch][min_sb] = 2; /*   for allocation anymore */
1099        if(stereo == 2 && min_sb >= jsbound) {
1100          oth_ch = 1-min_ch;  /* joint-st : fix other ch */
1101          bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
1102          used[oth_ch][min_sb] = used[min_ch][min_sb];
1103          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb]
1104                                + snr[bit_alloc[oth_ch][min_sb]];
1105        }
1106      }
1107    } while(min_sb>-1);     /* i.e. still some sub-bands to find */
1108 
1109    /* Calculate the number of bits left, add on to pointed var */
1110    ad -= bspl+bscf;
1111    *adb = ad;
1112 
1113    /* see how many channels are noisy */
1114    noisy_sbs = 0; small = mnr[0][0];
1115    for(k=0; k<stereo; ++k) {
1116      for(i = 0; i< SBLIMIT; ++i) {
1117        if(mnr[k][i] < NOISY_MIN_MNR)   ++noisy_sbs;
1118        if(small > mnr[k][i])           small = mnr[k][i];
1119      }
1120    }
1121    return noisy_sbs;
1122 }
1123 
1124 /***************************** Layer II  ********************************/
1125 
II_a_bit_allocation(perm_smr,scfsi,bit_alloc,adb,fr_ps)1126 int II_a_bit_allocation(perm_smr, scfsi, bit_alloc, adb, fr_ps)
1127 double perm_smr[2][SBLIMIT];
1128 unsigned int scfsi[2][SBLIMIT];
1129 unsigned int bit_alloc[2][SBLIMIT];
1130 int *adb;
1131 frame_params *fr_ps;
1132 {
1133    int i, min_ch, min_sb, oth_ch, k, increment, scale, seli, ba;
1134    int bspl, bscf, bsel, ad, noisy_sbs, bbal=0;
1135    double mnr[2][SBLIMIT], small;
1136    char used[2][SBLIMIT];
1137    int stereo  = fr_ps->stereo;
1138    int sblimit = fr_ps->sblimit;
1139    int jsbound = fr_ps->jsbound;
1140    al_table *alloc = fr_ps->alloc;
1141 static char init= 0;
1142 static int banc=32, berr=0;
1143 static int sfsPerScfsi[] = { 3,2,1,2 };    /* lookup # sfs per scfsi */
1144 
1145    if (!init) {
1146        init = 1;
1147        if (fr_ps->header->error_protection) berr=16; /* added 92-08-11 shn */
1148    }
1149    for (i=0; i<jsbound; ++i)
1150      bbal += stereo * (*alloc)[i][0].bits;
1151    for (i=jsbound; i<sblimit; ++i)
1152      bbal += (*alloc)[i][0].bits;
1153    *adb -= bbal + berr + banc;
1154    ad = *adb;
1155 
1156    for (i=0;i<sblimit;i++) for (k=0;k<stereo;k++) {
1157      mnr[k][i]=snr[0]-perm_smr[k][i];
1158      bit_alloc[k][i] = 0;
1159      used[k][i] = 0;
1160    }
1161    bspl = bscf = bsel = 0;
1162 
1163    do  {
1164      /* locate the subband with minimum SMR */
1165      small = 999999.0; min_sb = -1; min_ch = -1;
1166      for (i=0;i<sblimit;i++) for(k=0;k<stereo;++k)
1167        if (used[k][i]  != 2 && small > mnr[k][i]) {
1168          small = mnr[k][i];
1169          min_sb = i;  min_ch = k;
1170      }
1171      if(min_sb > -1) {   /* there was something to find */
1172        /* find increase in bit allocation in subband [min] */
1173        increment = SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].group *
1174                         (*alloc)[min_sb][bit_alloc[min_ch][min_sb]+1].bits);
1175        if (used[min_ch][min_sb])
1176          increment -= SCALE_BLOCK * ((*alloc)[min_sb][bit_alloc[min_ch][min_sb]].group*
1177                            (*alloc)[min_sb][bit_alloc[min_ch][min_sb]].bits);
1178 
1179        /* scale factor bits required for subband [min] */
1180        oth_ch = 1 - min_ch;    /* above js bound, need both chans */
1181        if (used[min_ch][min_sb]) scale = seli = 0;
1182        else {          /* this channel had no bits or scfs before */
1183          seli = 2;
1184          scale = 6 * sfsPerScfsi[scfsi[min_ch][min_sb]];
1185          if(stereo == 2 && min_sb >= jsbound) {
1186            /* each new js sb has L+R scfsis */
1187            seli += 2;
1188            scale += 6 * sfsPerScfsi[scfsi[oth_ch][min_sb]];
1189          }
1190        }
1191        /* check to see enough bits were available for */
1192        /* increasing resolution in the minimum band */
1193        if (ad >= bspl + bscf + bsel + seli + scale + increment) {
1194          ba = ++bit_alloc[min_ch][min_sb]; /* next up alloc */
1195          bspl += increment;  /* bits for subband sample */
1196          bscf += scale;      /* bits for scale factor */
1197          bsel += seli;       /* bits for scfsi code */
1198          used[min_ch][min_sb] = 1; /* subband has bits */
1199          mnr[min_ch][min_sb] = -perm_smr[min_ch][min_sb] +
1200                                snr[(*alloc)[min_sb][ba].quant+1];
1201          /* Check if subband has been fully allocated max bits */
1202          if (ba >= (1<<(*alloc)[min_sb][0].bits)-1) used[min_ch][min_sb] = 2;
1203        }
1204        else used[min_ch][min_sb] = 2; /* can't increase this alloc */
1205        if(min_sb >= jsbound && stereo == 2) {
1206          /* above jsbound, alloc applies L+R */
1207          ba = bit_alloc[oth_ch][min_sb] = bit_alloc[min_ch][min_sb];
1208          used[oth_ch][min_sb] = used[min_ch][min_sb];
1209          mnr[oth_ch][min_sb] = -perm_smr[oth_ch][min_sb] +
1210                                snr[(*alloc)[min_sb][ba].quant+1];
1211        }
1212      }
1213    } while(min_sb > -1);   /* until could find no channel */
1214    /* Calculate the number of bits left */
1215    ad -= bspl+bscf+bsel;   *adb = ad;
1216    for (i=sblimit;i<SBLIMIT;i++) for (k=0;k<stereo;k++) bit_alloc[k][i]=0;
1217 
1218    noisy_sbs = 0;  small = mnr[0][0];      /* calc worst noise in case */
1219    for(k=0;k<stereo;++k) {
1220      for (i=0;i<sblimit;i++) {
1221        if (small > mnr[k][i]) small = mnr[k][i];
1222        if(mnr[k][i] < NOISY_MIN_MNR) ++noisy_sbs; /* noise is not masked */
1223 
1224      }
1225    }
1226    return noisy_sbs;
1227 }
1228 
1229 /************************************************************************
1230  *
1231  * I_subband_quantization  (Layer I)
1232  * II_subband_quantization (Layer II)
1233  *
1234  * PURPOSE:Quantizes subband samples to appropriate number of bits
1235  *
1236  * SEMANTICS:  Subband samples are divided by their scalefactors, which
1237  * makes the quantization more efficient. The scaled samples are
1238  * quantized by the function a*x+b, where a and b are functions of
1239  * the number of quantization levels. The result is then truncated
1240  * to the appropriate number of bits and the MSB is inverted.
1241  *
1242  * Note that for fractional 2's complement, inverting the MSB for a
1243  * negative number x is equivalent to adding 1 to it.
1244  *
1245  ************************************************************************/
1246 
1247 static double a[17] = {
1248   0.750000000, 0.625000000, 0.875000000, 0.562500000, 0.937500000,
1249   0.968750000, 0.984375000, 0.992187500, 0.996093750, 0.998046875,
1250   0.999023438, 0.999511719, 0.999755859, 0.999877930, 0.999938965,
1251   0.999969482, 0.999984741 };
1252 
1253 static double b[17] = {
1254   -0.250000000, -0.375000000, -0.125000000, -0.437500000, -0.062500000,
1255   -0.031250000, -0.015625000, -0.007812500, -0.003906250, -0.001953125,
1256   -0.000976563, -0.000488281, -0.000244141, -0.000122070, -0.000061035,
1257   -0.000030518, -0.000015259 };
1258 
I_subband_quantization(scalar,sb_samples,j_scale,j_samps,bit_alloc,sbband,fr_ps)1259 void I_subband_quantization(scalar, sb_samples, j_scale, j_samps,
1260                             bit_alloc, sbband, fr_ps)
1261 unsigned int scalar[2][3][SBLIMIT];
1262 double sb_samples[2][3][SCALE_BLOCK][SBLIMIT];
1263 unsigned int j_scale[3][SBLIMIT];
1264 double j_samps[3][SCALE_BLOCK][SBLIMIT]; /* L+R for j-stereo if necess */
1265 unsigned int bit_alloc[2][SBLIMIT];
1266 unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT];
1267 frame_params *fr_ps;
1268 {
1269    int i, j, k, n, sig;
1270    int stereo  = fr_ps->stereo;
1271    int jsbound = fr_ps->jsbound;
1272    double d;
1273 static char init = 0;
1274 
1275    if (!init) {
1276      init = 1;
1277      /* rearrange quantization coef to correspond to layer I table */
1278      a[1] = a[2]; b[1] = b[2];
1279      for (i=2;i<15;i++) { a[i] = a[i+2]; b[i] = b[i+2]; }
1280    }
1281    for (j=0;j<SCALE_BLOCK;j++) for (i=0;i<SBLIMIT;i++)
1282      for (k=0;k<((i<jsbound)?stereo:1);k++)
1283        if (bit_alloc[k][i]) {
1284          /* for joint stereo mode, have to construct a single subband stream
1285             for the js channels.  At present, we calculate a set of mono
1286             subband samples and pass them through the scaling system to
1287             generate an alternate normalised sample stream.
1288 
1289             Could normalise both streams (divide by their scfs), then average
1290             them.  In bad conditions, this could give rise to spurious
1291             cancellations.  Instead, we could just select the sb stream from
1292             the larger channel (higher scf), in which case _that_ channel
1293             would be 'properly' reconstructed, and the mate would just be a
1294             scaled version.  Spec recommends averaging the two (unnormalised)
1295             subband channels, then normalising this new signal without
1296             actually sending this scale factor... This means looking ahead.
1297          */
1298          if(stereo == 2 && i>=jsbound)
1299            /* use the joint data passed in */
1300            d = j_samps[0][j][i] / multiple[j_scale[0][i]];
1301          else
1302            d = sb_samples[k][0][j][i] / multiple[scalar[k][0][i]];
1303          /* scale and quantize floating point sample */
1304          n = bit_alloc[k][i];
1305          d = d * a[n-1] + b[n-1];
1306          /* extract MSB N-1 bits from the floating point sample */
1307          if (d >= 0) sig = 1;
1308          else { sig = 0; d += 1.0; }
1309          sbband[k][0][j][i] = (unsigned int) (d * (double) (1L<<n));
1310          /* tag the inverted sign bit to sbband at position N */
1311          if (sig) sbband[k][0][j][i] |= 1<<n;
1312        }
1313 }
1314 
1315 /***************************** Layer II  ********************************/
1316 
II_subband_quantization(scalar,sb_samples,j_scale,j_samps,bit_alloc,sbband,fr_ps)1317 void II_subband_quantization(scalar, sb_samples, j_scale, j_samps,
1318                              bit_alloc, sbband, fr_ps)
1319 unsigned int scalar[2][3][SBLIMIT];
1320 double sb_samples[2][3][SCALE_BLOCK][SBLIMIT];
1321 unsigned int j_scale[3][SBLIMIT];
1322 double j_samps[3][SCALE_BLOCK][SBLIMIT];
1323 unsigned int bit_alloc[2][SBLIMIT];
1324 unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT];
1325 frame_params *fr_ps;
1326 {
1327    int i, j, k, s, n, qnt, sig;
1328    int stereo  = fr_ps->stereo;
1329    int sblimit = fr_ps->sblimit;
1330    int jsbound = fr_ps->jsbound;
1331    unsigned int stps;
1332    double d;
1333    al_table *alloc = fr_ps->alloc;
1334 
1335    for (s=0;s<3;s++)
1336      for (j=0;j<SCALE_BLOCK;j++)
1337        for (i=0;i<sblimit;i++)
1338          for (k=0;k<((i<jsbound)?stereo:1);k++)
1339            if (bit_alloc[k][i]) {
1340              /* scale and quantize floating point sample */
1341              if(stereo == 2 && i>=jsbound)       /* use j-stereo samples */
1342                d = j_samps[s][j][i] / multiple[j_scale[s][i]];
1343              else
1344                d = sb_samples[k][s][j][i] / multiple[scalar[k][s][i]];
1345              if (mod(d) > 1.0)
1346 				 mjpeg_info("Not scaled properly %d %d %d %d",k,s,j,i);
1347              qnt = (*alloc)[i][bit_alloc[k][i]].quant;
1348              d = d * a[qnt] + b[qnt];
1349              /* extract MSB N-1 bits from the floating point sample */
1350              if (d >= 0) sig = 1;
1351              else { sig = 0; d += 1.0; }
1352              n = 0;
1353              stps = (*alloc)[i][bit_alloc[k][i]].steps;
1354              while ((1L<<n) < stps) n++;
1355              n--;
1356              sbband[k][s][j][i] = (unsigned int) (d * (double) (1L<<n));
1357              /* tag the inverted sign bit to sbband at position N */
1358              /* The bit inversion is a must for grouping with 3,5,9 steps
1359                 so it is done for all subbands */
1360              if (sig) sbband[k][s][j][i] |= 1<<n;
1361            }
1362            for (s=0;s<3;s++)
1363              for (j=sblimit;j<SBLIMIT;j++)
1364                for (i=0;i<SCALE_BLOCK;i++) for (k=0;k<stereo;k++) sbband[k][s][i][j] = 0;
1365 }
1366 
1367 /************************************************************************
1368  *
1369  * I_encode_bit_alloc  (Layer I)
1370  * II_encode_bit_alloc (Layer II)
1371  *
1372  * PURPOSE:Writes bit allocation information onto bitstream
1373  *
1374  * Layer I uses 4 bits/subband for bit allocation information,
1375  * and Layer II uses 4,3,2, or 0 bits depending on the
1376  * quantization table used.
1377  *
1378  ************************************************************************/
1379 
I_encode_bit_alloc(bit_alloc,fr_ps,bs)1380 void I_encode_bit_alloc(bit_alloc, fr_ps, bs)
1381 unsigned int bit_alloc[2][SBLIMIT];
1382 frame_params *fr_ps;
1383 Bit_stream_struc *bs;
1384 {
1385    int i,k;
1386    int stereo  = fr_ps->stereo;
1387    int jsbound = fr_ps->jsbound;
1388 
1389    for (i=0;i<SBLIMIT;i++)
1390      for (k=0;k<((i<jsbound)?stereo:1);k++) putbits(bs,bit_alloc[k][i],4);
1391 }
1392 
1393 /***************************** Layer II  ********************************/
1394 
II_encode_bit_alloc(bit_alloc,fr_ps,bs)1395 void II_encode_bit_alloc(bit_alloc, fr_ps, bs)
1396 unsigned int bit_alloc[2][SBLIMIT];
1397 frame_params *fr_ps;
1398 Bit_stream_struc *bs;
1399 {
1400    int i,k;
1401    int stereo  = fr_ps->stereo;
1402    int sblimit = fr_ps->sblimit;
1403    int jsbound = fr_ps->jsbound;
1404    al_table *alloc = fr_ps->alloc;
1405 
1406    for (i=0;i<sblimit;i++)
1407      for (k=0;k<((i<jsbound)?stereo:1);k++)
1408        putbits(bs,bit_alloc[k][i],(*alloc)[i][0].bits);
1409 }
1410 
1411 /************************************************************************
1412  *
1413  * I_sample_encoding   (Layer I)
1414  * II_sample_encoding  (Layer II)
1415  *
1416  * PURPOSE:Put one frame of subband samples on to the bitstream
1417  *
1418  * SEMANTICS:  The number of bits allocated per sample is read from
1419  * the bit allocation information #bit_alloc#.  Layer 2
1420  * supports writing grouped samples for quantization steps
1421  * that are not a power of 2.
1422  *
1423  ************************************************************************/
1424 
I_sample_encoding(sbband,bit_alloc,fr_ps,bs)1425 void I_sample_encoding(sbband, bit_alloc, fr_ps, bs)
1426 unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT];
1427 unsigned int bit_alloc[2][SBLIMIT];
1428 frame_params *fr_ps;
1429 Bit_stream_struc *bs;
1430 {
1431    int i,j,k;
1432    int stereo  = fr_ps->stereo;
1433    int jsbound = fr_ps->jsbound;
1434 
1435    for(j=0;j<SCALE_BLOCK;j++) {
1436      for(i=0;i<SBLIMIT;i++)
1437        for(k=0;k<((i<jsbound)?stereo:1);k++)
1438          if(bit_alloc[k][i]) putbits(bs,sbband[k][0][j][i],bit_alloc[k][i]+1);
1439    }
1440 }
1441 
1442 /***************************** Layer II  ********************************/
1443 
II_sample_encoding(sbband,bit_alloc,fr_ps,bs)1444 void II_sample_encoding(sbband, bit_alloc, fr_ps, bs)
1445 unsigned int sbband[2][3][SCALE_BLOCK][SBLIMIT];
1446 unsigned int bit_alloc[2][SBLIMIT];
1447 frame_params *fr_ps;
1448 Bit_stream_struc *bs;
1449 {
1450    unsigned int temp;
1451    unsigned int i,j,k,s,x,y;
1452    int stereo  = fr_ps->stereo;
1453    int sblimit = fr_ps->sblimit;
1454    int jsbound = fr_ps->jsbound;
1455    al_table *alloc = fr_ps->alloc;
1456 
1457    for (s=0;s<3;s++)
1458      for (j=0;j<SCALE_BLOCK;j+=3)
1459        for (i=0;i<sblimit;i++)
1460          for (k=0;k<((i<jsbound)?stereo:1);k++)
1461            if (bit_alloc[k][i]) {
1462              if ((*alloc)[i][bit_alloc[k][i]].group == 3) {
1463                for (x=0;x<3;x++) putbits(bs,sbband[k][s][j+x][i],
1464                                          (*alloc)[i][bit_alloc[k][i]].bits);
1465              }
1466              else {
1467                y =(*alloc)[i][bit_alloc[k][i]].steps;
1468                temp = sbband[k][s][j][i] +
1469                       sbband[k][s][j+1][i] * y +
1470                       sbband[k][s][j+2][i] * y * y;
1471                putbits(bs,temp,(*alloc)[i][bit_alloc[k][i]].bits);
1472              }
1473            }
1474 }
1475 
1476 /************************************************************************
1477  *
1478  * encode_CRC
1479  *
1480  ************************************************************************/
1481 
encode_CRC(crc,bs)1482 void encode_CRC(crc, bs)
1483 unsigned int crc;
1484 Bit_stream_struc *bs;
1485 {
1486    putbits(bs, crc, 16);
1487 }
1488