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