]> git.llucax.com Git - z.facultad/75.06/jacu.git/blob - src/statichuff/statichuff.c
Borro .o en subdirectorios en el make clean.
[z.facultad/75.06/jacu.git] / src / statichuff / statichuff.c
1
2 #include "statichuff.h"
3 #include "../vfile/vfile.h"
4 #include <stdlib.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         /* frequencias en 1, por ello le sumo 1 antes de partir */
60         for (i = 0; i < 256; i++) {             
61                 freqtable[i] = (freqtable[i] << 2) | 1;
62                 totalfreq += freqtable[i];
63         }
64         
65         return totalfreq;
66 }
67
68 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
69 {
70         /* Locals */    
71         FILE *fp;
72         t_freq sumfreq = 0;
73         int i,symbol;
74         
75         /* Inicializamos la tabla de frecuencias */     
76         for (i = 0; i < 256; ++i) freqtable[i] = 0;
77                 
78         /* Abrimos el file */
79         if ((fp = fopen(inputfile,"r")) == NULL) return 0;
80         while (!feof(fp)) {             
81                 /* Contamos las frecuencias */          
82                 symbol = fgetc(fp);
83                 if (symbol == EOF) continue;
84                 
85                 freqtable[symbol]++;            
86                 ++sumfreq;
87                                 
88                 /* Si llegue al tope de freq acumulada, halve em */
89                 if (sumfreq == 14930352) 
90                         sumfreq = shuff_rescalefreq(freqtable);
91         }
92         
93         fclose(fp);
94         return 1;
95 }
96
97 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
98 {
99         int i,j = 0,nonzero = 0;        
100         SHUFFNODE *inputlist;
101         
102         /* Calculo cuantas frequencias > 0 hay y creo la tabla */
103         for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
104         inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
105                 
106         /* Cargo la inputlist del huffman solo con freqs > 0 */
107         for (i = 0; i < 256; ++i)
108                 if (freqtable[i] > 0) {                 
109                         inputlist[j].symbol = i;
110                         inputlist[j].freq = freqtable[i];
111                         inputlist[j].lchild = NULL;
112                         inputlist[j].rchild = NULL;                     
113                         j++;
114                 }
115                 
116         *nonzerofreqs = nonzero;
117         return inputlist;
118 }
119
120 SHUFFNODE *shuff_buildtree(SHUFFNODE *list, int listcount)
121 {
122         SHUFFNODE *lastsymbol = list+(listcount-1);
123         SHUFFNODE *node1,*node2;
124
125         while (lastsymbol > list) {             
126                 /* Ordeno la lista por frecuencia descendente */
127                 qsort(list,listcount,sizeof(SHUFFNODE),shuff_compnode);                         
128                 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
129                 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
130                 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
131                 shuff_cpynode(node1,lastsymbol-1);
132                 shuff_cpynode(node2,lastsymbol);                
133                 lastsymbol -= 1;
134                 /* Nodo ficticio con la suma de las probs y los ptros a childs */
135                 lastsymbol->symbol = 256;
136                 lastsymbol->freq = node1->freq + node2->freq;
137                 lastsymbol->lchild = node1;
138                 lastsymbol->rchild = node2;
139                 --listcount;
140         }
141                 
142         /* Devuelvo el puntero a la raiz del arbol de huffman */
143         return lastsymbol;
144 }
145
146 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
147 {
148         int i,j;
149         unsigned short int auxcode;
150         unsigned char bit;
151         
152         for (i = 0; i < 256; ++i) {
153                 if (codetable[i].codelength > 0) {
154                         auxcode = codetable[i].code;                    
155                         printf("Symbol:%i  Freq: %li  Code:",i,freqtable[i]);
156                         for (j = codetable[i].codelength-1; j >= 0; --j) {
157                                 auxcode = codetable[i].code;                    
158                                 auxcode = auxcode >> j;
159                                 bit = auxcode & 1;                              
160                                 printf("%i",bit);
161                         }
162                         printf("  Length:%i\n",codetable[i].codelength);
163                 }               
164         }
165 }
166
167 void shuff_zerocodes(SHUFFCODE *table)
168 {
169         int i;
170         
171         /* Inicializo los codigos prefijos */   
172         for (i = 0; i < 256; ++i) {
173                 table[i].code = 0;
174                 table[i].codelength = 0;
175         }
176 }
177
178 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
179 {
180         if (node->symbol < 256) {
181                 /* Guardo el codigo en la tabla */
182                 table[node->symbol].code = code;
183                 table[node->symbol].codelength = level;         
184         }
185         else {
186                 code = code << 1;
187                 shuff_buildcodes(table,node->lchild,level+1,code);
188                 code |= 1;
189                 shuff_buildcodes(table,node->rchild,level+1,code);
190         }
191 }
192
193 int shuff_encode_symbols(t_freq *ftable, SHUFFCODE *ctable, char* inputfile, char *outputfile, long volsize)
194 {
195         FILE *fpsource;
196         VFILE *fpdest;
197         int symbol,i;
198         unsigned long int sourcesize;
199         char bit;
200         SHUFFCODE symbolcode;
201                 
202         /* Abrimos el file */
203         if ((fpsource = fopen(inputfile,"r")) == NULL) return 0;
204         if ((fpdest = vfopen(outputfile,"w",volsize)) == NULL) return 0;
205                 
206         /* Guardamos el size el archivo original e inputlist como header */
207         fseek(fpsource,0,SEEK_END);
208         sourcesize = ftell(fpsource);
209         vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
210         vfwrite(ftable,sizeof(t_freq),256,fpdest);
211         
212         /* Encodeo */
213         fseek(fpsource,0,SEEK_SET);
214         while (!feof(fpsource)) {
215                 /* Levanto un symbolo (byte) */         
216                 symbol = fgetc(fpsource);
217                 if (symbol == EOF) continue;
218                 
219                 /* Cargamos el codigo y lo emitimos */
220                 symbolcode = ctable[symbol];
221                 for (i = symbolcode.codelength; i > 0; --i) {
222                         bit = (symbolcode.code >> (i-1)) & 1;
223                         putbit(bit,0,0,fpdest);
224                 }               
225         }
226         
227         /* Hacemos un flush de lo que haya quedado en el buffer de salida */
228         putbit(0,0,1,fpdest);
229         fclose(fpsource);
230         vfclose(fpdest);
231         return 1;       
232 }
233
234 int shuff_encode_file(char *inputfile, char *outputfile, long volsize)
235 {
236         /* Locals */
237         t_freq *freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
238         SHUFFNODE *inputlist;
239         SHUFFNODE *codetree;
240         SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
241         int freqcount = 0;
242         
243         /* Armamos la tabla de frecuencias */
244         if (!shuff_scanfreq(inputfile,freqtable)) return 0;
245         
246         /* Armo el input list y genero el arbol de huffman */
247         inputlist = shuff_buildlist(freqtable, &freqcount);
248         codetree = shuff_buildtree(inputlist,freqcount);
249
250         /* Armo la tabla de codigos prefijos para el encoder */
251         shuff_zerocodes(codetable);
252         shuff_buildcodes(codetable,codetree,0,0);
253         /*shuff_printcodes(codetable,freqtable);*/
254
255         /* Encodeo byte per byte */
256         shuff_encode_symbols(freqtable,codetable,inputfile,outputfile,volsize);
257         
258         /* Free up memory baby yeah */
259         free(freqtable);
260         free(inputlist);        
261         free(codetable);
262         
263         return 1;
264 }
265
266 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer, 
267                                                          int *bitsleft, unsigned short int *symbol)
268 {
269         char bit = 0;
270                 
271         /* Levanto el symbolo y si es uno valido, devuelvo */
272         *symbol = entrynode->symbol;
273         if (*symbol != 256) return entrynode;           
274         if (*bitsleft == 0) return entrynode;
275                 
276         /* Obtengo otro bit a procesar y me muevo en el arbol */
277         bit = (buffer >> ((*bitsleft)-1)) & 1;  
278         --(*bitsleft);
279         if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
280         else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
281 }
282
283 int shuff_decode_file(char *inputfile, char *outputfile)
284 {
285         SHUFFNODE *inputlist;
286         SHUFFNODE *codetree,*currnode;
287         t_freq *ftable = (t_freq*)malloc(sizeof(t_freq)*256);
288         unsigned long int bytesleft,codebuffer;
289         VFILE *fpsource;
290         FILE *fpdest;
291         unsigned short int decoded_symbol;
292         int bitsleft,freqcount = 0;     
293         
294         /* Levanto cuantos bytes decodeo y la freq table */
295         if ((fpsource = vfopen(inputfile,"r",0)) == NULL) return 0;
296         if ((fpdest = fopen(outputfile,"w")) == NULL) return 0;
297         vfread(&bytesleft,sizeof(unsigned long int),1,fpsource);
298         vfread(ftable,sizeof(unsigned long int),256,fpsource);  
299         inputlist = shuff_buildlist(ftable, &freqcount);
300         codetree = shuff_buildtree(inputlist,freqcount);
301         currnode = codetree;
302         
303         while (!vfeof(fpsource) && (bytesleft > 0)) {
304                 
305                 /* Leo un buffer de 32 bits */
306                 if (vfread(&codebuffer,sizeof(unsigned long int),1,fpsource) != 1) continue;
307                 bitsleft = sizeof(unsigned long int) * 8;
308                 
309                 /* Proceso el buffer sacando simbolos hasta que se me agote */
310                 while ((bitsleft > 0) && (bytesleft > 0)) {     
311                         currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
312                         /* Si obtuve un symbolo valido lo emito*/
313                         if (decoded_symbol != 256) {
314                                 fputc(decoded_symbol,fpdest);
315                                 currnode = codetree;
316                                 --bytesleft;                            
317                         }                                               
318                 }               
319         }
320                 
321         vfclose(fpsource);
322         fclose(fpdest);
323         
324         /* Free up memory baby yeah */
325         free(ftable);
326         free(inputlist);
327         
328         return 1;
329 }