]> git.llucax.com Git - z.facultad/75.06/jacu.git/blob - src/statichuff/statichuff.c
Minor fix en la declaracion de la funcion de comparacion para que no se queje el...
[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, FILE *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                 fwrite(&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                 fwrite(&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         /* frequencias en 1, por ello le sumo 1 antes de partir */
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(char *inputfile, t_freq *freqtable)
68 {
69         /* Locals */    
70         FILE *fp;
71         t_freq sumfreq = 0;
72         int i,symbol;
73         
74         /* Inicializamos la tabla de frecuencias */     
75         for (i = 0; i < 256; ++i) freqtable[i] = 0;
76                 
77         /* Abrimos el file */
78         if ((fp = fopen(inputfile,"rb")) == NULL) return 0;
79         while (!feof(fp)) {             
80                 /* Contamos las frecuencias */          
81                 symbol = fgetc(fp);
82                 if (symbol == EOF) continue;
83                 
84                 freqtable[symbol]++;            
85                 ++sumfreq;
86                                 
87                 /* Si llegue al tope de freq acumulada, halve em */
88                 if (sumfreq == 14930352) 
89                         sumfreq = shuff_rescalefreq(freqtable);
90         }
91         
92         fclose(fp);
93         return 1;       
94 }
95
96 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
97 {
98         int i,j = 0,nonzero = 0;        
99         SHUFFNODE *inputlist;
100         
101         /* Calculo cuantas frequencias > 0 hay y creo la tabla */
102         for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
103         inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
104                 
105         /* Cargo la inputlist del huffman solo con freqs > 0 */
106         for (i = 0; i < 256; ++i)
107                 if (freqtable[i] > 0) {                 
108                         inputlist[j].symbol = i;
109                         inputlist[j].freq = freqtable[i];
110                         inputlist[j].lchild = NULL;
111                         inputlist[j].rchild = NULL;                     
112                         j++;
113                 }
114                 
115         *nonzerofreqs = nonzero;
116         return inputlist;
117 }
118
119 SHUFFNODE *shuff_buildtree(SHUFFNODE *list, int listcount)
120 {
121         SHUFFNODE *lastsymbol = list+(listcount-1);
122         SHUFFNODE *node1,*node2;
123         int i;
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
194
195 int shuff_encode_symbols(t_freq *ftable, SHUFFCODE *ctable, char* inputfile, char *outputfile) {
196
197         FILE *fpsource,*fpdest;
198         int symbol,i;
199         unsigned long int sourcesize;
200         char bit;
201         SHUFFCODE symbolcode;
202                 
203         /* Abrimos el file */
204         if ((fpsource = fopen(inputfile,"rb")) == NULL) return 0;
205         if ((fpdest = fopen(outputfile,"wb")) == NULL) return 0;
206                 
207         /* Guardamos el size el archivo original e inputlist como header */
208         fseek(fpsource,0,SEEK_END);
209         sourcesize = ftell(fpsource);
210         fwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
211         fwrite(ftable,sizeof(t_freq),256,fpdest);
212         
213         /* Encodeo */
214         fseek(fpsource,0,SEEK_SET);
215         while (!feof(fpsource)) {
216                 /* Levanto un symbolo (byte) */         
217                 symbol = fgetc(fpsource);
218                 if (symbol == EOF) continue;
219                 
220                 /* Cargamos el codigo y lo emitimos */
221                 symbolcode = ctable[symbol];
222                 for (i = symbolcode.codelength; i > 0; --i) {
223                         bit = (symbolcode.code >> (i-1)) & 1;
224                         putbit(bit,0,0,fpdest);
225                 }               
226         }
227         
228         /* Hacemos un flush de lo que haya quedado en el buffer de salida */
229         putbit(0,0,1,fpdest);
230         fclose(fpsource);
231         fclose(fpdest);
232         return 1;       
233 }
234
235 int shuff_encode_file(char *inputfile, char *outputfile)
236 {
237         /* Locals */
238         t_freq *freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
239         SHUFFNODE *inputlist;
240         SHUFFNODE *codetree;
241         SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
242         int freqcount = 0;
243         
244         /* Armamos la tabla de frecuencias */
245         if (!shuff_scanfreq(inputfile,freqtable)) return 0;
246         
247         /* Armo el input list y genero el arbol de huffman */
248         inputlist = shuff_buildlist(freqtable, &freqcount);
249         codetree = shuff_buildtree(inputlist,freqcount);
250
251         /* Armo la tabla de codigos prefijos para el encoder */
252         shuff_zerocodes(codetable);
253         shuff_buildcodes(codetable,codetree,0,0);
254         /*shuff_printcodes(codetable,freqtable);*/
255
256         /* Encodeo byte per byte */
257         shuff_encode_symbols(freqtable,codetable,inputfile,outputfile);
258         
259         return 1;
260 }
261
262 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer, 
263                                                          int *bitsleft, unsigned short int *symbol)
264 {
265         char bit = 0;
266                 
267         /* Levanto el symbolo y si es uno valido, devuelvo */
268         *symbol = entrynode->symbol;
269         if (*symbol != 256) return entrynode;           
270         if (*bitsleft == 0) return entrynode;
271                 
272         /* Obtengo otro bit a procesar y me muevo en el arbol */
273         bit = (buffer >> ((*bitsleft)-1)) & 1;  
274         --(*bitsleft);
275         if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
276         else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
277 }
278
279 int shuff_decode_file(char *inputfile, char *outputfile)
280 {
281         SHUFFNODE *inputlist;
282         SHUFFNODE *codetree,*currnode;
283         t_freq *ftable = (t_freq*)malloc(sizeof(t_freq)*256);
284         unsigned long int bytesleft,codebuffer;
285         FILE *fpsource;
286         FILE *fpdest;
287         unsigned short int decoded_symbol;
288         int bitsleft,freqcount = 0;     
289         
290         /* Levanto cuantos bytes decodeo y la freq table */
291         if ((fpsource = fopen(inputfile,"rb")) == NULL) return 0;
292         if ((fpdest = fopen(outputfile,"wb")) == NULL) return 0;
293         fread(&bytesleft,sizeof(unsigned long int),1,fpsource);
294         fread(ftable,sizeof(unsigned long int),256,fpsource);   
295         inputlist = shuff_buildlist(ftable, &freqcount);
296         codetree = shuff_buildtree(inputlist,freqcount);
297         currnode = codetree;
298         
299         while (!feof(fpsource) && (bytesleft > 0)) {
300                 
301                 /* Leo un buffer de 32 bits */
302                 if (fread(&codebuffer,sizeof(unsigned long int),1,fpsource) != 1) continue;
303                 bitsleft = sizeof(unsigned long int) * 8;
304                 
305                 /* Proceso el buffer sacando simbolos hasta que se me agote */
306                 while ((bitsleft > 0) && (bytesleft > 0)) {     
307                         currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
308                         /* Si obtuve un symbolo valido lo emito*/
309                         if (decoded_symbol != 256) {
310                                 fputc(decoded_symbol,fpdest);
311                                 currnode = codetree;
312                                 --bytesleft;                            
313                         }                                               
314                 }               
315         }
316                 
317         fclose(fpsource);
318         fclose(fpdest);
319         
320         return 1;
321 }
322
323 int main(int argc, char* argv[])
324 {       
325         int cflag = 0;
326         int dflag = 0;
327         int tflag = 0;
328         long int volumesize = 0;
329         int ch;
330                         
331         while ((ch = getopt(argc, argv, "cdt:")) != -1) { 
332                  
333                 switch (ch) { 
334                         case 'c': cflag = 1; 
335                                           break;
336                         
337                         case 'd': dflag = 1; 
338                                           break; 
339                         
340                         case 't': tflag = 1; 
341                                           volumesize = atoi(optarg);                                      
342                                           break; 
343                         
344                         default: fprintf(stderr, "Usage: %s [-cdt] sourcefile targetfile\n", argv[0]); 
345                                          return(2);
346                 }
347         }
348                 
349         if ( (argc == 1) || (cflag & dflag) || !(cflag | dflag) || ((argc - optind) < 2) ) {
350                 fprintf(stderr, "Usage: %s [-cdt] sourcefile targetfile\n", argv[0]); 
351                 if ((tflag == 1) && (volumesize <= 0)) fprintf(stderr,"Error: The volume size must be a non-zero value\n");
352                 return (2);             
353         }
354                 
355         if (cflag == 1) {
356                 /* Comprimo */
357             return shuff_encode_file(argv[optind],argv[optind+1]);
358         }
359         
360         if (dflag == 1) { 
361                 /* Descomprimo */
362                 return shuff_decode_file(argv[optind],argv[optind+1]);
363         }
364                 
365         return 0;
366 }