]> git.llucax.com Git - z.facultad/75.06/jacu.git/blob - src/statichuff/statichuff.c
0632e361aac65a3782bea43d65b8c974c755ebdf
[z.facultad/75.06/jacu.git] / src / statichuff / statichuff.c
1
2 #include "statichuff.h"
3 #include <stdlib.h>
4 #include <string.h>
5
6 void putbit(char bit, char restart, char flush, VFILE *fp)
7 {
8         static unsigned long int bits_buffer = 0;
9         static unsigned char bits_used = 0;     
10
11         /* me obligan a emitir el output */
12         if ((flush == 1) && (bits_used > 0)) {
13                 bits_buffer = bits_buffer << ((sizeof(unsigned long int)*8) - bits_used);
14                 vfwrite(&bits_buffer,sizeof(unsigned long int),1,fp);
15                 bits_buffer = 0;
16                 bits_used = 0;
17                 return;
18         }       
19         /* me indican que comienza un nuevo output */
20         if (restart) {
21                 bits_buffer = 0;
22                 bits_used = 0;
23         }                       
24         /* inserto el bit en el buffer */       
25         bits_buffer = bits_buffer << 1;
26         bits_buffer |= bit;
27         bits_used++;
28         
29         /* lleno el buffer, escribo */
30         if (bits_used == 32) {
31                 vfwrite(&bits_buffer,sizeof(unsigned long int),1,fp);
32                 bits_buffer = 0;
33                 bits_used = 0;
34         }       
35         return;
36 }
37
38 void shuff_cpynode(SHUFFNODE *node1, SHUFFNODE *node2)
39 {
40         node1->symbol = node2->symbol;
41         node1->freq = node2->freq;
42         node1->lchild = node2->lchild;
43         node1->rchild = node2->rchild;  
44 }
45
46 int shuff_compnode(const void *node1, const void *node2)
47 {       
48         if (((SHUFFNODE*)node1)->freq < ((SHUFFNODE*)node2)->freq) return 1;
49         if (((SHUFFNODE*)node1)->freq > ((SHUFFNODE*)node2)->freq) return -1;
50         return 0;
51 }
52
53 int shuff_rescalefreq(t_freq *freqtable)
54
55         int i;
56         t_freq totalfreq = 0;
57         
58         /* Divido por la mitad las frecuencias, asegurando de no perder */
59         for (i = 0; i < 256; i++) {             
60                 freqtable[i] = (freqtable[i] >> 2) | 1;
61                 totalfreq += freqtable[i];
62         }
63         
64         return totalfreq;
65 }
66
67 int shuff_scanfreq_chunk(HUFF_STATE *chunkshuff, char* chunk, int chunksize)
68 {       
69         /* Locals */                    
70         int i = 0;
71         unsigned char symbol = 0;       
72                 
73         /* Contamos las frecuencias del chunk a menos que se use un canonico */                 
74         if (!chunkshuff->canonic) {
75                 for (i = 0; i < chunksize; ++i) {                               
76                         symbol = chunk[i];              
77                         chunkshuff->freqtable[symbol] += 1;
78                         chunkshuff->sumfreq += 1;
79                                 
80                         /* Si llegue al tope de freq acumulada, halve em */
81                         if (chunkshuff->sumfreq == 14930352) 
82                                 chunkshuff->sumfreq = shuff_rescalefreq(chunkshuff->freqtable);
83                 }
84         }
85         
86         /* Dumpeamos el chunk en el temporal homero */
87         fwrite(chunk,chunksize,1,chunkshuff->coderfp);
88                 
89         return 1;
90 }
91
92 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
93 {
94         /* Locals */    
95         FILE *fp;
96         t_freq sumfreq = 0;
97         int i,symbol;
98         
99         /* Inicializamos la tabla de frecuencias */     
100         for (i = 0; i < 256; ++i) freqtable[i] = 0;
101                 
102         /* Abrimos el file */
103         if ((fp = fopen(inputfile,"r")) == NULL) return 0;
104         while (!feof(fp)) {             
105                 /* Contamos las frecuencias */          
106                 symbol = fgetc(fp);
107                 if (symbol == EOF) continue;
108                 
109                 freqtable[symbol]++;            
110                 ++sumfreq;
111                                 
112                 /* Si llegue al tope de freq acumulada, halve em */
113                 if (sumfreq == 14930352) 
114                         sumfreq = shuff_rescalefreq(freqtable);
115         }
116         
117         fclose(fp);
118         return 1;
119 }
120
121 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
122 {
123         int i,j = 0,nonzero = 0;        
124         SHUFFNODE *inputlist;
125         
126         /* Calculo cuantas frequencias > 0 hay y creo la tabla */
127         for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
128         inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
129                 
130         /* Cargo la inputlist del huffman solo con freqs > 0 */
131         for (i = 0; i < 256; ++i)
132                 if (freqtable[i] > 0) {                 
133                         inputlist[j].symbol = i;
134                         inputlist[j].freq = freqtable[i];
135                         inputlist[j].lchild = NULL;
136                         inputlist[j].rchild = NULL;                     
137                         j++;
138                 }
139                 
140         *nonzerofreqs = nonzero;
141         return inputlist;
142 }
143
144 SHUFFNODE *shuff_buildtree(t_freq *ftable)
145 {
146         SHUFFNODE *lastsymbol;
147         SHUFFNODE *node1,*node2,*root;
148         SHUFFNODE *inputlist;
149         int freqcount = 0;
150
151         /* Genero la input list en base a la cual genera el arbol */
152         inputlist = shuff_buildlist(ftable, &freqcount);        
153         lastsymbol = inputlist+(freqcount-1);
154         
155         while (lastsymbol > inputlist) {                
156                 /* Ordeno la lista por frecuencia descendente */
157                 qsort(inputlist,freqcount,sizeof(SHUFFNODE),shuff_compnode);                            
158                 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
159                 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
160                 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
161                 shuff_cpynode(node1,lastsymbol-1);
162                 shuff_cpynode(node2,lastsymbol);                
163                 lastsymbol -= 1;
164                 /* Nodo ficticio con la suma de las probs y los ptros a childs */
165                 lastsymbol->symbol = 256;
166                 lastsymbol->freq = node1->freq + node2->freq;
167                 lastsymbol->lchild = node1;
168                 lastsymbol->rchild = node2;
169                 --freqcount;
170         }
171         
172         /* Copio la raiz para poder liberar la lista sin perderla */
173         root = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
174         shuff_cpynode(root,lastsymbol);
175         
176         /* Free up mem */
177         free(inputlist);
178         
179         /* Devuelvo el puntero a la raiz del arbol de huffman */
180         return root;
181 }
182
183 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
184 {
185         int i,j;
186         unsigned short int auxcode;
187         unsigned char bit;
188         
189         for (i = 0; i < 256; ++i) {
190                 if (codetable[i].codelength > 0) {
191                         auxcode = codetable[i].code;                    
192                         printf("Symbol:%i  Freq: %lu  Code:",i,freqtable[i]);
193                         for (j = codetable[i].codelength-1; j >= 0; --j) {
194                                 auxcode = codetable[i].code;                    
195                                 auxcode = auxcode >> j;
196                                 bit = auxcode & 1;                              
197                                 printf("%i",bit);
198                         }
199                         printf("  Length:%i\n",codetable[i].codelength);
200                 }               
201         }
202 }
203
204 void shuff_zerocodes(SHUFFCODE *table)
205 {
206         int i;
207         
208         /* Inicializo los codigos prefijos */   
209         for (i = 0; i < 256; ++i) {
210                 table[i].code = 0;
211                 table[i].codelength = 0;
212         }
213 }
214
215 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
216 {
217         if (node->symbol < 256) {
218                 /* Guardo el codigo en la tabla */
219                 table[node->symbol].code = code;
220                 table[node->symbol].codelength = level;         
221         }
222         else {
223                 code = code << 1;
224                 shuff_buildcodes(table,node->lchild,level+1,code);
225                 code |= 1;
226                 shuff_buildcodes(table,node->rchild,level+1,code);
227         }
228 }
229
230 int shuff_encode_symbols(HUFF_STATE *shuff, SHUFFCODE *ctable)
231 {
232         FILE *fpsource;
233         VFILE *fpdest;
234         int symbol,i;
235         unsigned long int sourcesize;
236         char bit;
237         SHUFFCODE symbolcode;
238                 
239         /* Abrimos el source y el destino */
240         if (shuff->coderfp != NULL) fclose(shuff->coderfp); /* close bychunk temp file */
241         if ((fpsource = fopen(shuff->sourcefile,"r")) == NULL) return 0;
242         if ((fpdest = vfopen(shuff->targetfile,"w",shuff->volsize)) == NULL) return 0;
243                 
244         /* Guardamos el size el archivo original e inputlist como header */
245         fseek(fpsource,0,SEEK_END);
246         sourcesize = ftell(fpsource);
247         vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
248         vfwrite(shuff->freqtable,sizeof(t_freq),256,fpdest);
249         
250         /* Encodeo */
251         fseek(fpsource,0,SEEK_SET);
252         while (!feof(fpsource)) {
253                 /* Levanto un symbolo (byte) */         
254                 symbol = fgetc(fpsource);
255                 if (symbol == EOF) continue;
256                 
257                 /* Cargamos el codigo y lo emitimos */
258                 symbolcode = ctable[symbol];
259                 for (i = symbolcode.codelength; i > 0; --i) {
260                         bit = (symbolcode.code >> (i-1)) & 1;
261                         putbit(bit,0,0,fpdest);
262                 }               
263         }
264         
265         /* Hacemos un flush de lo que haya quedado en el buffer de salida */
266         putbit(0,0,1,fpdest);
267         fclose(fpsource);
268         vfclose(fpdest);
269         return 1;       
270 }
271
272 int shuff_encode_file(HUFF_STATE *shuff)
273 {
274         /* Locals */            
275         SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
276         
277         /* Veo si debo armar una freqtable o si esta preloaded */
278         if ((!shuff->canonic) && (!shuff->bychunk)) 
279                 if (!shuff_scanfreq(shuff->sourcefile,shuff->freqtable)) return 0;
280         
281         /* Genero el arbol de huffman */
282         shuff->codetree = shuff_buildtree(shuff->freqtable);
283
284         /* Armo la tabla de codigos prefijos para el encoder */
285         shuff_zerocodes(codetable);
286         shuff_buildcodes(codetable,shuff->codetree,0,0);
287         /*shuff_printcodes(codetable,shuff->freqtable);*/
288
289         /* Encodeo byte per byte */
290         shuff_encode_symbols(shuff,codetable);
291         
292         /* Free up memory baby yeah */  
293         free(codetable);
294         
295         return 1;
296 }
297
298 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer, 
299                                                          int *bitsleft, unsigned short int *symbol)
300 {
301         char bit = 0;
302                 
303         /* Levanto el symbolo y si es uno valido, devuelvo */
304         *symbol = entrynode->symbol;
305         if (*symbol != 256) return entrynode;           
306         if (*bitsleft == 0) return entrynode;
307                 
308         /* Obtengo otro bit a procesar y me muevo en el arbol */
309         bit = (buffer >> ((*bitsleft)-1)) & 1;  
310         --(*bitsleft);
311         if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
312         else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
313 }
314
315 int shuff_decode_chunk(HUFF_STATE *shuff, char *chunk, int chunksize, int *decodedbytes)
316 {
317         SHUFFNODE *currnode = shuff->codetree;  
318         unsigned short int decoded_symbol;      
319         *decodedbytes = 0;
320         
321         while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
322                 
323                 /* Leo un buffer de 32 bits si es que quedo vacio el anterior */
324                 if (shuff->bitsleft == 0) {
325                         if (vfread(&(shuff->codebuffer),sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
326                         shuff->bitsleft = sizeof(unsigned long int) * 8;
327                 }
328                 
329                 /* Proceso el buffer sacando simbolos till se me agote el buffer, file o chunk */
330                 while ((shuff->bitsleft > 0) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {        
331                         currnode = shuff_decode_symbols(currnode,shuff->codebuffer,&(shuff->bitsleft),&decoded_symbol);
332                         /* Si obtuve un symbolo valido lo emito*/
333                         if (decoded_symbol != 256) {                            
334                                 chunk[(*decodedbytes)++] = decoded_symbol;
335                                 currnode = shuff->codetree;                             
336                                 --(shuff->bytesleft);
337                         }                                               
338                 }               
339         }
340         
341         if (shuff->bytesleft == 0) return 0;
342         else return 1;
343 }
344
345 int shuff_decode_file(HUFF_STATE *shuff)
346 {       
347         SHUFFNODE *currnode;    
348         unsigned long int codebuffer;   
349         FILE *fpdest;
350         unsigned short int decoded_symbol;
351         int bitsleft;   
352         
353         /* Comienzo a decodificar, pues la tabla ya la levante en el decinit */
354         if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;  
355         currnode = shuff->codetree;
356         
357         while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
358                 
359                 /* Leo un buffer de 32 bits */
360                 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
361                 bitsleft = sizeof(unsigned long int) * 8;
362                 
363                 /* Proceso el buffer sacando simbolos hasta que se me agote */
364                 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {      
365                         currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
366                         /* Si obtuve un symbolo valido lo emito*/
367                         if (decoded_symbol != 256) {
368                                 fputc(decoded_symbol,fpdest);
369                                 currnode = shuff->codetree;
370                                 --(shuff->bytesleft);
371                         }                                               
372                 }               
373         }
374                         
375         /* Close destination */
376         fclose(fpdest); 
377         
378         return 1;
379 }
380
381 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
382 {
383         /* Locals */
384         HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));                    
385         shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256); 
386         
387         /* Init fields */
388         shuff->codebuffer = 0;
389         shuff->bitsleft = 0;
390         shuff->coderfp = NULL;
391         shuff->targetfile = NULL;
392         shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
393         strcpy(shuff->sourcefile,inputfile);
394         if (outputfile != NULL) {
395                 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
396                 strcpy(shuff->targetfile,outputfile);
397         }       
398         
399         /* Levanto cuantos bytes debo decodificar y la freqtable */
400         if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return NULL;  
401         vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
402         vfread(shuff->freqtable,sizeof(t_freq),256,shuff->decoderfp);           
403         /* Armo el arbol de huffman que uso para decodificar */
404         shuff->codetree = shuff_buildtree(shuff->freqtable);
405         
406         return shuff;
407 }
408
409 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
410 {
411         /* Locals */
412         HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));                   
413         int i;
414         
415         /* Inicializo la estructura para trabajar con Huff Static by File */
416         fshuff->coderfp = NULL; 
417         fshuff->decoderfp = NULL;       
418         fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
419         fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
420         strcpy(fshuff->sourcefile,inputfile);   
421         strcpy(fshuff->targetfile,outputfile);
422         fshuff->volsize = volsize;
423         fshuff->bychunk = 0;
424         fshuff->canonic = 0;    
425         fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
426         for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;     
427         fshuff->sumfreq = 0;            
428         fshuff->codetree = NULL;
429         
430         return fshuff;
431 }
432
433 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
434 {
435         /* Locals */
436         HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));                   
437         int i;
438         
439         /* Inicializo la estructura para trabajar con Huff Static by Chunks */          
440         cshuff->decoderfp = NULL;
441         cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
442         cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
443         strcpy(cshuff->targetfile,outputfile);  
444         strcpy(cshuff->sourcefile,outputfile);
445         strcat(cshuff->sourcefile,"~"); 
446         cshuff->volsize = volsize;
447         cshuff->bychunk = 1;
448         cshuff->canonic = 0;
449         cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);        
450         for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;     
451         cshuff->sumfreq = 0;    
452         cshuff->codetree = NULL;        
453         
454         /* Abrimos un archivo temporal para ir tirando los chunks */    
455         if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;     
456
457         return cshuff;
458 }
459
460 int shuff_loadmodel(HUFF_STATE *shuff, char *modelfile) {
461
462         FILE *fp;
463         
464         if ((shuff) && (shuff->freqtable) && (modelfile)) {
465                 /* Cargo el modelo de disco */
466                 if ((fp = fopen(modelfile,"r")) == NULL) return 0;
467                 if (fread(shuff->freqtable,sizeof(t_freq),256,fp) != 256) return 0;
468                 shuff->canonic = 1;
469                 if (fp) fclose(fp);             
470                 return 1;
471         }       
472         return 0;       
473 }
474
475 int shuff_savemodel(HUFF_STATE *shuff) {
476
477         FILE *fp;
478         char *auxfilename;
479         char *stopchar;
480         
481         if ((shuff) && (shuff->targetfile) && (shuff->freqtable)) {
482                 /* Preparo el nombre del archivo con la tabla */
483                 auxfilename = (char*)malloc(strlen(shuff->targetfile)+1);               
484                 stopchar = strrchr(shuff->targetfile,'.');              
485                 strncpy(auxfilename,shuff->targetfile,stopchar - shuff->targetfile);
486                 auxfilename[stopchar - shuff->targetfile] = 0;
487                 strcat(auxfilename,".ftb");
488                 
489                 /* Lo creamos y dumpeamos la tabla de frecuencias (modelo) */
490                 if ((fp = fopen(auxfilename,"w")) == NULL) return 0;
491                 fwrite(shuff->freqtable,sizeof(t_freq),256,fp);
492                 if (fp) fclose(fp);
493                                 
494                 return 1;
495         }       
496         return 0;
497 }
498
499 void shuff_deinit_encoder(HUFF_STATE *shuff)
500 {
501         /* Libero mallocs y cierro archivos */
502         if (shuff->freqtable) free(shuff->freqtable);
503         if (shuff->coderfp) fclose(shuff->coderfp);
504         if (shuff->bychunk) unlink(shuff->sourcefile);
505         if (shuff->sourcefile) free(shuff->sourcefile); 
506         if (shuff->targetfile) free(shuff->targetfile);                         
507         
508         /* Destruyo recursivamente el arbol de codigos */
509 }
510
511 void shuff_deinit_decoder(HUFF_STATE *shuff)
512 {
513         /* Libero mallocs y cierro archivos */  
514         if (shuff->freqtable) free(shuff->freqtable);
515         if (shuff->sourcefile != NULL) free(shuff->sourcefile);
516         if (shuff->targetfile != NULL) free(shuff->targetfile);
517         if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
518                 
519         /* Destruyo recursivamente el arbol de codigos */
520 }