Add code to prevent heap attacks by exploiting dim=bignum and
[platform/upstream/libvorbis.git] / lib / res0.c
1 /********************************************************************
2  *                                                                  *
3  * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE.   *
4  * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS     *
5  * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
6  * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING.       *
7  *                                                                  *
8  * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007             *
9  * by the Xiph.Org Foundation http://www.xiph.org/                  *
10  *                                                                  *
11  ********************************************************************
12
13  function: residue backend 0, 1 and 2 implementation
14  last mod: $Id$
15
16  ********************************************************************/
17
18 /* Slow, slow, slow, simpleminded and did I mention it was slow?  The
19    encode/decode loops are coded for clarity and performance is not
20    yet even a nagging little idea lurking in the shadows.  Oh and BTW,
21    it's slow. */
22
23 #include <stdlib.h>
24 #include <string.h>
25 #include <math.h>
26 #include <ogg/ogg.h>
27 #include "vorbis/codec.h"
28 #include "codec_internal.h"
29 #include "registry.h"
30 #include "codebook.h"
31 #include "misc.h"
32 #include "os.h"
33
34 #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
35 #include <stdio.h>
36 #endif 
37
38 typedef struct {
39   vorbis_info_residue0 *info;
40   
41   int         parts;
42   int         stages;
43   codebook   *fullbooks;
44   codebook   *phrasebook;
45   codebook ***partbooks;
46
47   int         partvals;
48   int       **decodemap;
49
50   long      postbits;
51   long      phrasebits;
52   long      frames;
53
54 #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
55   int        train_seq;
56   long      *training_data[8][64];
57   float      training_max[8][64];
58   float      training_min[8][64];
59   float     tmin;
60   float     tmax;
61 #endif
62
63 } vorbis_look_residue0;
64
65 void res0_free_info(vorbis_info_residue *i){
66   vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
67   if(info){
68     memset(info,0,sizeof(*info));
69     _ogg_free(info);
70   }
71 }
72
73 void res0_free_look(vorbis_look_residue *i){
74   int j;
75   if(i){
76
77     vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
78
79 #ifdef TRAIN_RES
80     {
81       int j,k,l;
82       for(j=0;j<look->parts;j++){
83         /*fprintf(stderr,"partition %d: ",j);*/
84         for(k=0;k<8;k++)
85           if(look->training_data[k][j]){
86             char buffer[80];
87             FILE *of;
88             codebook *statebook=look->partbooks[j][k];
89             
90             /* long and short into the same bucket by current convention */
91             sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
92             of=fopen(buffer,"a");
93
94             for(l=0;l<statebook->entries;l++)
95               fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
96             
97             fclose(of);
98             
99             /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
100               look->training_min[k][j],look->training_max[k][j]);*/
101
102             _ogg_free(look->training_data[k][j]);
103             look->training_data[k][j]=NULL;
104           }
105         /*fprintf(stderr,"\n");*/
106       }
107     }
108     fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
109
110     /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
111             (float)look->phrasebits/look->frames,
112             (float)look->postbits/look->frames,
113             (float)(look->postbits+look->phrasebits)/look->frames);*/
114 #endif
115
116
117     /*vorbis_info_residue0 *info=look->info;
118
119     fprintf(stderr,
120             "%ld frames encoded in %ld phrasebits and %ld residue bits "
121             "(%g/frame) \n",look->frames,look->phrasebits,
122             look->resbitsflat,
123             (look->phrasebits+look->resbitsflat)/(float)look->frames);
124     
125     for(j=0;j<look->parts;j++){
126       long acc=0;
127       fprintf(stderr,"\t[%d] == ",j);
128       for(k=0;k<look->stages;k++)
129         if((info->secondstages[j]>>k)&1){
130           fprintf(stderr,"%ld,",look->resbits[j][k]);
131           acc+=look->resbits[j][k];
132         }
133
134       fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
135               acc?(float)acc/(look->resvals[j]*info->grouping):0);
136     }
137     fprintf(stderr,"\n");*/
138
139     for(j=0;j<look->parts;j++)
140       if(look->partbooks[j])_ogg_free(look->partbooks[j]);
141     _ogg_free(look->partbooks);
142     for(j=0;j<look->partvals;j++)
143       _ogg_free(look->decodemap[j]);
144     _ogg_free(look->decodemap);
145
146     memset(look,0,sizeof(*look));
147     _ogg_free(look);
148   }
149 }
150
151 static int ilog(unsigned int v){
152   int ret=0;
153   while(v){
154     ret++;
155     v>>=1;
156   }
157   return(ret);
158 }
159
160 static int icount(unsigned int v){
161   int ret=0;
162   while(v){
163     ret+=v&1;
164     v>>=1;
165   }
166   return(ret);
167 }
168
169
170 void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
171   vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
172   int j,acc=0;
173   oggpack_write(opb,info->begin,24);
174   oggpack_write(opb,info->end,24);
175
176   oggpack_write(opb,info->grouping-1,24);  /* residue vectors to group and 
177                                              code with a partitioned book */
178   oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
179   oggpack_write(opb,info->groupbook,8);  /* group huffman book */
180
181   /* secondstages is a bitmask; as encoding progresses pass by pass, a
182      bitmask of one indicates this partition class has bits to write
183      this pass */
184   for(j=0;j<info->partitions;j++){
185     if(ilog(info->secondstages[j])>3){
186       /* yes, this is a minor hack due to not thinking ahead */
187       oggpack_write(opb,info->secondstages[j],3); 
188       oggpack_write(opb,1,1);
189       oggpack_write(opb,info->secondstages[j]>>3,5); 
190     }else
191       oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
192     acc+=icount(info->secondstages[j]);
193   }
194   for(j=0;j<acc;j++)
195     oggpack_write(opb,info->booklist[j],8);
196
197 }
198
199 /* vorbis_info is for range checking */
200 vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
201   int j,acc=0;
202   vorbis_info_residue0 *info=_ogg_calloc(1,sizeof(*info));
203   codec_setup_info     *ci=vi->codec_setup;
204
205   info->begin=oggpack_read(opb,24);
206   info->end=oggpack_read(opb,24);
207   info->grouping=oggpack_read(opb,24)+1;
208   info->partitions=oggpack_read(opb,6)+1;
209   info->groupbook=oggpack_read(opb,8);
210
211   for(j=0;j<info->partitions;j++){
212     int cascade=oggpack_read(opb,3);
213     if(oggpack_read(opb,1))
214       cascade|=(oggpack_read(opb,5)<<3);
215     info->secondstages[j]=cascade;
216
217     acc+=icount(cascade);
218   }
219   for(j=0;j<acc;j++)
220     info->booklist[j]=oggpack_read(opb,8);
221
222   if(info->groupbook>=ci->books)goto errout;
223   for(j=0;j<acc;j++)
224     if(info->booklist[j]>=ci->books)goto errout;
225
226   /* verify the phrasebook is not specifying an impossible or
227      inconsistent partitioning scheme. */
228   {
229     int entries = ci->book_param[info->groupbook]->entries;
230     int dim = ci->book_param[info->groupbook]->dim;
231     int partvals = 1;
232     while(dim>0){
233       partvals *= info->partitions;
234       if(partvals > entries) goto errout;
235       dim--;
236     }
237     if(partvals != entries) goto errout;
238   }
239
240   return(info);
241  errout:
242   res0_free_info(info);
243   return(NULL);
244 }
245
246 vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
247                                vorbis_info_residue *vr){
248   vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
249   vorbis_look_residue0 *look=_ogg_calloc(1,sizeof(*look));
250   codec_setup_info     *ci=vd->vi->codec_setup;
251
252   int j,k,acc=0;
253   int dim;
254   int maxstage=0;
255   look->info=info;
256
257   look->parts=info->partitions;
258   look->fullbooks=ci->fullbooks;
259   look->phrasebook=ci->fullbooks+info->groupbook;
260   dim=look->phrasebook->dim;
261
262   look->partbooks=_ogg_calloc(look->parts,sizeof(*look->partbooks));
263
264   for(j=0;j<look->parts;j++){
265     int stages=ilog(info->secondstages[j]);
266     if(stages){
267       if(stages>maxstage)maxstage=stages;
268       look->partbooks[j]=_ogg_calloc(stages,sizeof(*look->partbooks[j]));
269       for(k=0;k<stages;k++)
270         if(info->secondstages[j]&(1<<k)){
271           look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
272 #ifdef TRAIN_RES
273           look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
274                                            sizeof(***look->training_data));
275 #endif
276         }
277     }
278   }
279
280   look->partvals=look->phrasebook->entries;
281   look->stages=maxstage;
282   look->decodemap=_ogg_malloc(look->partvals*sizeof(*look->decodemap));
283   for(j=0;j<look->partvals;j++){
284     long val=j;
285     long mult=look->partvals/look->parts;
286     look->decodemap[j]=_ogg_malloc(dim*sizeof(*look->decodemap[j]));
287     for(k=0;k<dim;k++){
288       long deco=val/mult;
289       val-=deco*mult;
290       mult/=look->parts;
291       look->decodemap[j][k]=deco;
292     }
293   }
294 #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
295   {
296     static int train_seq=0;
297     look->train_seq=train_seq++;
298   }
299 #endif
300   return(look);
301 }
302
303 /* break an abstraction and copy some code for performance purposes */
304 static int local_book_besterror(codebook *book,float *a){
305   int dim=book->dim,i,k,o;
306   int best=0;
307   encode_aux_threshmatch *tt=book->c->thresh_tree;
308
309   /* find the quant val of each scalar */
310   for(k=0,o=dim;k<dim;++k){
311     float val=a[--o];
312     i=tt->threshvals>>1;
313
314     if(val<tt->quantthresh[i]){      
315       if(val<tt->quantthresh[i-1]){
316         for(--i;i>0;--i)
317           if(val>=tt->quantthresh[i-1])
318             break;
319       }
320     }else{
321       
322       for(++i;i<tt->threshvals-1;++i)
323         if(val<tt->quantthresh[i])break;
324       
325     }
326
327     best=(best*tt->quantvals)+tt->quantmap[i];
328   }
329   /* regular lattices are easy :-) */
330   
331   if(book->c->lengthlist[best]<=0){
332     const static_codebook *c=book->c;
333     int i,j;
334     float bestf=0.f;
335     float *e=book->valuelist;
336     best=-1;
337     for(i=0;i<book->entries;i++){
338       if(c->lengthlist[i]>0){
339         float this=0.f;
340         for(j=0;j<dim;j++){
341           float val=(e[j]-a[j]);
342           this+=val*val;
343         }
344         if(best==-1 || this<bestf){
345           bestf=this;
346           best=i;
347         }
348       }
349       e+=dim;
350     }
351   }
352
353   if(best>-1){
354     float *ptr=book->valuelist+best*dim;
355     for(i=0;i<dim;i++)
356       *a++ -= *ptr++;
357   }
358
359   return(best);
360 }
361
362 static int _encodepart(oggpack_buffer *opb,float *vec, int n,
363                        codebook *book,long *acc){
364   int i,bits=0;
365   int dim=book->dim;
366   int step=n/dim;
367
368   for(i=0;i<step;i++){
369     int entry=local_book_besterror(book,vec+i*dim);
370
371 #ifdef TRAIN_RES
372     if(entry>0)
373       acc[entry]++;
374 #endif
375       
376     bits+=vorbis_book_encode(book,entry,opb);
377   
378   }
379
380   return(bits);
381 }
382
383 static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
384                        float **in,int ch){
385   long i,j,k;
386   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
387   vorbis_info_residue0 *info=look->info;
388   vorbis_info           *vi=vb->vd->vi;
389
390   /* move all this setup out later */
391   int samples_per_partition=info->grouping;
392   int possible_partitions=info->partitions;
393   int n=info->end-info->begin;
394   
395   int partvals=n/samples_per_partition;
396   long **partword=_vorbis_block_alloc(vb,ch*sizeof(*partword));
397   float scale=100./samples_per_partition;
398   
399   /* we find the partition type for each partition of each
400      channel.  We'll go back and do the interleaved encoding in a
401      bit.  For now, clarity */
402   
403   for(i=0;i<ch;i++){
404     partword[i]=_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
405     memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
406   }
407   
408   for(i=0;i<partvals;i++){
409     int offset=i*samples_per_partition+info->begin;
410     for(j=0;j<ch;j++){
411       float max=0.;
412       float ent=0.;
413       for(k=0;k<samples_per_partition;k++){
414         if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
415         ent+=fabs(rint(in[j][offset+k]));
416       }
417       ent*=scale;
418       
419       for(k=0;k<possible_partitions-1;k++)
420         if(max<=info->classmetric1[k] &&
421            (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
422           break;
423       
424       partword[j][i]=k;  
425     }
426   }
427   
428 #ifdef TRAIN_RESAUX
429   {
430     FILE *of;
431     char buffer[80];
432     
433     for(i=0;i<ch;i++){
434       sprintf(buffer,"resaux_%d.vqd",look->train_seq);
435       of=fopen(buffer,"a");
436       for(j=0;j<partvals;j++)
437         fprintf(of,"%ld, ",partword[i][j]);
438       fprintf(of,"\n");
439       fclose(of);
440     }
441   }
442 #endif
443   look->frames++;
444   
445   return(partword);
446 }
447
448 /* designed for stereo or other modes where the partition size is an
449    integer multiple of the number of channels encoded in the current
450    submap */
451 static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
452                       int ch){
453   long i,j,k,l;
454   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
455   vorbis_info_residue0 *info=look->info;
456
457   /* move all this setup out later */
458   int samples_per_partition=info->grouping;
459   int possible_partitions=info->partitions;
460   int n=info->end-info->begin;
461
462   int partvals=n/samples_per_partition;
463   long **partword=_vorbis_block_alloc(vb,sizeof(*partword));
464   
465 #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
466   FILE *of;
467   char buffer[80];
468 #endif
469   
470   partword[0]=_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
471   memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
472   
473   for(i=0,l=info->begin/ch;i<partvals;i++){
474     float magmax=0.f;
475     float angmax=0.f;
476     for(j=0;j<samples_per_partition;j+=ch){
477       if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
478       for(k=1;k<ch;k++)
479         if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
480         l++;
481     }
482     
483     for(j=0;j<possible_partitions-1;j++)
484       if(magmax<=info->classmetric1[j] &&
485          angmax<=info->classmetric2[j])
486         break;
487     
488     partword[0][i]=j;
489     
490   }  
491   
492 #ifdef TRAIN_RESAUX
493   sprintf(buffer,"resaux_%d.vqd",look->train_seq);
494   of=fopen(buffer,"a");
495   for(i=0;i<partvals;i++)
496     fprintf(of,"%ld, ",partword[0][i]);
497   fprintf(of,"\n");
498   fclose(of);
499 #endif
500   
501   look->frames++;
502   
503   return(partword);
504 }
505
506 static int _01forward(oggpack_buffer *opb,
507                       vorbis_block *vb,vorbis_look_residue *vl,
508                       float **in,int ch,
509                       long **partword,
510                       int (*encode)(oggpack_buffer *,float *,int,
511                                     codebook *,long *)){
512   long i,j,k,s;
513   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
514   vorbis_info_residue0 *info=look->info;
515
516   vorbis_dsp_state      *vd=vb->vd;
517
518   /* move all this setup out later */
519   int samples_per_partition=info->grouping;
520   int possible_partitions=info->partitions;
521   int partitions_per_word=look->phrasebook->dim;
522   int n=info->end-info->begin;
523
524   int partvals=n/samples_per_partition;
525   long resbits[128];
526   long resvals[128];
527   
528 #ifdef TRAIN_RES
529   for(i=0;i<ch;i++)
530     for(j=info->begin;j<end;j++){
531       if(in[i][j]>look->tmax)look->tmax=in[i][j];
532       if(in[i][j]<look->tmin)look->tmin=in[i][j];
533     }
534 #endif
535   
536   memset(resbits,0,sizeof(resbits));
537   memset(resvals,0,sizeof(resvals));
538   
539   /* we code the partition words for each channel, then the residual
540      words for a partition per channel until we've written all the
541      residual words for that partition word.  Then write the next
542      partition channel words... */
543   
544   for(s=0;s<look->stages;s++){
545     
546     for(i=0;i<partvals;){
547       
548       /* first we encode a partition codeword for each channel */
549       if(s==0){
550         for(j=0;j<ch;j++){
551           long val=partword[j][i];
552           for(k=1;k<partitions_per_word;k++){
553             val*=possible_partitions;
554             if(i+k<partvals)
555               val+=partword[j][i+k];
556           }     
557           
558           /* training hack */
559           if(val<look->phrasebook->entries)
560             look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
561 #if 0 /*def TRAIN_RES*/
562           else
563             fprintf(stderr,"!");
564 #endif
565           
566         }
567       }
568       
569       /* now we encode interleaved residual values for the partitions */
570       for(k=0;k<partitions_per_word && i<partvals;k++,i++){
571         long offset=i*samples_per_partition+info->begin;
572           
573         for(j=0;j<ch;j++){
574           if(s==0)resvals[partword[j][i]]+=samples_per_partition;
575           if(info->secondstages[partword[j][i]]&(1<<s)){
576             codebook *statebook=look->partbooks[partword[j][i]][s];
577             if(statebook){
578               int ret;
579               long *accumulator=NULL;
580               
581 #ifdef TRAIN_RES
582               accumulator=look->training_data[s][partword[j][i]];
583               {
584                 int l;
585                 float *samples=in[j]+offset;
586                 for(l=0;l<samples_per_partition;l++){
587                   if(samples[l]<look->training_min[s][partword[j][i]])
588                     look->training_min[s][partword[j][i]]=samples[l];
589                   if(samples[l]>look->training_max[s][partword[j][i]])
590                     look->training_max[s][partword[j][i]]=samples[l];
591                 }
592               }
593 #endif
594               
595               ret=encode(opb,in[j]+offset,samples_per_partition,
596                          statebook,accumulator);
597               
598               look->postbits+=ret;
599               resbits[partword[j][i]]+=ret;
600             }
601           }
602         }
603       }
604     }
605   }
606   
607   /*{
608     long total=0;
609     long totalbits=0;
610     fprintf(stderr,"%d :: ",vb->mode);
611     for(k=0;k<possible_partitions;k++){
612     fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
613     total+=resvals[k];
614     totalbits+=resbits[k];
615     }
616     
617     fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
618     }*/
619
620   return(0);
621 }
622
623 /* a truncated packet here just means 'stop working'; it's not an error */
624 static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
625                       float **in,int ch,
626                       long (*decodepart)(codebook *, float *, 
627                                          oggpack_buffer *,int)){
628
629   long i,j,k,l,s;
630   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
631   vorbis_info_residue0 *info=look->info;
632
633   /* move all this setup out later */
634   int samples_per_partition=info->grouping;
635   int partitions_per_word=look->phrasebook->dim;
636   int max=vb->pcmend>>1;
637   int end=(info->end<max?info->end:max);
638   int n=end-info->begin;
639   
640   if(n>0){
641     int partvals=n/samples_per_partition;
642     int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
643     int ***partword=alloca(ch*sizeof(*partword));
644     
645     for(j=0;j<ch;j++)
646       partword[j]=_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
647     
648     for(s=0;s<look->stages;s++){
649       
650       /* each loop decodes on partition codeword containing 
651          partitions_per_word partitions */
652       for(i=0,l=0;i<partvals;l++){
653         if(s==0){
654           /* fetch the partition word for each channel */
655           for(j=0;j<ch;j++){
656             int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
657             
658             if(temp==-1)goto eopbreak;
659             partword[j][l]=look->decodemap[temp];
660             if(partword[j][l]==NULL)goto errout;
661           }
662         }
663         
664         /* now we decode residual values for the partitions */
665         for(k=0;k<partitions_per_word && i<partvals;k++,i++)
666           for(j=0;j<ch;j++){
667             long offset=info->begin+i*samples_per_partition;
668             if(info->secondstages[partword[j][l][k]]&(1<<s)){
669               codebook *stagebook=look->partbooks[partword[j][l][k]][s];
670               if(stagebook){
671                 if(decodepart(stagebook,in[j]+offset,&vb->opb,
672                               samples_per_partition)==-1)goto eopbreak;
673               }
674             }
675           }
676       } 
677     }
678   }
679  errout:
680  eopbreak:
681   return(0);
682 }
683
684 #if 0
685 /* residue 0 and 1 are just slight variants of one another. 0 is
686    interleaved, 1 is not */
687 long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
688                   float **in,int *nonzero,int ch){
689   /* we encode only the nonzero parts of a bundle */
690   int i,used=0;
691   for(i=0;i<ch;i++)
692     if(nonzero[i])
693       in[used++]=in[i];
694   if(used)
695     /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
696     return(_01class(vb,vl,in,used));
697   else
698     return(0);
699 }
700
701 int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
702                  float **in,float **out,int *nonzero,int ch,
703                  long **partword){
704   /* we encode only the nonzero parts of a bundle */
705   int i,j,used=0,n=vb->pcmend/2;
706   for(i=0;i<ch;i++)
707     if(nonzero[i]){
708       if(out)
709         for(j=0;j<n;j++)
710           out[i][j]+=in[i][j];
711       in[used++]=in[i];
712     }
713   if(used){
714     int ret=_01forward(vb,vl,in,used,partword,
715                       _interleaved_encodepart);
716     if(out){
717       used=0;
718       for(i=0;i<ch;i++)
719         if(nonzero[i]){
720           for(j=0;j<n;j++)
721             out[i][j]-=in[used][j];
722           used++;
723         }
724     }
725     return(ret);
726   }else{
727     return(0);
728   }
729 }
730 #endif
731
732 int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
733                  float **in,int *nonzero,int ch){
734   int i,used=0;
735   for(i=0;i<ch;i++)
736     if(nonzero[i])
737       in[used++]=in[i];
738   if(used)
739     return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
740   else
741     return(0);
742 }
743
744 int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
745                  float **in,float **out,int *nonzero,int ch,
746                  long **partword){
747   int i,j,used=0,n=vb->pcmend/2;
748   for(i=0;i<ch;i++)
749     if(nonzero[i]){
750       if(out)
751         for(j=0;j<n;j++)
752           out[i][j]+=in[i][j];
753       in[used++]=in[i];
754     }
755
756   if(used){
757     int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
758     if(out){
759       used=0;
760       for(i=0;i<ch;i++)
761         if(nonzero[i]){
762           for(j=0;j<n;j++)
763             out[i][j]-=in[used][j];
764           used++;
765         }
766     }
767     return(ret);
768   }else{
769     return(0);
770   }
771 }
772
773 long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
774                   float **in,int *nonzero,int ch){
775   int i,used=0;
776   for(i=0;i<ch;i++)
777     if(nonzero[i])
778       in[used++]=in[i];
779   if(used)
780     return(_01class(vb,vl,in,used));
781   else
782     return(0);
783 }
784
785 int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
786                  float **in,int *nonzero,int ch){
787   int i,used=0;
788   for(i=0;i<ch;i++)
789     if(nonzero[i])
790       in[used++]=in[i];
791   if(used)
792     return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
793   else
794     return(0);
795 }
796
797 long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
798                   float **in,int *nonzero,int ch){
799   int i,used=0;
800   for(i=0;i<ch;i++)
801     if(nonzero[i])used++;
802   if(used)
803     return(_2class(vb,vl,in,ch));
804   else
805     return(0);
806 }
807
808 /* res2 is slightly more different; all the channels are interleaved
809    into a single vector and encoded. */
810
811 int res2_forward(oggpack_buffer *opb,
812                  vorbis_block *vb,vorbis_look_residue *vl,
813                  float **in,float **out,int *nonzero,int ch,
814                  long **partword){
815   long i,j,k,n=vb->pcmend/2,used=0;
816
817   /* don't duplicate the code; use a working vector hack for now and
818      reshape ourselves into a single channel res1 */
819   /* ugly; reallocs for each coupling pass :-( */
820   float *work=_vorbis_block_alloc(vb,ch*n*sizeof(*work));
821   for(i=0;i<ch;i++){
822     float *pcm=in[i];
823     if(nonzero[i])used++;
824     for(j=0,k=i;j<n;j++,k+=ch)
825       work[k]=pcm[j];
826   }
827   
828   if(used){
829     int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
830     /* update the sofar vector */
831     if(out){
832       for(i=0;i<ch;i++){
833         float *pcm=in[i];
834         float *sofar=out[i];
835         for(j=0,k=i;j<n;j++,k+=ch)
836           sofar[j]+=pcm[j]-work[k];
837         
838       }
839     }
840     return(ret);
841   }else{
842     return(0);
843   }
844 }
845
846 /* duplicate code here as speed is somewhat more important */
847 int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
848                  float **in,int *nonzero,int ch){
849   long i,k,l,s;
850   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
851   vorbis_info_residue0 *info=look->info;
852
853   /* move all this setup out later */
854   int samples_per_partition=info->grouping;
855   int partitions_per_word=look->phrasebook->dim;
856   int max=(vb->pcmend*ch)>>1;
857   int end=(info->end<max?info->end:max);
858   int n=end-info->begin;
859
860   if(n>0){
861     int partvals=n/samples_per_partition;
862     int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
863     int **partword=_vorbis_block_alloc(vb,partwords*sizeof(*partword));
864     
865     for(i=0;i<ch;i++)if(nonzero[i])break;
866     if(i==ch)return(0); /* no nonzero vectors */
867     
868     for(s=0;s<look->stages;s++){
869       for(i=0,l=0;i<partvals;l++){
870         
871         if(s==0){
872           /* fetch the partition word */
873           int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
874           if(temp==-1)goto eopbreak;
875           partword[l]=look->decodemap[temp];
876           if(partword[l]==NULL)goto errout;
877         }
878         
879         /* now we decode residual values for the partitions */
880         for(k=0;k<partitions_per_word && i<partvals;k++,i++)
881           if(info->secondstages[partword[l][k]]&(1<<s)){
882             codebook *stagebook=look->partbooks[partword[l][k]][s];
883             
884             if(stagebook){
885               if(vorbis_book_decodevv_add(stagebook,in,
886                                           i*samples_per_partition+info->begin,ch,
887                                           &vb->opb,samples_per_partition)==-1)
888                 goto eopbreak;
889             }
890           }
891       } 
892     }
893   }
894  errout:
895  eopbreak:
896   return(0);
897 }
898
899
900 vorbis_func_residue residue0_exportbundle={
901   NULL,
902   &res0_unpack,
903   &res0_look,
904   &res0_free_info,
905   &res0_free_look,
906   NULL,
907   NULL,
908   &res0_inverse
909 };
910
911 vorbis_func_residue residue1_exportbundle={
912   &res0_pack,
913   &res0_unpack,
914   &res0_look,
915   &res0_free_info,
916   &res0_free_look,
917   &res1_class,
918   &res1_forward,
919   &res1_inverse
920 };
921
922 vorbis_func_residue residue2_exportbundle={
923   &res0_pack,
924   &res0_unpack,
925   &res0_look,
926   &res0_free_info,
927   &res0_free_look,
928   &res2_class,
929   &res2_forward,
930   &res2_inverse
931 };
932