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