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