latticepare.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. /********************************************************************
  2. * *
  3. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  4. * USE, DISTRIBUTION AND REPRODUCTION OF THIS SOURCE IS GOVERNED BY *
  5. * THE GNU LESSER/LIBRARY PUBLIC LICENSE, WHICH IS INCLUDED WITH *
  6. * THIS SOURCE. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  7. * *
  8. * THE OggVorbis 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: utility for paring low hit count cells from lattice codebook
  14. last mod: $Id: latticepare.c,v 1.5.2.2 2000/11/04 06:43:55 xiphmont Exp $
  15. ********************************************************************/
  16. #include <stdlib.h>
  17. #include <stdio.h>
  18. #include <math.h>
  19. #include <string.h>
  20. #include <errno.h>
  21. #include "vorbis/codebook.h"
  22. #include "../lib/sharedbook.h"
  23. #include "../lib/scales.h"
  24. #include "bookutil.h"
  25. #include "vqgen.h"
  26. #include "vqsplit.h"
  27. #include "../lib/os.h"
  28. /* Lattice codebooks have two strengths: important fetaures that are
  29. poorly modelled by global error minimization training (eg, strong
  30. peaks) are not neglected 2) compact quantized representation.
  31. A fully populated lattice codebook, however, swings point 1 too far
  32. in the opposite direction; rare features need not be modelled quite
  33. so religiously and as such, we waste bits unless we eliminate the
  34. least common cells. The codebook rep supports unused cells, so we
  35. need to tag such cells and build an auxiliary (non-thresh) search
  36. mechanism to find the proper match quickly */
  37. /* two basic steps; first is pare the cell for which dispersal creates
  38. the least additional error. This will naturally choose
  39. low-population cells and cells that have not taken on points from
  40. neighboring paring (but does not result in the lattice collapsing
  41. inward and leaving low population ares totally unmodelled). After
  42. paring has removed the desired number of cells, we need to build an
  43. auxiliary search for each culled point */
  44. /* Although lattice books (due to threshhold-based matching) do not
  45. actually use error to make cell selections (in fact, it need not
  46. bear any relation), the 'secondbest' entry finder here is in fact
  47. error/distance based, so latticepare is only useful on such books */
  48. /* command line:
  49. latticepare latticebook.vqh input_data.vqd <target_cells>
  50. produces a new output book on stdout
  51. */
  52. static float _dist(int el,float *a, float *b){
  53. int i;
  54. float acc=0.;
  55. for(i=0;i<el;i++){
  56. float val=(a[i]-b[i]);
  57. acc+=val*val;
  58. }
  59. return(acc);
  60. }
  61. static float *pointlist;
  62. static long points=0;
  63. void add_vector(codebook *b,float *vec,long n){
  64. int dim=b->dim,i,j;
  65. int step=n/dim;
  66. for(i=0;i<step;i++){
  67. for(j=i;j<n;j+=step){
  68. pointlist[points++]=vec[j];
  69. }
  70. }
  71. }
  72. static int bestm(codebook *b,float *vec){
  73. encode_aux_threshmatch *tt=b->c->thresh_tree;
  74. int dim=b->dim;
  75. int i,k,o;
  76. int best=0;
  77. /* what would be the closest match if the codebook was fully
  78. populated? */
  79. for(k=0,o=dim-1;k<dim;k++,o--){
  80. int i;
  81. for(i=0;i<tt->threshvals-1;i++)
  82. if(vec[o]<tt->quantthresh[i])break;
  83. best=(best*tt->quantvals)+tt->quantmap[i];
  84. }
  85. return(best);
  86. }
  87. static int closest(codebook *b,float *vec,int current){
  88. encode_aux_threshmatch *tt=b->c->thresh_tree;
  89. int dim=b->dim;
  90. int i,k,o;
  91. float bestmetric=0;
  92. int bestentry=-1;
  93. int best=bestm(b,vec);
  94. if(current<0 && b->c->lengthlist[best]>0)return best;
  95. for(i=0;i<b->entries;i++){
  96. if(b->c->lengthlist[i]>0 && i!=best && i!=current){
  97. float thismetric=_dist(dim, vec, b->valuelist+i*dim);
  98. if(bestentry==-1 || thismetric<bestmetric){
  99. bestentry=i;
  100. bestmetric=thismetric;
  101. }
  102. }
  103. }
  104. return(bestentry);
  105. }
  106. static float _heuristic(codebook *b,float *ppt,int secondbest){
  107. float *secondcell=b->valuelist+secondbest*b->dim;
  108. int best=bestm(b,ppt);
  109. float *firstcell=b->valuelist+best*b->dim;
  110. float error=_dist(b->dim,firstcell,secondcell);
  111. float *zero=alloca(b->dim*sizeof(float));
  112. float fromzero;
  113. memset(zero,0,b->dim*sizeof(float));
  114. fromzero=sqrt(_dist(b->dim,firstcell,zero));
  115. return(error/fromzero);
  116. }
  117. static int longsort(const void *a, const void *b){
  118. return **(long **)b-**(long **)a;
  119. }
  120. void usage(void){
  121. fprintf(stderr,"Ogg/Vorbis lattice codebook paring utility\n\n"
  122. "usage: latticepare book.vqh data.vqd <target_cells> <protected_cells> base\n"
  123. "where <target_cells> is the desired number of final cells (or -1\n"
  124. " for no change)\n"
  125. " <protected_cells> is the number of highest-hit count cells\n"
  126. " to protect from dispersal\n"
  127. " base is the base name (not including .vqh) of the new\n"
  128. " book\n\n");
  129. exit(1);
  130. }
  131. int main(int argc,char *argv[]){
  132. char *basename;
  133. codebook *b=NULL;
  134. int entries=0;
  135. int dim=0;
  136. long i,j,target=-1,protect=-1;
  137. FILE *out=NULL;
  138. int argnum=0;
  139. argv++;
  140. if(*argv==NULL){
  141. usage();
  142. exit(1);
  143. }
  144. while(*argv){
  145. if(*argv[0]=='-'){
  146. argv++;
  147. }else{
  148. switch (argnum++){
  149. case 0:case 1:
  150. {
  151. /* yes, this is evil. However, it's very convenient to parse file
  152. extentions */
  153. /* input file. What kind? */
  154. char *dot;
  155. char *ext=NULL;
  156. char *name=strdup(*argv++);
  157. dot=strrchr(name,'.');
  158. if(dot)
  159. ext=dot+1;
  160. else{
  161. ext="";
  162. }
  163. /* codebook */
  164. if(!strcmp(ext,"vqh")){
  165. basename=strrchr(name,'/');
  166. if(basename)
  167. basename=strdup(basename)+1;
  168. else
  169. basename=strdup(name);
  170. dot=strrchr(basename,'.');
  171. if(dot)*dot='\0';
  172. b=codebook_load(name);
  173. dim=b->dim;
  174. entries=b->entries;
  175. }
  176. /* data file; we do actually need to suck it into memory */
  177. /* we're dealing with just one book, so we can de-interleave */
  178. if(!strcmp(ext,"vqd") && !points){
  179. int cols;
  180. long lines=0;
  181. char *line;
  182. float *vec;
  183. FILE *in=fopen(name,"r");
  184. if(!in){
  185. fprintf(stderr,"Could not open input file %s\n",name);
  186. exit(1);
  187. }
  188. reset_next_value();
  189. line=setup_line(in);
  190. /* count cols before we start reading */
  191. {
  192. char *temp=line;
  193. while(*temp==' ')temp++;
  194. for(cols=0;*temp;cols++){
  195. while(*temp>32)temp++;
  196. while(*temp==' ')temp++;
  197. }
  198. }
  199. vec=alloca(cols*sizeof(float));
  200. /* count, then load, to avoid fragmenting the hell out of
  201. memory */
  202. while(line){
  203. lines++;
  204. for(j=0;j<cols;j++)
  205. if(get_line_value(in,vec+j)){
  206. fprintf(stderr,"Too few columns on line %ld in data file\n",lines);
  207. exit(1);
  208. }
  209. if((lines&0xff)==0)spinnit("counting samples...",lines*cols);
  210. line=setup_line(in);
  211. }
  212. pointlist=_ogg_malloc((cols*lines+entries*dim)*sizeof(float));
  213. rewind(in);
  214. line=setup_line(in);
  215. while(line){
  216. lines--;
  217. for(j=0;j<cols;j++)
  218. if(get_line_value(in,vec+j)){
  219. fprintf(stderr,"Too few columns on line %ld in data file\n",lines);
  220. exit(1);
  221. }
  222. /* deinterleave, add to heap */
  223. add_vector(b,vec,cols);
  224. if((lines&0xff)==0)spinnit("loading samples...",lines*cols);
  225. line=setup_line(in);
  226. }
  227. fclose(in);
  228. }
  229. }
  230. break;
  231. case 2:
  232. target=atol(*argv++);
  233. if(target==0)target=entries;
  234. break;
  235. case 3:
  236. protect=atol(*argv++);
  237. break;
  238. case 4:
  239. {
  240. char *buff=alloca(strlen(*argv)+5);
  241. sprintf(buff,"%s.vqh",*argv);
  242. basename=*argv++;
  243. out=fopen(buff,"w");
  244. if(!out){
  245. fprintf(stderr,"unable ot open %s for output",buff);
  246. exit(1);
  247. }
  248. }
  249. break;
  250. default:
  251. usage();
  252. }
  253. }
  254. }
  255. if(!entries || !points || !out)usage();
  256. if(target==-1)usage();
  257. /* add guard points */
  258. for(i=0;i<entries;i++)
  259. for(j=0;j<dim;j++)
  260. pointlist[points++]=b->valuelist[i*dim+j];
  261. points/=dim;
  262. /* set up auxiliary vectors for error tracking */
  263. {
  264. encode_aux_nearestmatch *nt=NULL;
  265. long pointssofar=0;
  266. long *pointindex;
  267. long indexedpoints=0;
  268. long *entryindex;
  269. long *reventry;
  270. long *membership=_ogg_malloc(points*sizeof(long));
  271. long *firsthead=_ogg_malloc(entries*sizeof(long));
  272. long *secondary=_ogg_malloc(points*sizeof(long));
  273. long *secondhead=_ogg_malloc(entries*sizeof(long));
  274. long *cellcount=_ogg_calloc(entries,sizeof(long));
  275. long *cellcount2=_ogg_calloc(entries,sizeof(long));
  276. float *cellerror=_ogg_calloc(entries,sizeof(float));
  277. float *cellerrormax=_ogg_calloc(entries,sizeof(float));
  278. long cellsleft=entries;
  279. for(i=0;i<points;i++)membership[i]=-1;
  280. for(i=0;i<entries;i++)firsthead[i]=-1;
  281. for(i=0;i<points;i++)secondary[i]=-1;
  282. for(i=0;i<entries;i++)secondhead[i]=-1;
  283. for(i=0;i<points;i++){
  284. /* assign vectors to the nearest cell. Also keep track of second
  285. nearest for error statistics */
  286. float *ppt=pointlist+i*dim;
  287. int firstentry=closest(b,ppt,-1);
  288. int secondentry=closest(b,ppt,firstentry);
  289. float firstmetric=_dist(dim,b->valuelist+dim*firstentry,ppt);
  290. float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
  291. if(!(i&0xff))spinnit("initializing... ",points-i);
  292. membership[i]=firsthead[firstentry];
  293. firsthead[firstentry]=i;
  294. secondary[i]=secondhead[secondentry];
  295. secondhead[secondentry]=i;
  296. if(i<points-entries){
  297. cellerror[firstentry]+=secondmetric-firstmetric;
  298. cellerrormax[firstentry]=max(cellerrormax[firstentry],
  299. _heuristic(b,ppt,secondentry));
  300. cellcount[firstentry]++;
  301. cellcount2[secondentry]++;
  302. }
  303. }
  304. /* which cells are most heavily populated? Protect as many from
  305. dispersal as the user has requested */
  306. {
  307. long **countindex=_ogg_calloc(entries,sizeof(long *));
  308. for(i=0;i<entries;i++)countindex[i]=cellcount+i;
  309. qsort(countindex,entries,sizeof(long *),longsort);
  310. for(i=0;i<protect;i++){
  311. int ptr=countindex[i]-cellcount;
  312. cellerrormax[ptr]=9e50;
  313. }
  314. }
  315. {
  316. fprintf(stderr,"\r");
  317. for(i=0;i<entries;i++){
  318. /* decompose index */
  319. int entry=i;
  320. for(j=0;j<dim;j++){
  321. fprintf(stderr,"%d:",entry%b->c->thresh_tree->quantvals);
  322. entry/=b->c->thresh_tree->quantvals;
  323. }
  324. fprintf(stderr,":%ld/%ld, ",cellcount[i],cellcount2[i]);
  325. }
  326. fprintf(stderr,"\n");
  327. }
  328. /* do the automatic cull request */
  329. while(cellsleft>target){
  330. int bestcell=-1;
  331. float besterror=0;
  332. float besterror2=0;
  333. long head=-1;
  334. char spinbuf[80];
  335. sprintf(spinbuf,"cells left to eliminate: %ld : ",cellsleft-target);
  336. /* find the cell with lowest removal impact */
  337. for(i=0;i<entries;i++){
  338. if(b->c->lengthlist[i]>0){
  339. if(bestcell==-1 || cellerrormax[i]<=besterror2){
  340. if(bestcell==-1 || cellerrormax[i]<besterror2 ||
  341. besterror>cellerror[i]){
  342. besterror=cellerror[i];
  343. besterror2=cellerrormax[i];
  344. bestcell=i;
  345. }
  346. }
  347. }
  348. }
  349. fprintf(stderr,"\reliminating cell %d \n"
  350. " dispersal error of %g max/%g total (%ld hits)\n",
  351. bestcell,besterror2,besterror,cellcount[bestcell]);
  352. /* disperse it. move each point out, adding it (properly) to
  353. the second best */
  354. b->c->lengthlist[bestcell]=0;
  355. head=firsthead[bestcell];
  356. firsthead[bestcell]=-1;
  357. while(head!=-1){
  358. /* head is a point number */
  359. float *ppt=pointlist+head*dim;
  360. int firstentry=closest(b,ppt,-1);
  361. int secondentry=closest(b,ppt,firstentry);
  362. float firstmetric=_dist(dim,b->valuelist+dim*firstentry,ppt);
  363. float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
  364. long next=membership[head];
  365. if(head<points-entries){
  366. cellcount[firstentry]++;
  367. cellcount[bestcell]--;
  368. cellerror[firstentry]+=secondmetric-firstmetric;
  369. cellerrormax[firstentry]=max(cellerrormax[firstentry],
  370. _heuristic(b,ppt,secondentry));
  371. }
  372. membership[head]=firsthead[firstentry];
  373. firsthead[firstentry]=head;
  374. head=next;
  375. if(cellcount[bestcell]%128==0)
  376. spinnit(spinbuf,cellcount[bestcell]+cellcount2[bestcell]);
  377. }
  378. /* now see that all points that had the dispersed cell as second
  379. choice have second choice reassigned */
  380. head=secondhead[bestcell];
  381. secondhead[bestcell]=-1;
  382. while(head!=-1){
  383. float *ppt=pointlist+head*dim;
  384. /* who are we assigned to now? */
  385. int firstentry=closest(b,ppt,-1);
  386. /* what is the new second closest match? */
  387. int secondentry=closest(b,ppt,firstentry);
  388. /* old second closest is the cell being disbanded */
  389. float oldsecondmetric=_dist(dim,b->valuelist+dim*bestcell,ppt);
  390. /* new second closest error */
  391. float secondmetric=_dist(dim,b->valuelist+dim*secondentry,ppt);
  392. long next=secondary[head];
  393. if(head<points-entries){
  394. cellcount2[secondentry]++;
  395. cellcount2[bestcell]--;
  396. cellerror[firstentry]+=secondmetric-oldsecondmetric;
  397. cellerrormax[firstentry]=max(cellerrormax[firstentry],
  398. _heuristic(b,ppt,secondentry));
  399. }
  400. secondary[head]=secondhead[secondentry];
  401. secondhead[secondentry]=head;
  402. head=next;
  403. if(cellcount2[bestcell]%128==0)
  404. spinnit(spinbuf,cellcount2[bestcell]);
  405. }
  406. cellsleft--;
  407. }
  408. /* paring is over. Build decision trees using points that now fall
  409. through the thresh matcher. */
  410. /* we don't free membership; we flatten it in order to use in lp_split */
  411. for(i=0;i<entries;i++){
  412. long head=firsthead[i];
  413. spinnit("rearranging membership cache... ",entries-i);
  414. while(head!=-1){
  415. long next=membership[head];
  416. membership[head]=i;
  417. head=next;
  418. }
  419. }
  420. free(secondhead);
  421. free(firsthead);
  422. free(cellerror);
  423. free(cellerrormax);
  424. free(secondary);
  425. pointindex=_ogg_malloc(points*sizeof(long));
  426. /* make a point index of fall-through points */
  427. for(i=0;i<points;i++){
  428. int best=_best(b,pointlist+i*dim,1);
  429. if(best==-1)
  430. pointindex[indexedpoints++]=i;
  431. spinnit("finding orphaned points... ",points-i);
  432. }
  433. /* make an entry index */
  434. entryindex=_ogg_malloc(entries*sizeof(long));
  435. target=0;
  436. for(i=0;i<entries;i++){
  437. if(b->c->lengthlist[i]>0)
  438. entryindex[target++]=i;
  439. }
  440. /* make working space for a reverse entry index */
  441. reventry=_ogg_malloc(entries*sizeof(long));
  442. /* do the split */
  443. nt=b->c->nearest_tree=
  444. _ogg_calloc(1,sizeof(encode_aux_nearestmatch));
  445. nt->alloc=4096;
  446. nt->ptr0=_ogg_malloc(sizeof(long)*nt->alloc);
  447. nt->ptr1=_ogg_malloc(sizeof(long)*nt->alloc);
  448. nt->p=_ogg_malloc(sizeof(long)*nt->alloc);
  449. nt->q=_ogg_malloc(sizeof(long)*nt->alloc);
  450. nt->aux=0;
  451. fprintf(stderr,"Leaves added: %d \n",
  452. lp_split(pointlist,points,
  453. b,entryindex,target,
  454. pointindex,indexedpoints,
  455. membership,reventry,
  456. 0,&pointssofar));
  457. free(membership);
  458. free(reventry);
  459. free(pointindex);
  460. /* hack alert. I should just change the damned splitter and
  461. codebook writer */
  462. for(i=0;i<nt->aux;i++)nt->p[i]*=dim;
  463. for(i=0;i<nt->aux;i++)nt->q[i]*=dim;
  464. /* recount hits. Build new lengthlist. reuse entryindex storage */
  465. for(i=0;i<entries;i++)entryindex[i]=1;
  466. for(i=0;i<points-entries;i++){
  467. int best=_best(b,pointlist+i*dim,1);
  468. float *a=pointlist+i*dim;
  469. if(!(i&0xff))spinnit("counting hits...",i);
  470. if(best==-1){
  471. fprintf(stderr,"\nINTERNAL ERROR; a point count not be matched to a\n"
  472. "codebook entry. The new decision tree is broken.\n");
  473. exit(1);
  474. }
  475. entryindex[best]++;
  476. }
  477. for(i=0;i<nt->aux;i++)nt->p[i]/=dim;
  478. for(i=0;i<nt->aux;i++)nt->q[i]/=dim;
  479. /* the lengthlist builder doesn't actually deal with 0 hit entries.
  480. So, we pack the 'sparse' hit list into a dense list, then unpack
  481. the lengths after the build */
  482. {
  483. int upper=0;
  484. long *lengthlist=_ogg_calloc(entries,sizeof(long));
  485. for(i=0;i<entries;i++){
  486. if(b->c->lengthlist[i]>0)
  487. entryindex[upper++]=entryindex[i];
  488. else{
  489. if(entryindex[i]>1){
  490. fprintf(stderr,"\nINTERNAL ERROR; _best matched to unused entry\n");
  491. exit(1);
  492. }
  493. }
  494. }
  495. /* sanity check */
  496. if(upper != target){
  497. fprintf(stderr,"\nINTERNAL ERROR; packed the wrong number of entries\n");
  498. exit(1);
  499. }
  500. build_tree_from_lengths(upper,entryindex,lengthlist);
  501. upper=0;
  502. for(i=0;i<entries;i++){
  503. if(b->c->lengthlist[i]>0)
  504. b->c->lengthlist[i]=lengthlist[upper++];
  505. }
  506. }
  507. }
  508. /* we're done. write it out. */
  509. write_codebook(out,basename,b->c);
  510. fprintf(stderr,"\r \nDone.\n");
  511. return(0);
  512. }