Fix for bug #1456-- the 'bulletproofing' from CVE-2008-1420 inadvertantly
[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   }
238
239   return(info);
240  errout:
241   res0_free_info(info);
242   return(NULL);
243 }
244
245 vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
246                                vorbis_info_residue *vr){
247   vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
248   vorbis_look_residue0 *look=_ogg_calloc(1,sizeof(*look));
249   codec_setup_info     *ci=vd->vi->codec_setup;
250
251   int j,k,acc=0;
252   int dim;
253   int maxstage=0;
254   look->info=info;
255
256   look->parts=info->partitions;
257   look->fullbooks=ci->fullbooks;
258   look->phrasebook=ci->fullbooks+info->groupbook;
259   dim=look->phrasebook->dim;
260
261   look->partbooks=_ogg_calloc(look->parts,sizeof(*look->partbooks));
262
263   for(j=0;j<look->parts;j++){
264     int stages=ilog(info->secondstages[j]);
265     if(stages){
266       if(stages>maxstage)maxstage=stages;
267       look->partbooks[j]=_ogg_calloc(stages,sizeof(*look->partbooks[j]));
268       for(k=0;k<stages;k++)
269         if(info->secondstages[j]&(1<<k)){
270           look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
271 #ifdef TRAIN_RES
272           look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
273                                            sizeof(***look->training_data));
274 #endif
275         }
276     }
277   }
278
279   look->partvals=look->phrasebook->entries;
280   look->stages=maxstage;
281   look->decodemap=_ogg_malloc(look->partvals*sizeof(*look->decodemap));
282   for(j=0;j<look->partvals;j++){
283     long val=j;
284     long mult=look->partvals/look->parts;
285     look->decodemap[j]=_ogg_malloc(dim*sizeof(*look->decodemap[j]));
286     for(k=0;k<dim;k++){
287       long deco=val/mult;
288       val-=deco*mult;
289       mult/=look->parts;
290       look->decodemap[j][k]=deco;
291     }
292   }
293 #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
294   {
295     static int train_seq=0;
296     look->train_seq=train_seq++;
297   }
298 #endif
299   return(look);
300 }
301
302 /* break an abstraction and copy some code for performance purposes */
303 static int local_book_besterror(codebook *book,float *a){
304   int dim=book->dim,i,k,o;
305   int best=0;
306   encode_aux_threshmatch *tt=book->c->thresh_tree;
307
308   /* find the quant val of each scalar */
309   for(k=0,o=dim;k<dim;++k){
310     float val=a[--o];
311     i=tt->threshvals>>1;
312
313     if(val<tt->quantthresh[i]){      
314       if(val<tt->quantthresh[i-1]){
315         for(--i;i>0;--i)
316           if(val>=tt->quantthresh[i-1])
317             break;
318       }
319     }else{
320       
321       for(++i;i<tt->threshvals-1;++i)
322         if(val<tt->quantthresh[i])break;
323       
324     }
325
326     best=(best*tt->quantvals)+tt->quantmap[i];
327   }
328   /* regular lattices are easy :-) */
329   
330   if(book->c->lengthlist[best]<=0){
331     const static_codebook *c=book->c;
332     int i,j;
333     float bestf=0.f;
334     float *e=book->valuelist;
335     best=-1;
336     for(i=0;i<book->entries;i++){
337       if(c->lengthlist[i]>0){
338         float this=0.f;
339         for(j=0;j<dim;j++){
340           float val=(e[j]-a[j]);
341           this+=val*val;
342         }
343         if(best==-1 || this<bestf){
344           bestf=this;
345           best=i;
346         }
347       }
348       e+=dim;
349     }
350   }
351
352   if(best>-1){
353     float *ptr=book->valuelist+best*dim;
354     for(i=0;i<dim;i++)
355       *a++ -= *ptr++;
356   }
357
358   return(best);
359 }
360
361 static int _encodepart(oggpack_buffer *opb,float *vec, int n,
362                        codebook *book,long *acc){
363   int i,bits=0;
364   int dim=book->dim;
365   int step=n/dim;
366
367   for(i=0;i<step;i++){
368     int entry=local_book_besterror(book,vec+i*dim);
369
370 #ifdef TRAIN_RES
371     if(entry>0)
372       acc[entry]++;
373 #endif
374       
375     bits+=vorbis_book_encode(book,entry,opb);
376   
377   }
378
379   return(bits);
380 }
381
382 static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
383                        float **in,int ch){
384   long i,j,k;
385   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
386   vorbis_info_residue0 *info=look->info;
387
388   /* move all this setup out later */
389   int samples_per_partition=info->grouping;
390   int possible_partitions=info->partitions;
391   int n=info->end-info->begin;
392   
393   int partvals=n/samples_per_partition;
394   long **partword=_vorbis_block_alloc(vb,ch*sizeof(*partword));
395   float scale=100./samples_per_partition;
396   
397   /* we find the partition type for each partition of each
398      channel.  We'll go back and do the interleaved encoding in a
399      bit.  For now, clarity */
400   
401   for(i=0;i<ch;i++){
402     partword[i]=_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
403     memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
404   }
405   
406   for(i=0;i<partvals;i++){
407     int offset=i*samples_per_partition+info->begin;
408     for(j=0;j<ch;j++){
409       float max=0.;
410       float ent=0.;
411       for(k=0;k<samples_per_partition;k++){
412         if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
413         ent+=fabs(rint(in[j][offset+k]));
414       }
415       ent*=scale;
416       
417       for(k=0;k<possible_partitions-1;k++)
418         if(max<=info->classmetric1[k] &&
419            (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
420           break;
421       
422       partword[j][i]=k;  
423     }
424   }
425   
426 #ifdef TRAIN_RESAUX
427   {
428     FILE *of;
429     char buffer[80];
430     
431     for(i=0;i<ch;i++){
432       sprintf(buffer,"resaux_%d.vqd",look->train_seq);
433       of=fopen(buffer,"a");
434       for(j=0;j<partvals;j++)
435         fprintf(of,"%ld, ",partword[i][j]);
436       fprintf(of,"\n");
437       fclose(of);
438     }
439   }
440 #endif
441   look->frames++;
442   
443   return(partword);
444 }
445
446 /* designed for stereo or other modes where the partition size is an
447    integer multiple of the number of channels encoded in the current
448    submap */
449 static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
450                       int ch){
451   long i,j,k,l;
452   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
453   vorbis_info_residue0 *info=look->info;
454
455   /* move all this setup out later */
456   int samples_per_partition=info->grouping;
457   int possible_partitions=info->partitions;
458   int n=info->end-info->begin;
459
460   int partvals=n/samples_per_partition;
461   long **partword=_vorbis_block_alloc(vb,sizeof(*partword));
462   
463 #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
464   FILE *of;
465   char buffer[80];
466 #endif
467   
468   partword[0]=_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
469   memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
470   
471   for(i=0,l=info->begin/ch;i<partvals;i++){
472     float magmax=0.f;
473     float angmax=0.f;
474     for(j=0;j<samples_per_partition;j+=ch){
475       if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
476       for(k=1;k<ch;k++)
477         if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
478         l++;
479     }
480     
481     for(j=0;j<possible_partitions-1;j++)
482       if(magmax<=info->classmetric1[j] &&
483          angmax<=info->classmetric2[j])
484         break;
485     
486     partword[0][i]=j;
487     
488   }  
489   
490 #ifdef TRAIN_RESAUX
491   sprintf(buffer,"resaux_%d.vqd",look->train_seq);
492   of=fopen(buffer,"a");
493   for(i=0;i<partvals;i++)
494     fprintf(of,"%ld, ",partword[0][i]);
495   fprintf(of,"\n");
496   fclose(of);
497 #endif
498   
499   look->frames++;
500   
501   return(partword);
502 }
503
504 static int _01forward(oggpack_buffer *opb,
505                       vorbis_block *vb,vorbis_look_residue *vl,
506                       float **in,int ch,
507                       long **partword,
508                       int (*encode)(oggpack_buffer *,float *,int,
509                                     codebook *,long *)){
510   long i,j,k,s;
511   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
512   vorbis_info_residue0 *info=look->info;
513
514   /* move all this setup out later */
515   int samples_per_partition=info->grouping;
516   int possible_partitions=info->partitions;
517   int partitions_per_word=look->phrasebook->dim;
518   int n=info->end-info->begin;
519
520   int partvals=n/samples_per_partition;
521   long resbits[128];
522   long resvals[128];
523   
524 #ifdef TRAIN_RES
525   for(i=0;i<ch;i++)
526     for(j=info->begin;j<end;j++){
527       if(in[i][j]>look->tmax)look->tmax=in[i][j];
528       if(in[i][j]<look->tmin)look->tmin=in[i][j];
529     }
530 #endif
531   
532   memset(resbits,0,sizeof(resbits));
533   memset(resvals,0,sizeof(resvals));
534   
535   /* we code the partition words for each channel, then the residual
536      words for a partition per channel until we've written all the
537      residual words for that partition word.  Then write the next
538      partition channel words... */
539   
540   for(s=0;s<look->stages;s++){
541     
542     for(i=0;i<partvals;){
543       
544       /* first we encode a partition codeword for each channel */
545       if(s==0){
546         for(j=0;j<ch;j++){
547           long val=partword[j][i];
548           for(k=1;k<partitions_per_word;k++){
549             val*=possible_partitions;
550             if(i+k<partvals)
551               val+=partword[j][i+k];
552           }     
553           
554           /* training hack */
555           if(val<look->phrasebook->entries)
556             look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
557 #if 0 /*def TRAIN_RES*/
558           else
559             fprintf(stderr,"!");
560 #endif
561           
562         }
563       }
564       
565       /* now we encode interleaved residual values for the partitions */
566       for(k=0;k<partitions_per_word && i<partvals;k++,i++){
567         long offset=i*samples_per_partition+info->begin;
568           
569         for(j=0;j<ch;j++){
570           if(s==0)resvals[partword[j][i]]+=samples_per_partition;
571           if(info->secondstages[partword[j][i]]&(1<<s)){
572             codebook *statebook=look->partbooks[partword[j][i]][s];
573             if(statebook){
574               int ret;
575               long *accumulator=NULL;
576               
577 #ifdef TRAIN_RES
578               accumulator=look->training_data[s][partword[j][i]];
579               {
580                 int l;
581                 float *samples=in[j]+offset;
582                 for(l=0;l<samples_per_partition;l++){
583                   if(samples[l]<look->training_min[s][partword[j][i]])
584                     look->training_min[s][partword[j][i]]=samples[l];
585                   if(samples[l]>look->training_max[s][partword[j][i]])
586                     look->training_max[s][partword[j][i]]=samples[l];
587                 }
588               }
589 #endif
590               
591               ret=encode(opb,in[j]+offset,samples_per_partition,
592                          statebook,accumulator);
593               
594               look->postbits+=ret;
595               resbits[partword[j][i]]+=ret;
596             }
597           }
598         }
599       }
600     }
601   }
602   
603   /*{
604     long total=0;
605     long totalbits=0;
606     fprintf(stderr,"%d :: ",vb->mode);
607     for(k=0;k<possible_partitions;k++){
608     fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
609     total+=resvals[k];
610     totalbits+=resbits[k];
611     }
612     
613     fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
614     }*/
615
616   return(0);
617 }
618
619 /* a truncated packet here just means 'stop working'; it's not an error */
620 static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
621                       float **in,int ch,
622                       long (*decodepart)(codebook *, float *, 
623                                          oggpack_buffer *,int)){
624
625   long i,j,k,l,s;
626   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
627   vorbis_info_residue0 *info=look->info;
628
629   /* move all this setup out later */
630   int samples_per_partition=info->grouping;
631   int partitions_per_word=look->phrasebook->dim;
632   int max=vb->pcmend>>1;
633   int end=(info->end<max?info->end:max);
634   int n=end-info->begin;
635   
636   if(n>0){
637     int partvals=n/samples_per_partition;
638     int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
639     int ***partword=alloca(ch*sizeof(*partword));
640     
641     for(j=0;j<ch;j++)
642       partword[j]=_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
643     
644     for(s=0;s<look->stages;s++){
645       
646       /* each loop decodes on partition codeword containing 
647          partitions_per_word partitions */
648       for(i=0,l=0;i<partvals;l++){
649         if(s==0){
650           /* fetch the partition word for each channel */
651           for(j=0;j<ch;j++){
652             int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
653             
654             if(temp==-1)goto eopbreak;
655             partword[j][l]=look->decodemap[temp];
656             if(partword[j][l]==NULL)goto errout;
657           }
658         }
659         
660         /* now we decode residual values for the partitions */
661         for(k=0;k<partitions_per_word && i<partvals;k++,i++)
662           for(j=0;j<ch;j++){
663             long offset=info->begin+i*samples_per_partition;
664             if(info->secondstages[partword[j][l][k]]&(1<<s)){
665               codebook *stagebook=look->partbooks[partword[j][l][k]][s];
666               if(stagebook){
667                 if(decodepart(stagebook,in[j]+offset,&vb->opb,
668                               samples_per_partition)==-1)goto eopbreak;
669               }
670             }
671           }
672       } 
673     }
674   }
675  errout:
676  eopbreak:
677   return(0);
678 }
679
680 #if 0
681 /* residue 0 and 1 are just slight variants of one another. 0 is
682    interleaved, 1 is not */
683 long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
684                   float **in,int *nonzero,int ch){
685   /* we encode only the nonzero parts of a bundle */
686   int i,used=0;
687   for(i=0;i<ch;i++)
688     if(nonzero[i])
689       in[used++]=in[i];
690   if(used)
691     /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
692     return(_01class(vb,vl,in,used));
693   else
694     return(0);
695 }
696
697 int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
698                  float **in,float **out,int *nonzero,int ch,
699                  long **partword){
700   /* we encode only the nonzero parts of a bundle */
701   int i,j,used=0,n=vb->pcmend/2;
702   for(i=0;i<ch;i++)
703     if(nonzero[i]){
704       if(out)
705         for(j=0;j<n;j++)
706           out[i][j]+=in[i][j];
707       in[used++]=in[i];
708     }
709   if(used){
710     int ret=_01forward(vb,vl,in,used,partword,
711                       _interleaved_encodepart);
712     if(out){
713       used=0;
714       for(i=0;i<ch;i++)
715         if(nonzero[i]){
716           for(j=0;j<n;j++)
717             out[i][j]-=in[used][j];
718           used++;
719         }
720     }
721     return(ret);
722   }else{
723     return(0);
724   }
725 }
726 #endif
727
728 int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
729                  float **in,int *nonzero,int ch){
730   int i,used=0;
731   for(i=0;i<ch;i++)
732     if(nonzero[i])
733       in[used++]=in[i];
734   if(used)
735     return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
736   else
737     return(0);
738 }
739
740 int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
741                  float **in,float **out,int *nonzero,int ch,
742                  long **partword){
743   int i,j,used=0,n=vb->pcmend/2;
744   for(i=0;i<ch;i++)
745     if(nonzero[i]){
746       if(out)
747         for(j=0;j<n;j++)
748           out[i][j]+=in[i][j];
749       in[used++]=in[i];
750     }
751
752   if(used){
753     int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
754     if(out){
755       used=0;
756       for(i=0;i<ch;i++)
757         if(nonzero[i]){
758           for(j=0;j<n;j++)
759             out[i][j]-=in[used][j];
760           used++;
761         }
762     }
763     return(ret);
764   }else{
765     return(0);
766   }
767 }
768
769 long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
770                   float **in,int *nonzero,int ch){
771   int i,used=0;
772   for(i=0;i<ch;i++)
773     if(nonzero[i])
774       in[used++]=in[i];
775   if(used)
776     return(_01class(vb,vl,in,used));
777   else
778     return(0);
779 }
780
781 int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
782                  float **in,int *nonzero,int ch){
783   int i,used=0;
784   for(i=0;i<ch;i++)
785     if(nonzero[i])
786       in[used++]=in[i];
787   if(used)
788     return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
789   else
790     return(0);
791 }
792
793 long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
794                   float **in,int *nonzero,int ch){
795   int i,used=0;
796   for(i=0;i<ch;i++)
797     if(nonzero[i])used++;
798   if(used)
799     return(_2class(vb,vl,in,ch));
800   else
801     return(0);
802 }
803
804 /* res2 is slightly more different; all the channels are interleaved
805    into a single vector and encoded. */
806
807 int res2_forward(oggpack_buffer *opb,
808                  vorbis_block *vb,vorbis_look_residue *vl,
809                  float **in,float **out,int *nonzero,int ch,
810                  long **partword){
811   long i,j,k,n=vb->pcmend/2,used=0;
812
813   /* don't duplicate the code; use a working vector hack for now and
814      reshape ourselves into a single channel res1 */
815   /* ugly; reallocs for each coupling pass :-( */
816   float *work=_vorbis_block_alloc(vb,ch*n*sizeof(*work));
817   for(i=0;i<ch;i++){
818     float *pcm=in[i];
819     if(nonzero[i])used++;
820     for(j=0,k=i;j<n;j++,k+=ch)
821       work[k]=pcm[j];
822   }
823   
824   if(used){
825     int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
826     /* update the sofar vector */
827     if(out){
828       for(i=0;i<ch;i++){
829         float *pcm=in[i];
830         float *sofar=out[i];
831         for(j=0,k=i;j<n;j++,k+=ch)
832           sofar[j]+=pcm[j]-work[k];
833         
834       }
835     }
836     return(ret);
837   }else{
838     return(0);
839   }
840 }
841
842 /* duplicate code here as speed is somewhat more important */
843 int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
844                  float **in,int *nonzero,int ch){
845   long i,k,l,s;
846   vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
847   vorbis_info_residue0 *info=look->info;
848
849   /* move all this setup out later */
850   int samples_per_partition=info->grouping;
851   int partitions_per_word=look->phrasebook->dim;
852   int max=(vb->pcmend*ch)>>1;
853   int end=(info->end<max?info->end:max);
854   int n=end-info->begin;
855
856   if(n>0){
857     int partvals=n/samples_per_partition;
858     int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
859     int **partword=_vorbis_block_alloc(vb,partwords*sizeof(*partword));
860     
861     for(i=0;i<ch;i++)if(nonzero[i])break;
862     if(i==ch)return(0); /* no nonzero vectors */
863     
864     for(s=0;s<look->stages;s++){
865       for(i=0,l=0;i<partvals;l++){
866         
867         if(s==0){
868           /* fetch the partition word */
869           int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
870           if(temp==-1)goto eopbreak;
871           partword[l]=look->decodemap[temp];
872           if(partword[l]==NULL)goto errout;
873         }
874         
875         /* now we decode residual values for the partitions */
876         for(k=0;k<partitions_per_word && i<partvals;k++,i++)
877           if(info->secondstages[partword[l][k]]&(1<<s)){
878             codebook *stagebook=look->partbooks[partword[l][k]][s];
879             
880             if(stagebook){
881               if(vorbis_book_decodevv_add(stagebook,in,
882                                           i*samples_per_partition+info->begin,ch,
883                                           &vb->opb,samples_per_partition)==-1)
884                 goto eopbreak;
885             }
886           }
887       } 
888     }
889   }
890  errout:
891  eopbreak:
892   return(0);
893 }
894
895
896 const vorbis_func_residue residue0_exportbundle={
897   NULL,
898   &res0_unpack,
899   &res0_look,
900   &res0_free_info,
901   &res0_free_look,
902   NULL,
903   NULL,
904   &res0_inverse
905 };
906
907 const vorbis_func_residue residue1_exportbundle={
908   &res0_pack,
909   &res0_unpack,
910   &res0_look,
911   &res0_free_info,
912   &res0_free_look,
913   &res1_class,
914   &res1_forward,
915   &res1_inverse
916 };
917
918 const vorbis_func_residue residue2_exportbundle={
919   &res0_pack,
920   &res0_unpack,
921   &res0_look,
922   &res0_free_info,
923   &res0_free_look,
924   &res2_class,
925   &res2_forward,
926   &res2_inverse
927 };
928