2 #include "statichuff.h"
5 void putbit(char bit, char restart, char flush, VFILE *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 vfwrite(&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 vfwrite(&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 for (i = 0; i < 256; i++) {
59 freqtable[i] = (freqtable[i] >> 2) | 1;
60 totalfreq += freqtable[i];
66 int shuff_scanfreq_chunk(HUFF_STATE *chunkshuff, char* chunk, int chunksize)
70 unsigned char symbol = 0;
72 /* Contamos las frecuencias del chunk*/
73 for (i = 0; i < chunksize; ++i) {
75 chunkshuff->freqtable[symbol] += 1;
76 chunkshuff->sumfreq += 1;
78 /* Si llegue al tope de freq acumulada, halve em */
79 if (chunkshuff->sumfreq == 14930352)
80 chunkshuff->sumfreq = shuff_rescalefreq(chunkshuff->freqtable);
83 /* Dumpeamos el chunk en el temporal homero */
84 fwrite(chunk,chunksize,1,chunkshuff->coderfp);
89 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
96 /* Inicializamos la tabla de frecuencias */
97 for (i = 0; i < 256; ++i) freqtable[i] = 0;
100 if ((fp = fopen(inputfile,"r")) == NULL) return 0;
102 /* Contamos las frecuencias */
104 if (symbol == EOF) continue;
109 /* Si llegue al tope de freq acumulada, halve em */
110 if (sumfreq == 14930352)
111 sumfreq = shuff_rescalefreq(freqtable);
118 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
120 int i,j = 0,nonzero = 0;
121 SHUFFNODE *inputlist;
123 /* Calculo cuantas frequencias > 0 hay y creo la tabla */
124 for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
125 inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
127 /* Cargo la inputlist del huffman solo con freqs > 0 */
128 for (i = 0; i < 256; ++i)
129 if (freqtable[i] > 0) {
130 inputlist[j].symbol = i;
131 inputlist[j].freq = freqtable[i];
132 inputlist[j].lchild = NULL;
133 inputlist[j].rchild = NULL;
137 *nonzerofreqs = nonzero;
141 SHUFFNODE *shuff_buildtree(t_freq *ftable)
143 SHUFFNODE *lastsymbol;
144 SHUFFNODE *node1,*node2,*root;
145 SHUFFNODE *inputlist;
148 /* Genero la input list en base a la cual genera el arbol */
149 inputlist = shuff_buildlist(ftable, &freqcount);
150 lastsymbol = inputlist+(freqcount-1);
152 while (lastsymbol > inputlist) {
153 /* Ordeno la lista por frecuencia descendente */
154 qsort(inputlist,freqcount,sizeof(SHUFFNODE),shuff_compnode);
155 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
156 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
157 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
158 shuff_cpynode(node1,lastsymbol-1);
159 shuff_cpynode(node2,lastsymbol);
161 /* Nodo ficticio con la suma de las probs y los ptros a childs */
162 lastsymbol->symbol = 256;
163 lastsymbol->freq = node1->freq + node2->freq;
164 lastsymbol->lchild = node1;
165 lastsymbol->rchild = node2;
169 /* Copio la raiz para poder liberar la lista sin perderla */
170 root = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
171 shuff_cpynode(root,lastsymbol);
176 /* Devuelvo el puntero a la raiz del arbol de huffman */
180 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
183 unsigned short int auxcode;
186 for (i = 0; i < 256; ++i) {
187 if (codetable[i].codelength > 0) {
188 auxcode = codetable[i].code;
189 printf("Symbol:%i Freq: %li Code:",i,freqtable[i]);
190 for (j = codetable[i].codelength-1; j >= 0; --j) {
191 auxcode = codetable[i].code;
192 auxcode = auxcode >> j;
196 printf(" Length:%i\n",codetable[i].codelength);
201 void shuff_zerocodes(SHUFFCODE *table)
205 /* Inicializo los codigos prefijos */
206 for (i = 0; i < 256; ++i) {
208 table[i].codelength = 0;
212 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
214 if (node->symbol < 256) {
215 /* Guardo el codigo en la tabla */
216 table[node->symbol].code = code;
217 table[node->symbol].codelength = level;
221 shuff_buildcodes(table,node->lchild,level+1,code);
223 shuff_buildcodes(table,node->rchild,level+1,code);
227 int shuff_encode_symbols(HUFF_STATE *shuff, SHUFFCODE *ctable)
232 unsigned long int sourcesize;
234 SHUFFCODE symbolcode;
236 /* Abrimos el source y el destino */
237 if (shuff->coderfp != NULL) fclose(shuff->coderfp); /* close bychunk temp file */
238 if ((fpsource = fopen(shuff->sourcefile,"r")) == NULL) return 0;
239 if ((fpdest = vfopen(shuff->targetfile,"w",shuff->volsize)) == NULL) return 0;
241 /* Guardamos el size el archivo original e inputlist como header */
242 fseek(fpsource,0,SEEK_END);
243 sourcesize = ftell(fpsource);
244 vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
245 vfwrite(shuff->freqtable,sizeof(t_freq),256,fpdest);
248 fseek(fpsource,0,SEEK_SET);
249 while (!feof(fpsource)) {
250 /* Levanto un symbolo (byte) */
251 symbol = fgetc(fpsource);
252 if (symbol == EOF) continue;
254 /* Cargamos el codigo y lo emitimos */
255 symbolcode = ctable[symbol];
256 for (i = symbolcode.codelength; i > 0; --i) {
257 bit = (symbolcode.code >> (i-1)) & 1;
258 putbit(bit,0,0,fpdest);
262 /* Hacemos un flush de lo que haya quedado en el buffer de salida */
263 putbit(0,0,1,fpdest);
269 int shuff_encode_file(HUFF_STATE *shuff)
272 SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
274 /* Veo si debo armar una freqtable o si esta preloaded */
275 if (!shuff->preloadfreq) if (!shuff_scanfreq(shuff->sourcefile,shuff->freqtable)) return 0;
277 /* Genero el arbol de huffman */
278 shuff->codetree = shuff_buildtree(shuff->freqtable);
280 /* Armo la tabla de codigos prefijos para el encoder */
281 shuff_zerocodes(codetable);
282 shuff_buildcodes(codetable,shuff->codetree,0,0);
283 /*shuff_printcodes(codetable,shuff->freqtable);*/
285 /* Encodeo byte per byte */
286 shuff_encode_symbols(shuff,codetable);
288 /* Free up memory baby yeah */
294 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer,
295 int *bitsleft, unsigned short int *symbol)
299 /* Levanto el symbolo y si es uno valido, devuelvo */
300 *symbol = entrynode->symbol;
301 if (*symbol != 256) return entrynode;
302 if (*bitsleft == 0) return entrynode;
304 /* Obtengo otro bit a procesar y me muevo en el arbol */
305 bit = (buffer >> ((*bitsleft)-1)) & 1;
307 if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
308 else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
311 int shuff_decode_chunk(HUFF_STATE *shuff, char *chunk, int chunksize, int *decodedbytes)
313 SHUFFNODE *currnode = shuff->codetree;
314 unsigned short int decoded_symbol;
317 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
319 /* Leo un buffer de 32 bits si es que quedo vacio el anterior */
320 if (shuff->bitsleft == 0) {
321 if (vfread(&(shuff->codebuffer),sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
322 shuff->bitsleft = sizeof(unsigned long int) * 8;
325 /* Proceso el buffer sacando simbolos till se me agote el buffer, file o chunk */
326 while ((shuff->bitsleft > 0) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
327 currnode = shuff_decode_symbols(currnode,shuff->codebuffer,&(shuff->bitsleft),&decoded_symbol);
328 /* Si obtuve un symbolo valido lo emito*/
329 if (decoded_symbol != 256) {
330 chunk[(*decodedbytes)++] = decoded_symbol;
331 currnode = shuff->codetree;
332 --(shuff->bytesleft);
337 if (shuff->bytesleft == 0) return 0;
341 int shuff_decode_file(HUFF_STATE *shuff)
344 unsigned long int codebuffer;
346 unsigned short int decoded_symbol;
349 /* Comienzo a decodificar, pues la tabla ya la levante en el decinit */
350 if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;
351 currnode = shuff->codetree;
353 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
355 /* Leo un buffer de 32 bits */
356 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
357 bitsleft = sizeof(unsigned long int) * 8;
359 /* Proceso el buffer sacando simbolos hasta que se me agote */
360 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {
361 currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
362 /* Si obtuve un symbolo valido lo emito*/
363 if (decoded_symbol != 256) {
364 fputc(decoded_symbol,fpdest);
365 currnode = shuff->codetree;
366 --(shuff->bytesleft);
371 /* Close destination */
377 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
380 HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
381 shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
384 shuff->codebuffer = 0;
386 shuff->coderfp = NULL;
387 shuff->targetfile = NULL;
388 shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
389 strcpy(shuff->sourcefile,inputfile);
390 if (outputfile != NULL) {
391 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
392 strcpy(shuff->targetfile,outputfile);
395 /* Levanto cuantos bytes decodeo y la freq table */
396 if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return 0;
397 vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
398 vfread(shuff->freqtable,sizeof(unsigned long int),256,shuff->decoderfp);
399 shuff->codetree = shuff_buildtree(shuff->freqtable);
404 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
407 HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
410 /* Inicializo la estructura para trabajar con Huff Static by File */
411 fshuff->coderfp = NULL;
412 fshuff->decoderfp = NULL;
413 fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
414 fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
415 strcpy(fshuff->sourcefile,inputfile);
416 strcpy(fshuff->targetfile,outputfile);
417 fshuff->volsize = volsize;
418 fshuff->preloadfreq = 0;
419 fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
420 for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;
422 fshuff->bytesleft = 0;
423 fshuff->codetree = NULL;
428 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
431 HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
434 /* Inicializo la estructura para trabajar con Huff Static by Chunks */
435 cshuff->decoderfp = NULL;
436 cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
437 cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
438 strcpy(cshuff->targetfile,outputfile);
439 strcpy(cshuff->sourcefile,outputfile);
440 strcat(cshuff->sourcefile,"~");
441 cshuff->volsize = volsize;
442 cshuff->preloadfreq = 1;
443 cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
444 for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;
446 cshuff->bytesleft = 0;
447 cshuff->codetree = NULL;
449 /* Abrimos un archivo temporal para ir tirando los chunks */
450 if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;
455 void shuff_deinit_encoder(HUFF_STATE *shuff)
457 /* Libero mallocs y cierro archivos */
458 free(shuff->freqtable);
459 if (shuff->coderfp != NULL) fclose(shuff->coderfp);
460 if (shuff->preloadfreq == 1) unlink(shuff->sourcefile);
461 if (shuff->targetfile != NULL) free(shuff->targetfile);
462 free(shuff->sourcefile);
464 /* Destruyo recursivamente el arbol de codigos */
467 void shuff_deinit_decoder(HUFF_STATE *shuff)
469 /* Libero mallocs y cierro archivos */
470 free(shuff->freqtable);
471 free(shuff->sourcefile);
472 if (shuff->targetfile != NULL) free(shuff->targetfile);
473 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
475 /* Destruyo recursivamente el arbol de codigos */