1 /********************************************************************
3 * THIS FILE IS PART OF THE Ogg Vorbis SOFTWARE CODEC SOURCE CODE. *
4 * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
5 * THE GNU PUBLIC LICENSE 2, WHICH IS INCLUDED WITH THIS SOURCE. *
6 * PLEASE READ THESE TERMS DISTRIBUTING. *
8 * THE OggSQUISH SOURCE CODE IS (C) COPYRIGHT 1994-1999 *
9 * by 1999 Monty <monty@xiph.org> and The XIPHOPHORUS Company *
10 * http://www.xiph.org/ *
12 ********************************************************************
14 function: build a VQ codebook
15 author: Monty <xiphmont@mit.edu>
16 modifications by: Monty
17 last modification date: Dec 10 1999
19 ********************************************************************/
21 /* This code is *not* part of libvorbis. It is used to generate
22 trained codebooks offline and then spit the results into a
23 pregenerated codebook that is compiled into libvorbis. It is an
24 expensive (but good) algorithm. Run it on big iron. */
26 /* There are so many optimizations to explore in *both* stages that
27 considering the undertaking is almost withering. For now, we brute
36 /* Codebook generation happens in two steps:
38 1) Train the codebook with data collected from the encoder: We use
39 one of a few error metrics (which represent the distance between a
40 given data point and a candidate point in the training set) to
41 divide the training set up into cells representing roughly equal
42 probability of occurring.
44 2) Generate the codebook and auxiliary data from the trained data set
47 /* Codebook training ****************************************************
49 * The basic idea here is that a VQ codebook is like an m-dimensional
50 * foam with n bubbles. The bubbles compete for space/volume and are
51 * 'pressurized' [biased] according to some metric. The basic alg
52 * iterates through allowing the bubbles to compete for space until
53 * they converge (if the damping is dome properly) on a steady-state
54 * solution. Individual input points, collected from libvorbis, are
55 * used to train the algorithm monte-carlo style. */
57 /* internal helpers *****************************************************/
58 #define vN(data,i) (data+v->elements*i)
60 double *_point(vqgen *v,long ptr){
61 return v->pointlist+(v->elements*ptr);
64 double *_now(vqgen *v,long ptr){
65 return v->entrylist+(v->elements*ptr);
68 /* default metric; squared 'distance' from desired value. */
69 double _dist_sq(vqgen *v,double *a, double *b){
74 double val=(a[i]-b[i]);
80 /* *must* be beefed up. */
81 void _vqgen_seed(vqgen *v){
82 memcpy(v->entrylist,v->pointlist,sizeof(double)*v->entries*v->elements);
85 /* External calls *******************************************************/
87 void vqgen_init(vqgen *v,int elements,int entries,
88 double (*metric)(vqgen *,double *, double *),
90 memset(v,0,sizeof(vqgen));
95 v->pointlist=malloc(v->allocated*v->elements*sizeof(double));
98 v->entrylist=malloc(v->entries*v->elements*sizeof(double));
99 v->assigned=malloc(v->entries*sizeof(long));
100 v->bias=calloc(v->entries,sizeof(double));
102 v->metric_func=metric;
104 v->metric_func=_dist_sq;
107 void vqgen_addpoint(vqgen *v, double *p){
108 if(v->points>=v->allocated){
110 v->pointlist=realloc(v->pointlist,v->allocated*v->elements*sizeof(double));
113 memcpy(_point(v,v->points),p,sizeof(double)*v->elements);
115 if(v->points==v->entries)_vqgen_seed(v);
118 double vqgen_iterate(vqgen *v){
120 double fdesired=(double)v->points/v->entries;
121 long desired=fdesired;
124 double *new=malloc(sizeof(double)*v->entries*v->elements);
125 long *nearcount=malloc(v->entries*sizeof(long));
126 double *nearbias=malloc(v->entries*desired*sizeof(double));
133 sprintf(buff,"cells%d.m",v->it);
134 cells=fopen(buff,"w");
135 sprintf(buff,"assig%d.m",v->it);
136 assig=fopen(buff,"w");
137 sprintf(buff,"bias%d.m",v->it);
138 bias=fopen(buff,"w");
141 fprintf(stderr,"Pass #%d... ",v->it);
144 fprintf(stderr,"generation requires at least two entries\n");
148 /* fill in nearest points for entries */
149 /*memset(v->bias,0,sizeof(double)*v->entries);*/
150 memset(nearcount,0,sizeof(long)*v->entries);
151 memset(v->assigned,0,sizeof(long)*v->entries);
152 for(i=0;i<v->points;i++){
153 double *ppt=_point(v,i);
154 double firstmetric=v->metric_func(v,_now(v,0),ppt)+v->bias[0];
155 double secondmetric=v->metric_func(v,_now(v,1),ppt)+v->bias[1];
158 if(firstmetric>secondmetric){
159 double temp=firstmetric;
160 firstmetric=secondmetric;
166 for(j=2;j<v->entries;j++){
167 double thismetric=v->metric_func(v,_now(v,j),_point(v,i))+v->bias[j];
168 if(thismetric<secondmetric){
169 if(thismetric<firstmetric){
170 secondmetric=firstmetric;
171 secondentry=firstentry;
172 firstmetric=thismetric;
175 secondmetric=thismetric;
182 meterror+=firstmetric-v->bias[firstentry];
183 /* set up midpoints for next iter */
185 for(k=0;k<v->elements;k++)
186 vN(new,j)[k]+=_point(v,i)[k];
188 for(k=0;k<v->elements;k++)
189 vN(new,j)[k]=_point(v,i)[k];
193 fprintf(cells,"%g %g\n%g %g\n\n",
194 _now(v,j)[0],_now(v,j)[1],
195 _point(v,i)[0],_point(v,i)[1]);
198 for(j=0;j<v->entries;j++){
201 double *nearbiasptr=nearbias+desired*j;
202 long k=nearcount[j]-1;
204 /* 'thismetric' is to be the bias value necessary in the current
205 arrangement for entry j to capture point i */
207 /* use the secondary entry as the threshhold */
208 thismetric=secondmetric-v->metric_func(v,_now(v,j),_point(v,i));
210 /* use the primary entry as the threshhold */
211 thismetric=firstmetric-v->metric_func(v,_now(v,j),_point(v,i));
214 if(k>=0 && thismetric>nearbiasptr[k]){
216 /* start at the end and search backward for where this entry
219 for(;k>0;k--) if(nearbiasptr[k-1]>=thismetric)break;
221 /* insert at k. Shift and inject. */
222 memmove(nearbiasptr+k+1,nearbiasptr+k,(desired-k-1)*sizeof(double));
223 nearbiasptr[k]=thismetric;
225 if(nearcount[j]<desired)nearcount[j]++;
228 if(nearcount[j]<desired){
229 /* we checked the thresh earlier. We know this is the
231 nearbiasptr[nearcount[j]++]=thismetric;
237 /* inflate/deflate */
238 for(i=0;i<v->entries;i++)
239 v->bias[i]=nearbias[(i+1)*desired-1];
241 /* assign midpoints */
243 for(j=0;j<v->entries;j++){
244 asserror+=fabs(v->assigned[j]-fdesired);
246 for(k=0;k<v->elements;k++)
247 _now(v,j)[k]=vN(new,j)[k]/v->assigned[j];
249 fprintf(assig,"%ld\n",v->assigned[j]);
250 fprintf(bias,"%g\n",v->bias[j]);
255 /* midpoints must be quantized. but we need to know the range in
259 for(k=0;k<v->elements;k++){
261 min=max=_now(v,0)[k];
263 for(j=1;j<v->entries;j++){
264 double val=_now(v,j)[k];
269 delta=(max-min)/((1<<v->quantbits)-1);
270 for(j=0;j<v->entries;j++){
271 double val=_now(v,j)[k];
272 _now(v,j)[k]=min+delta*rint((val-min)/delta);
277 asserror/=(v->entries*fdesired);
278 fprintf(stderr,": dist %g(%g) metric error=%g \n",
279 asserror,fdesired,meterror/v->points);
294 /* Building a codebook from trained set **********************************
296 The codebook in raw form is technically finished once it's trained.
297 However, we want to finalize the representative codebook values for
298 each entry and generate auxiliary information to optimize encoding.
299 We generate the auxiliary coding tree using collected data,
300 probably the same data as in the original training */
302 /* At each recursion, the data set is split in half. Cells with data
303 points on side A go into set A, same with set B. The sets may
304 overlap. If the cell overlaps the deviding line only very slightly
305 (provided parameter), we may choose to ignore the overlap in order
306 to pare the tree down */
310 int iascsort(const void *a,const void *b){
311 double av=sortvals[*((long *)a) * els];
312 double bv=sortvals[*((long *)b) * els];
317 /* goes through the split, but just counts it and returns a metric*/
318 void lp_count(vqgen *v,long *entryindex,long entries,
319 long *pointindex,long points,
320 long *entryA,long *entryB,
321 double *n, double c, double slack,
322 long *entriesA,long *entriesB,long *entriesC){
326 memset(entryA,0,sizeof(long)*entries);
327 memset(entryB,0,sizeof(long)*entries);
329 for(i=0;i<points;i++){
330 double *ppt=_point(v,pointindex[i]);
332 double firstmetric=_dist_sq(v,_now(v,entryindex[0]),ppt);
335 for(j=1;j<entries;j++){
336 double thismetric=_dist_sq(v,_now(v,entryindex[j]),ppt);
337 if(thismetric<firstmetric){
338 firstmetric=thismetric;
343 /* count point split */
344 for(k=0;k<v->elements;k++)
345 position+=ppt[k]*n[k];
347 entryA[firstentry]++;
349 entryB[firstentry]++;
353 /* look to see if entries are in the slack zone */
354 /* The entry splitting isn't total, so that storage has to be
355 allocated for recursion. Reuse the entryA/entryB vectors */
356 for(j=0;j<entries;j++){
357 long total=entryA[j]+entryB[j];
358 if((double)entryA[j]/total<slack){
360 }else if((double)entryB[j]/total<slack){
363 if(entryA[j] && entryB[j])C++;
364 if(entryA[j])entryA[A++]=entryindex[j];
365 if(entryB[j])entryB[B++]=entryindex[j];
372 void pq_in_out(vqgen *v,double *n,double *c,double *p,double *q){
375 for(k=0;k<v->elements;k++){
376 double center=(p[k]+q[k])/2.;
377 n[k]=(center-q[k])*2.;
382 void pq_center_out(vqgen *v,double *n,double *c,double *center,double *q){
385 for(k=0;k<v->elements;k++){
386 n[k]=(center[k]-q[k])*2.;
391 int lp_split(vqgen *v,vqbook *b,
392 long *entryindex,long entries,
393 long *pointindex,long points,
394 long depth,double slack){
396 /* The encoder, regardless of book, will be using a straight
397 euclidian distance-to-point metric to determine closest point.
398 Thus we split the cells using the same (we've already trained the
399 codebook set spacing and distribution using special metrics and
400 even a midpoint division won't disturb the basic properties) */
407 long *entryA=calloc(entries,sizeof(long));
408 long *entryB=calloc(entries,sizeof(long));
415 p=alloca(sizeof(double)*v->elements);
416 q=alloca(sizeof(double)*v->elements);
417 n=alloca(sizeof(double)*v->elements);
418 memset(p,0,sizeof(double)*v->elements);
420 /* We need to find the dividing hyperplane. find the median of each
421 axis as the centerpoint and the normal facing farthest point */
423 /* more than one way to do this part. For small sets, we can brute
427 /* try every pair possibility */
432 for(i=0;i<entries-1;i++){
433 for(j=i+1;j<entries;j++){
434 pq_in_out(v,n,&c,_now(v,entryindex[i]),_now(v,entryindex[j]));
435 lp_count(v,entryindex,entries,
439 &entriesA,&entriesB,&entriesC);
440 this=(entriesA-entriesC)*(entriesB-entriesC);
449 pq_in_out(v,n,&c,_now(v,entryindex[besti]),_now(v,entryindex[bestj]));
454 /* try COG/normal and furthest pairs */
456 for(k=0;k<v->elements;k++){
457 /* just sort the index array */
458 sortvals=v->pointlist+k;
460 qsort(pointindex,points,sizeof(long),iascsort);
462 p[k]=v->pointlist[(pointindex[points/2])*v->elements+k];
464 p[k]=(v->pointlist[(pointindex[points/2])*v->elements+k]+
465 v->pointlist[(pointindex[points/2-1])*v->elements+k])/2.;
469 /* try every normal, but just for distance */
470 for(j=0;j<entries;j++){
471 double *ppj=_now(v,entryindex[j]);
472 double this=_dist_sq(v,p,ppj);
479 pq_center_out(v,n,&c,p,_point(v,pointindex[bestj]));
484 /* find cells enclosing points */
485 /* count A/B points */
487 lp_count(v,entryindex,entries,
491 &entriesA,&entriesB,&entriesC);
493 /* the point index is split evenly, so we do an Order n
494 rearrangement into A first/B last and just pass it on */
501 for(k=0;k<v->elements;k++)
502 position+=_point(v,pointindex[Aptr])[k]*n[k];
503 if(position<=0.)break; /* not in A */
508 for(k=0;k<v->elements;k++)
509 position+=_point(v,pointindex[Bptr])[k]*n[k];
510 if(position>0.)break; /* not in B */
514 long temp=pointindex[Aptr];
515 pointindex[Aptr]=pointindex[Bptr];
516 pointindex[Bptr]=temp;
522 fprintf(stderr,"split: total=%ld depth=%ld set A=%ld:%ld:%ld=B\n",
523 entries,depth,entriesA-entriesC,entriesC,entriesB-entriesC);
525 long thisaux=b->aux++;
526 if(b->aux>=b->alloc){
528 b->ptr0=realloc(b->ptr0,sizeof(long)*b->alloc);
529 b->ptr1=realloc(b->ptr1,sizeof(long)*b->alloc);
530 b->n=realloc(b->n,sizeof(double)*b->elements*b->alloc);
531 b->c=realloc(b->c,sizeof(double)*b->alloc);
534 memcpy(b->n+b->elements*thisaux,n,sizeof(double)*v->elements);
539 b->ptr0[thisaux]=entryA[0];
541 b->ptr0[thisaux]= -b->aux;
542 ret=lp_split(v,b,entryA,entriesA,pointindex,pointsA,depth+1,slack);
546 b->ptr1[thisaux]=entryB[0];
548 b->ptr1[thisaux]= -b->aux;
549 ret+=lp_split(v,b,entryB,entriesB,pointindex+pointsA,points-pointsA,
558 int vqenc_entry(vqbook *b,double *val){
561 double c= -b->c[ptr];
562 double *nptr=b->n+b->elements*ptr;
563 for(k=0;k<b->elements;k++)
574 void vqgen_book(vqgen *v,vqbook *b){
576 long *entryindex=malloc(sizeof(double)*v->entries);
577 long *pointindex=malloc(sizeof(double)*v->points);
579 memset(b,0,sizeof(vqbook));
580 for(i=0;i<v->entries;i++)entryindex[i]=i;
581 for(i=0;i<v->points;i++)pointindex[i]=i;
582 b->elements=v->elements;
583 b->entries=v->entries;
585 b->ptr0=malloc(sizeof(long)*b->alloc);
586 b->ptr1=malloc(sizeof(long)*b->alloc);
587 b->n=malloc(sizeof(double)*b->elements*b->alloc);
588 b->c=malloc(sizeof(double)*b->alloc);
590 b->valuelist=malloc(sizeof(double)*b->elements*b->entries);
591 b->codelist=malloc(sizeof(long)*b->entries);
592 b->lengthlist=malloc(b->entries*sizeof(long));
594 /* first, generate the encoding decision heirarchy */
595 fprintf(stderr,"Total leaves: %ld\n",
596 lp_split(v,b,entryindex,v->entries, pointindex,v->points,0,0));
598 /* run all training points through the decision tree to get a final
601 long *probability=calloc(b->entries*2,sizeof(long));
602 for(i=0;i<v->points;i++){
603 int ret=vqenc_entry(b,v->pointlist+i*v->elements);
607 for(i=0;i<b->entries;i++){
608 fprintf(stderr,"point %ld: %ld\n",i,probability[i]);
613 /* generate the codewords (short to long) */