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