vqsplit.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615
  1. /********************************************************************
  2. * *
  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. *
  7. * *
  8. * THE OggSQUISH SOURCE CODE IS (C) COPYRIGHT 1994-2000 *
  9. * by Monty <monty@xiph.org> and The XIPHOPHORUS Company *
  10. * http://www.xiph.org/ *
  11. * *
  12. ********************************************************************
  13. function: build a VQ codebook and the encoding decision 'tree'
  14. last mod: $Id: vqsplit.c,v 1.19.8.1 2000/08/31 09:00:03 xiphmont Exp $
  15. ********************************************************************/
  16. /* This code is *not* part of libvorbis. It is used to generate
  17. trained codebooks offline and then spit the results into a
  18. pregenerated codebook that is compiled into libvorbis. It is an
  19. expensive (but good) algorithm. Run it on big iron. */
  20. /* There are so many optimizations to explore in *both* stages that
  21. considering the undertaking is almost withering. For now, we brute
  22. force it all */
  23. #include <stdlib.h>
  24. #include <stdio.h>
  25. #include <math.h>
  26. #include <string.h>
  27. #include <sys/time.h>
  28. #include "vqgen.h"
  29. #include "vqsplit.h"
  30. #include "bookutil.h"
  31. #include "../lib/sharedbook.h"
  32. /* Codebook generation happens in two steps:
  33. 1) Train the codebook with data collected from the encoder: We use
  34. one of a few error metrics (which represent the distance between a
  35. given data point and a candidate point in the training set) to
  36. divide the training set up into cells representing roughly equal
  37. probability of occurring.
  38. 2) Generate the codebook and auxiliary data from the trained data set
  39. */
  40. /* Building a codebook from trained set **********************************
  41. The codebook in raw form is technically finished once it's trained.
  42. However, we want to finalize the representative codebook values for
  43. each entry and generate auxiliary information to optimize encoding.
  44. We generate the auxiliary coding tree using collected data,
  45. probably the same data as in the original training */
  46. /* At each recursion, the data set is split in half. Cells with data
  47. points on side A go into set A, same with set B. The sets may
  48. overlap. If the cell overlaps the deviding line only very slightly
  49. (provided parameter), we may choose to ignore the overlap in order
  50. to pare the tree down */
  51. long *isortvals;
  52. int iascsort(const void *a,const void *b){
  53. long av=isortvals[*((long *)a)];
  54. long bv=isortvals[*((long *)b)];
  55. return(av-bv);
  56. }
  57. static float _Ndist(int el,float *a, float *b){
  58. int i;
  59. float acc=0.;
  60. for(i=0;i<el;i++){
  61. float val=(a[i]-b[i]);
  62. acc+=val*val;
  63. }
  64. return sqrt(acc);
  65. }
  66. #define _Npoint(i) (pointlist+dim*(i))
  67. #define _Nnow(i) (entrylist+dim*(i))
  68. /* goes through the split, but just counts it and returns a metric*/
  69. int vqsp_count(float *entrylist,float *pointlist,int dim,
  70. long *membership,long *reventry,
  71. long *entryindex,long entries,
  72. long *pointindex,long points,int splitp,
  73. long *entryA,long *entryB,
  74. long besti,long bestj,
  75. long *entriesA,long *entriesB,long *entriesC){
  76. long i,j;
  77. long A=0,B=0,C=0;
  78. long pointsA=0;
  79. long pointsB=0;
  80. long *temppointsA=NULL;
  81. long *temppointsB=NULL;
  82. if(splitp){
  83. temppointsA=malloc(points*sizeof(long));
  84. temppointsB=malloc(points*sizeof(long));
  85. }
  86. memset(entryA,0,sizeof(long)*entries);
  87. memset(entryB,0,sizeof(long)*entries);
  88. /* Do the points belonging to this cell occur on sideA, sideB or
  89. both? */
  90. for(i=0;i<points;i++){
  91. float *ppt=_Npoint(pointindex[i]);
  92. long firstentry=membership[pointindex[i]];
  93. if(firstentry==besti){
  94. entryA[reventry[firstentry]]=1;
  95. if(splitp)temppointsA[pointsA++]=pointindex[i];
  96. continue;
  97. }
  98. if(firstentry==bestj){
  99. entryB[reventry[firstentry]]=1;
  100. if(splitp)temppointsB[pointsB++]=pointindex[i];
  101. continue;
  102. }
  103. {
  104. float distA=_Ndist(dim,ppt,_Nnow(besti));
  105. float distB=_Ndist(dim,ppt,_Nnow(bestj));
  106. if(distA<distB){
  107. entryA[reventry[firstentry]]=1;
  108. if(splitp)temppointsA[pointsA++]=pointindex[i];
  109. }else{
  110. entryB[reventry[firstentry]]=1;
  111. if(splitp)temppointsB[pointsB++]=pointindex[i];
  112. }
  113. }
  114. }
  115. /* The entry splitting isn't total, so that storage has to be
  116. allocated for recursion. Reuse the entryA/entryB vectors */
  117. /* keep the entries in ascending order (relative to the original
  118. list); we rely on that stability when ordering p/q choice */
  119. for(j=0;j<entries;j++){
  120. if(entryA[j] && entryB[j])C++;
  121. if(entryA[j])entryA[A++]=entryindex[j];
  122. if(entryB[j])entryB[B++]=entryindex[j];
  123. }
  124. *entriesA=A;
  125. *entriesB=B;
  126. *entriesC=C;
  127. if(splitp){
  128. memcpy(pointindex,temppointsA,sizeof(long)*pointsA);
  129. memcpy(pointindex+pointsA,temppointsB,sizeof(long)*pointsB);
  130. free(temppointsA);
  131. free(temppointsB);
  132. }
  133. return(pointsA);
  134. }
  135. int lp_split(float *pointlist,long totalpoints,
  136. codebook *b,
  137. long *entryindex,long entries,
  138. long *pointindex,long points,
  139. long *membership,long *reventry,
  140. long depth, long *pointsofar){
  141. encode_aux_nearestmatch *t=b->c->nearest_tree;
  142. /* The encoder, regardless of book, will be using a straight
  143. euclidian distance-to-point metric to determine closest point.
  144. Thus we split the cells using the same (we've already trained the
  145. codebook set spacing and distribution using special metrics and
  146. even a midpoint division won't disturb the basic properties) */
  147. int dim=b->dim;
  148. float *entrylist=b->valuelist;
  149. long ret;
  150. long *entryA=calloc(entries,sizeof(long));
  151. long *entryB=calloc(entries,sizeof(long));
  152. long entriesA=0;
  153. long entriesB=0;
  154. long entriesC=0;
  155. long pointsA=0;
  156. long i,j,k;
  157. long besti=-1;
  158. long bestj=-1;
  159. char spinbuf[80];
  160. sprintf(spinbuf,"splitting [%ld left]... ",totalpoints-*pointsofar);
  161. /* one reverse index needed */
  162. for(i=0;i<b->entries;i++)reventry[i]=-1;
  163. for(i=0;i<entries;i++)reventry[entryindex[i]]=i;
  164. /* We need to find the dividing hyperplane. find the median of each
  165. axis as the centerpoint and the normal facing farthest point */
  166. /* more than one way to do this part. For small sets, we can brute
  167. force it. */
  168. if(entries<8 || (float)points*entries*entries<16.*1024*1024){
  169. /* try every pair possibility */
  170. float best=0;
  171. float this;
  172. for(i=0;i<entries-1;i++){
  173. for(j=i+1;j<entries;j++){
  174. spinnit(spinbuf,entries-i);
  175. vqsp_count(b->valuelist,pointlist,dim,
  176. membership,reventry,
  177. entryindex,entries,
  178. pointindex,points,0,
  179. entryA,entryB,
  180. entryindex[i],entryindex[j],
  181. &entriesA,&entriesB,&entriesC);
  182. this=(entriesA-entriesC)*(entriesB-entriesC);
  183. /* when choosing best, we also want some form of stability to
  184. make sure more branches are pared later; secondary
  185. weighting isn;t needed as the entry lists are in ascending
  186. order, and we always try p/q in the same sequence */
  187. if( (besti==-1) ||
  188. (this>best) ){
  189. best=this;
  190. besti=entryindex[i];
  191. bestj=entryindex[j];
  192. }
  193. }
  194. }
  195. }else{
  196. float *p=alloca(dim*sizeof(float));
  197. float *q=alloca(dim*sizeof(float));
  198. float best=0.;
  199. /* try COG/normal and furthest pairs */
  200. /* meanpoint */
  201. /* eventually, we want to select the closest entry and figure n/c
  202. from p/q (because storing n/c is too large */
  203. for(k=0;k<dim;k++){
  204. spinnit(spinbuf,entries);
  205. p[k]=0.;
  206. for(j=0;j<entries;j++)
  207. p[k]+=b->valuelist[entryindex[j]*dim+k];
  208. p[k]/=entries;
  209. }
  210. /* we go through the entries one by one, looking for the entry on
  211. the other side closest to the point of reflection through the
  212. center */
  213. for(i=0;i<entries;i++){
  214. float *ppi=_Nnow(entryindex[i]);
  215. float ref_best=0.;
  216. float ref_j=-1;
  217. float this;
  218. spinnit(spinbuf,entries-i);
  219. for(k=0;k<dim;k++)
  220. q[k]=2*p[k]-ppi[k];
  221. for(j=0;j<entries;j++){
  222. if(j!=i){
  223. float this=_Ndist(dim,q,_Nnow(entryindex[j]));
  224. if(ref_j==-1 || this<=ref_best){ /* <=, not <; very important */
  225. ref_best=this;
  226. ref_j=entryindex[j];
  227. }
  228. }
  229. }
  230. vqsp_count(b->valuelist,pointlist,dim,
  231. membership,reventry,
  232. entryindex,entries,
  233. pointindex,points,0,
  234. entryA,entryB,
  235. entryindex[i],ref_j,
  236. &entriesA,&entriesB,&entriesC);
  237. this=(entriesA-entriesC)*(entriesB-entriesC);
  238. /* when choosing best, we also want some form of stability to
  239. make sure more branches are pared later; secondary
  240. weighting isn;t needed as the entry lists are in ascending
  241. order, and we always try p/q in the same sequence */
  242. if( (besti==-1) ||
  243. (this>best) ){
  244. best=this;
  245. besti=entryindex[i];
  246. bestj=ref_j;
  247. }
  248. }
  249. if(besti>bestj){
  250. long temp=besti;
  251. besti=bestj;
  252. bestj=temp;
  253. }
  254. }
  255. /* find cells enclosing points */
  256. /* count A/B points */
  257. pointsA=vqsp_count(b->valuelist,pointlist,dim,
  258. membership,reventry,
  259. entryindex,entries,
  260. pointindex,points,1,
  261. entryA,entryB,
  262. besti,bestj,
  263. &entriesA,&entriesB,&entriesC);
  264. /* fprintf(stderr,"split: total=%ld depth=%ld set A=%ld:%ld:%ld=B\n",
  265. entries,depth,entriesA-entriesC,entriesC,entriesB-entriesC);*/
  266. {
  267. long thisaux=t->aux++;
  268. if(t->aux>=t->alloc){
  269. t->alloc*=2;
  270. t->ptr0=realloc(t->ptr0,sizeof(long)*t->alloc);
  271. t->ptr1=realloc(t->ptr1,sizeof(long)*t->alloc);
  272. t->p=realloc(t->p,sizeof(long)*t->alloc);
  273. t->q=realloc(t->q,sizeof(long)*t->alloc);
  274. }
  275. t->p[thisaux]=besti;
  276. t->q[thisaux]=bestj;
  277. if(entriesA==1){
  278. ret=1;
  279. t->ptr0[thisaux]=entryA[0];
  280. *pointsofar+=pointsA;
  281. }else{
  282. t->ptr0[thisaux]= -t->aux;
  283. ret=lp_split(pointlist,totalpoints,b,entryA,entriesA,pointindex,pointsA,
  284. membership,reventry,depth+1,pointsofar);
  285. }
  286. if(entriesB==1){
  287. ret++;
  288. t->ptr1[thisaux]=entryB[0];
  289. *pointsofar+=points-pointsA;
  290. }else{
  291. t->ptr1[thisaux]= -t->aux;
  292. ret+=lp_split(pointlist,totalpoints,b,entryB,entriesB,pointindex+pointsA,
  293. points-pointsA,membership,reventry,
  294. depth+1,pointsofar);
  295. }
  296. }
  297. free(entryA);
  298. free(entryB);
  299. return(ret);
  300. }
  301. static int _node_eq(encode_aux_nearestmatch *v, long a, long b){
  302. long Aptr0=v->ptr0[a];
  303. long Aptr1=v->ptr1[a];
  304. long Bptr0=v->ptr0[b];
  305. long Bptr1=v->ptr1[b];
  306. /* the possibility of choosing the same p and q, but switched, can;t
  307. happen because we always look for the best p/q in the same search
  308. order and the search is stable */
  309. if(Aptr0==Bptr0 && Aptr1==Bptr1)
  310. return(1);
  311. return(0);
  312. }
  313. void vqsp_book(vqgen *v, codebook *b, long *quantlist){
  314. long i,j;
  315. static_codebook *c=(static_codebook *)b->c;
  316. encode_aux_nearestmatch *t;
  317. memset(b,0,sizeof(codebook));
  318. memset(c,0,sizeof(static_codebook));
  319. b->c=c;
  320. t=c->nearest_tree=calloc(1,sizeof(encode_aux_nearestmatch));
  321. c->maptype=2;
  322. /* make sure there are no duplicate entries and that every
  323. entry has points */
  324. for(i=0;i<v->entries;){
  325. /* duplicate? if so, eliminate */
  326. for(j=0;j<i;j++){
  327. if(_Ndist(v->elements,_now(v,i),_now(v,j))==0.){
  328. fprintf(stderr,"found a duplicate entry! removing...\n");
  329. v->entries--;
  330. memcpy(_now(v,i),_now(v,v->entries),sizeof(float)*v->elements);
  331. memcpy(quantlist+i*v->elements,quantlist+v->entries*v->elements,
  332. sizeof(long)*v->elements);
  333. break;
  334. }
  335. }
  336. if(j==i)i++;
  337. }
  338. {
  339. v->assigned=calloc(v->entries,sizeof(long));
  340. for(i=0;i<v->points;i++){
  341. float *ppt=_point(v,i);
  342. float firstmetric=_Ndist(v->elements,_now(v,0),ppt);
  343. long firstentry=0;
  344. if(!(i&0xff))spinnit("checking... ",v->points-i);
  345. for(j=0;j<v->entries;j++){
  346. float thismetric=_Ndist(v->elements,_now(v,j),ppt);
  347. if(thismetric<firstmetric){
  348. firstmetric=thismetric;
  349. firstentry=j;
  350. }
  351. }
  352. v->assigned[firstentry]++;
  353. }
  354. for(j=0;j<v->entries;){
  355. if(v->assigned[j]==0){
  356. fprintf(stderr,"found an unused entry! removing...\n");
  357. v->entries--;
  358. memcpy(_now(v,j),_now(v,v->entries),sizeof(float)*v->elements);
  359. v->assigned[j]=v->assigned[v->elements];
  360. memcpy(quantlist+j*v->elements,quantlist+v->entries*v->elements,
  361. sizeof(long)*v->elements);
  362. continue;
  363. }
  364. j++;
  365. }
  366. }
  367. fprintf(stderr,"Building a book with %ld unique entries...\n",v->entries);
  368. {
  369. long *entryindex=malloc(v->entries*sizeof(long *));
  370. long *pointindex=malloc(v->points*sizeof(long));
  371. long *membership=malloc(v->points*sizeof(long));
  372. long *reventry=malloc(v->entries*sizeof(long));
  373. long pointssofar=0;
  374. for(i=0;i<v->entries;i++)entryindex[i]=i;
  375. for(i=0;i<v->points;i++)pointindex[i]=i;
  376. t->alloc=4096;
  377. t->ptr0=malloc(sizeof(long)*t->alloc);
  378. t->ptr1=malloc(sizeof(long)*t->alloc);
  379. t->p=malloc(sizeof(long)*t->alloc);
  380. t->q=malloc(sizeof(long)*t->alloc);
  381. t->aux=0;
  382. c->dim=v->elements;
  383. c->entries=v->entries;
  384. c->lengthlist=calloc(c->entries,sizeof(long));
  385. b->valuelist=v->entrylist; /* temporary; replaced later */
  386. b->dim=c->dim;
  387. b->entries=c->entries;
  388. for(i=0;i<v->points;i++)membership[i]=-1;
  389. for(i=0;i<v->points;i++){
  390. float *ppt=_point(v,i);
  391. long firstentry=0;
  392. float firstmetric=_Ndist(v->elements,_now(v,0),ppt);
  393. if(!(i&0xff))spinnit("assigning... ",v->points-i);
  394. for(j=1;j<v->entries;j++){
  395. if(v->assigned[j]!=-1){
  396. float thismetric=_Ndist(v->elements,_now(v,j),ppt);
  397. if(thismetric<=firstmetric){
  398. firstmetric=thismetric;
  399. firstentry=j;
  400. }
  401. }
  402. }
  403. membership[i]=firstentry;
  404. }
  405. fprintf(stderr,"Leaves added: %d \n",
  406. lp_split(v->pointlist,v->points,
  407. b,entryindex,v->entries,
  408. pointindex,v->points,
  409. membership,reventry,
  410. 0,&pointssofar));
  411. free(pointindex);
  412. free(membership);
  413. free(reventry);
  414. fprintf(stderr,"Paring/rerouting redundant branches... ");
  415. /* The tree is likely big and redundant. Pare and reroute branches */
  416. {
  417. int changedflag=1;
  418. while(changedflag){
  419. changedflag=0;
  420. /* span the tree node by node; list unique decision nodes and
  421. short circuit redundant branches */
  422. for(i=0;i<t->aux;){
  423. int k;
  424. /* check list of unique decisions */
  425. for(j=0;j<i;j++)
  426. if(_node_eq(t,i,j))break;
  427. if(j<i){
  428. /* a redundant entry; find all higher nodes referencing it and
  429. short circuit them to the previously noted unique entry */
  430. changedflag=1;
  431. for(k=0;k<t->aux;k++){
  432. if(t->ptr0[k]==-i)t->ptr0[k]=-j;
  433. if(t->ptr1[k]==-i)t->ptr1[k]=-j;
  434. }
  435. /* Now, we need to fill in the hole from this redundant
  436. entry in the listing. Insert the last entry in the list.
  437. Fix the forward pointers to that last entry */
  438. t->aux--;
  439. t->ptr0[i]=t->ptr0[t->aux];
  440. t->ptr1[i]=t->ptr1[t->aux];
  441. t->p[i]=t->p[t->aux];
  442. t->q[i]=t->q[t->aux];
  443. for(k=0;k<t->aux;k++){
  444. if(t->ptr0[k]==-t->aux)t->ptr0[k]=-i;
  445. if(t->ptr1[k]==-t->aux)t->ptr1[k]=-i;
  446. }
  447. /* hole plugged */
  448. }else
  449. i++;
  450. }
  451. fprintf(stderr,"\rParing/rerouting redundant branches... "
  452. "%ld remaining ",t->aux);
  453. }
  454. fprintf(stderr,"\n");
  455. }
  456. }
  457. /* run all training points through the decision tree to get a final
  458. probability count */
  459. {
  460. long *probability=malloc(c->entries*sizeof(long));
  461. for(i=0;i<c->entries;i++)probability[i]=1; /* trivial guard */
  462. b->dim=c->dim;
  463. /* sigh. A necessary hack */
  464. for(i=0;i<t->aux;i++)t->p[i]*=c->dim;
  465. for(i=0;i<t->aux;i++)t->q[i]*=c->dim;
  466. for(i=0;i<v->points;i++){
  467. /* we use the linear matcher regardless becuase the trainer
  468. doesn't convert log to linear */
  469. int ret=_best(b,v->pointlist+i*v->elements,1);
  470. probability[ret]++;
  471. if(!(i&0xff))spinnit("counting hits... ",v->points-i);
  472. }
  473. for(i=0;i<t->aux;i++)t->p[i]/=c->dim;
  474. for(i=0;i<t->aux;i++)t->q[i]/=c->dim;
  475. build_tree_from_lengths(c->entries,probability,c->lengthlist);
  476. free(probability);
  477. }
  478. /* Sort the entries by codeword length, short to long (eases
  479. assignment and packing to do it now) */
  480. {
  481. long *wordlen=c->lengthlist;
  482. long *index=malloc(c->entries*sizeof(long));
  483. long *revindex=malloc(c->entries*sizeof(long));
  484. int k;
  485. for(i=0;i<c->entries;i++)index[i]=i;
  486. isortvals=c->lengthlist;
  487. qsort(index,c->entries,sizeof(long),iascsort);
  488. /* rearrange storage; ptr0/1 first as it needs a reverse index */
  489. /* n and c stay unchanged */
  490. for(i=0;i<c->entries;i++)revindex[index[i]]=i;
  491. for(i=0;i<t->aux;i++){
  492. if(!(i&0x3f))spinnit("sorting... ",t->aux-i);
  493. if(t->ptr0[i]>=0)t->ptr0[i]=revindex[t->ptr0[i]];
  494. if(t->ptr1[i]>=0)t->ptr1[i]=revindex[t->ptr1[i]];
  495. t->p[i]=revindex[t->p[i]];
  496. t->q[i]=revindex[t->q[i]];
  497. }
  498. free(revindex);
  499. /* map lengthlist and vallist with index */
  500. c->lengthlist=calloc(c->entries,sizeof(long));
  501. b->valuelist=malloc(sizeof(float)*c->entries*c->dim);
  502. c->quantlist=malloc(sizeof(long)*c->entries*c->dim);
  503. for(i=0;i<c->entries;i++){
  504. long e=index[i];
  505. for(k=0;k<c->dim;k++){
  506. b->valuelist[i*c->dim+k]=v->entrylist[e*c->dim+k];
  507. c->quantlist[i*c->dim+k]=quantlist[e*c->dim+k];
  508. }
  509. c->lengthlist[i]=wordlen[e];
  510. }
  511. free(wordlen);
  512. }
  513. fprintf(stderr,"Done. \n\n");
  514. }