2 #include "statichuff.h"
5 void putbit(char bit, char restart, char flush, FILE *fp)
7 static unsigned long int bits_buffer = 0;
8 static unsigned char bits_used = 0;
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);
18 /* me indican que comienza un nuevo output */
23 /* inserto el bit en el buffer */
24 bits_buffer = bits_buffer << 1;
28 /* lleno el buffer, escribo */
29 if (bits_used == 32) {
30 fwrite(&bits_buffer,sizeof(unsigned long int),1,fp);
37 void shuff_cpynode(SHUFFNODE *node1, SHUFFNODE *node2)
39 node1->symbol = node2->symbol;
40 node1->freq = node2->freq;
41 node1->lchild = node2->lchild;
42 node1->rchild = node2->rchild;
45 int shuff_compnode(const void *node1, const void *node2)
47 if (((SHUFFNODE*)node1)->freq < ((SHUFFNODE*)node2)->freq) return 1;
48 if (((SHUFFNODE*)node1)->freq > ((SHUFFNODE*)node2)->freq) return -1;
52 int shuff_rescalefreq(t_freq *freqtable)
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];
67 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
74 /* Inicializamos la tabla de frecuencias */
75 for (i = 0; i < 256; ++i) freqtable[i] = 0;
78 if ((fp = fopen(inputfile,"rb")) == NULL) return 0;
80 /* Contamos las frecuencias */
82 if (symbol == EOF) continue;
87 /* Si llegue al tope de freq acumulada, halve em */
88 if (sumfreq == 14930352)
89 sumfreq = shuff_rescalefreq(freqtable);
96 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
98 int i,j = 0,nonzero = 0;
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);
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;
115 *nonzerofreqs = nonzero;
119 SHUFFNODE *shuff_buildtree(SHUFFNODE *list, int listcount)
121 SHUFFNODE *lastsymbol = list+(listcount-1);
122 SHUFFNODE *node1,*node2;
124 while (lastsymbol > list) {
125 /* Ordeno la lista por frecuencia descendente */
126 qsort(list,listcount,sizeof(SHUFFNODE),shuff_compnode);
127 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
128 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
129 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
130 shuff_cpynode(node1,lastsymbol-1);
131 shuff_cpynode(node2,lastsymbol);
133 /* Nodo ficticio con la suma de las probs y los ptros a childs */
134 lastsymbol->symbol = 256;
135 lastsymbol->freq = node1->freq + node2->freq;
136 lastsymbol->lchild = node1;
137 lastsymbol->rchild = node2;
141 /* Devuelvo el puntero a la raiz del arbol de huffman */
145 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
148 unsigned short int auxcode;
151 for (i = 0; i < 256; ++i) {
152 if (codetable[i].codelength > 0) {
153 auxcode = codetable[i].code;
154 printf("Symbol:%i Freq: %li Code:",i,freqtable[i]);
155 for (j = codetable[i].codelength-1; j >= 0; --j) {
156 auxcode = codetable[i].code;
157 auxcode = auxcode >> j;
161 printf(" Length:%i\n",codetable[i].codelength);
166 void shuff_zerocodes(SHUFFCODE *table)
170 /* Inicializo los codigos prefijos */
171 for (i = 0; i < 256; ++i) {
173 table[i].codelength = 0;
177 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
179 if (node->symbol < 256) {
180 /* Guardo el codigo en la tabla */
181 table[node->symbol].code = code;
182 table[node->symbol].codelength = level;
186 shuff_buildcodes(table,node->lchild,level+1,code);
188 shuff_buildcodes(table,node->rchild,level+1,code);
194 int shuff_encode_symbols(t_freq *ftable, SHUFFCODE *ctable, char* inputfile, char *outputfile) {
196 FILE *fpsource,*fpdest;
198 unsigned long int sourcesize;
200 SHUFFCODE symbolcode;
202 /* Abrimos el file */
203 if ((fpsource = fopen(inputfile,"rb")) == NULL) return 0;
204 if ((fpdest = fopen(outputfile,"wb")) == NULL) return 0;
206 /* Guardamos el size el archivo original e inputlist como header */
207 fseek(fpsource,0,SEEK_END);
208 sourcesize = ftell(fpsource);
209 fwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
210 fwrite(ftable,sizeof(t_freq),256,fpdest);
213 fseek(fpsource,0,SEEK_SET);
214 while (!feof(fpsource)) {
215 /* Levanto un symbolo (byte) */
216 symbol = fgetc(fpsource);
217 if (symbol == EOF) continue;
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);
227 /* Hacemos un flush de lo que haya quedado en el buffer de salida */
228 putbit(0,0,1,fpdest);
234 int shuff_encode_file(char *inputfile, char *outputfile)
237 t_freq *freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
238 SHUFFNODE *inputlist;
240 SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
243 /* Armamos la tabla de frecuencias */
244 if (!shuff_scanfreq(inputfile,freqtable)) return 0;
246 /* Armo el input list y genero el arbol de huffman */
247 inputlist = shuff_buildlist(freqtable, &freqcount);
248 codetree = shuff_buildtree(inputlist,freqcount);
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);*/
255 /* Encodeo byte per byte */
256 shuff_encode_symbols(freqtable,codetable,inputfile,outputfile);
258 /* Free up memory baby yeah */
266 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer,
267 int *bitsleft, unsigned short int *symbol)
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;
276 /* Obtengo otro bit a procesar y me muevo en el arbol */
277 bit = (buffer >> ((*bitsleft)-1)) & 1;
279 if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
280 else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
283 int shuff_decode_file(char *inputfile, char *outputfile)
285 SHUFFNODE *inputlist;
286 SHUFFNODE *codetree,*currnode;
287 t_freq *ftable = (t_freq*)malloc(sizeof(t_freq)*256);
288 unsigned long int bytesleft,codebuffer;
291 unsigned short int decoded_symbol;
292 int bitsleft,freqcount = 0;
294 /* Levanto cuantos bytes decodeo y la freq table */
295 if ((fpsource = fopen(inputfile,"rb")) == NULL) return 0;
296 if ((fpdest = fopen(outputfile,"wb")) == NULL) return 0;
297 fread(&bytesleft,sizeof(unsigned long int),1,fpsource);
298 fread(ftable,sizeof(unsigned long int),256,fpsource);
299 inputlist = shuff_buildlist(ftable, &freqcount);
300 codetree = shuff_buildtree(inputlist,freqcount);
303 while (!feof(fpsource) && (bytesleft > 0)) {
305 /* Leo un buffer de 32 bits */
306 if (fread(&codebuffer,sizeof(unsigned long int),1,fpsource) != 1) continue;
307 bitsleft = sizeof(unsigned long int) * 8;
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);
324 /* Free up memory baby yeah */
331 int main(int argc, char* argv[])
336 long int volumesize = 0;
339 while ((ch = getopt(argc, argv, "cdt:")) != -1) {
349 volumesize = atoi(optarg);
352 default: fprintf(stderr, "Usage: %s [-cdt] sourcefile targetfile\n", argv[0]);
357 if ( (argc == 1) || (cflag & dflag) || !(cflag | dflag) || ((argc - optind) < 2) ) {
358 fprintf(stderr, "Usage: %s [-cdt] sourcefile targetfile\n", argv[0]);
359 if ((tflag == 1) && (volumesize <= 0)) fprintf(stderr,"Error: The volume size must be a non-zero value\n");
365 return shuff_encode_file(argv[optind],argv[optind+1]);
370 return shuff_decode_file(argv[optind],argv[optind+1]);