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