vqsplit.c 19 KB

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