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