2 #include "statichuff.h"
6 void putbit(char bit, char restart, char flush, VFILE *fp)
8 static unsigned long int bits_buffer = 0;
9 static unsigned char bits_used = 0;
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);
19 /* me indican que comienza un nuevo output */
24 /* inserto el bit en el buffer */
25 bits_buffer = bits_buffer << 1;
29 /* lleno el buffer, escribo */
30 if (bits_used == 32) {
31 vfwrite(&bits_buffer,sizeof(unsigned long int),1,fp);
38 void shuff_cpynode(SHUFFNODE *node1, SHUFFNODE *node2)
40 node1->symbol = node2->symbol;
41 node1->freq = node2->freq;
42 node1->lchild = node2->lchild;
43 node1->rchild = node2->rchild;
46 int shuff_compnode(const void *node1, const void *node2)
48 if (((SHUFFNODE*)node1)->freq < ((SHUFFNODE*)node2)->freq) return 1;
49 if (((SHUFFNODE*)node1)->freq > ((SHUFFNODE*)node2)->freq) return -1;
53 int shuff_rescalefreq(t_freq *freqtable)
58 /* Divido por la mitad las frecuencias, asegurando de no perder */
59 for (i = 0; i < 256; i++) {
60 freqtable[i] = (freqtable[i] >> 2) | 1;
61 totalfreq += freqtable[i];
67 int shuff_scanfreq_chunk(HUFF_STATE *chunkshuff, char* chunk, int chunksize)
71 unsigned char symbol = 0;
73 /* Contamos las frecuencias del chunk*/
74 for (i = 0; i < chunksize; ++i) {
76 chunkshuff->freqtable[symbol] += 1;
77 chunkshuff->sumfreq += 1;
79 /* Si llegue al tope de freq acumulada, halve em */
80 if (chunkshuff->sumfreq == 14930352)
81 chunkshuff->sumfreq = shuff_rescalefreq(chunkshuff->freqtable);
84 /* Dumpeamos el chunk en el temporal homero */
85 fwrite(chunk,chunksize,1,chunkshuff->coderfp);
90 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
97 /* Inicializamos la tabla de frecuencias */
98 for (i = 0; i < 256; ++i) freqtable[i] = 0;
100 /* Abrimos el file */
101 if ((fp = fopen(inputfile,"r")) == NULL) return 0;
103 /* Contamos las frecuencias */
105 if (symbol == EOF) continue;
110 /* Si llegue al tope de freq acumulada, halve em */
111 if (sumfreq == 14930352)
112 sumfreq = shuff_rescalefreq(freqtable);
119 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
121 int i,j = 0,nonzero = 0;
122 SHUFFNODE *inputlist;
124 /* Calculo cuantas frequencias > 0 hay y creo la tabla */
125 for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
126 inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
128 /* Cargo la inputlist del huffman solo con freqs > 0 */
129 for (i = 0; i < 256; ++i)
130 if (freqtable[i] > 0) {
131 inputlist[j].symbol = i;
132 inputlist[j].freq = freqtable[i];
133 inputlist[j].lchild = NULL;
134 inputlist[j].rchild = NULL;
138 *nonzerofreqs = nonzero;
142 SHUFFNODE *shuff_buildtree(t_freq *ftable)
144 SHUFFNODE *lastsymbol;
145 SHUFFNODE *node1,*node2,*root;
146 SHUFFNODE *inputlist;
149 /* Genero la input list en base a la cual genera el arbol */
150 inputlist = shuff_buildlist(ftable, &freqcount);
151 lastsymbol = inputlist+(freqcount-1);
153 while (lastsymbol > inputlist) {
154 /* Ordeno la lista por frecuencia descendente */
155 qsort(inputlist,freqcount,sizeof(SHUFFNODE),shuff_compnode);
156 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
157 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
158 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
159 shuff_cpynode(node1,lastsymbol-1);
160 shuff_cpynode(node2,lastsymbol);
162 /* Nodo ficticio con la suma de las probs y los ptros a childs */
163 lastsymbol->symbol = 256;
164 lastsymbol->freq = node1->freq + node2->freq;
165 lastsymbol->lchild = node1;
166 lastsymbol->rchild = node2;
170 /* Copio la raiz para poder liberar la lista sin perderla */
171 root = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
172 shuff_cpynode(root,lastsymbol);
177 /* Devuelvo el puntero a la raiz del arbol de huffman */
181 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
184 unsigned short int auxcode;
187 for (i = 0; i < 256; ++i) {
188 if (codetable[i].codelength > 0) {
189 auxcode = codetable[i].code;
190 printf("Symbol:%i Freq: %li Code:",i,freqtable[i]);
191 for (j = codetable[i].codelength-1; j >= 0; --j) {
192 auxcode = codetable[i].code;
193 auxcode = auxcode >> j;
197 printf(" Length:%i\n",codetable[i].codelength);
202 void shuff_zerocodes(SHUFFCODE *table)
206 /* Inicializo los codigos prefijos */
207 for (i = 0; i < 256; ++i) {
209 table[i].codelength = 0;
213 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
215 if (node->symbol < 256) {
216 /* Guardo el codigo en la tabla */
217 table[node->symbol].code = code;
218 table[node->symbol].codelength = level;
222 shuff_buildcodes(table,node->lchild,level+1,code);
224 shuff_buildcodes(table,node->rchild,level+1,code);
228 int shuff_encode_symbols(HUFF_STATE *shuff, SHUFFCODE *ctable)
233 unsigned long int sourcesize;
235 SHUFFCODE symbolcode;
237 /* Abrimos el source y el destino */
238 if (shuff->coderfp != NULL) fclose(shuff->coderfp); /* close bychunk temp file */
239 if ((fpsource = fopen(shuff->sourcefile,"r")) == NULL) return 0;
240 if ((fpdest = vfopen(shuff->targetfile,"w",shuff->volsize)) == NULL) return 0;
242 /* Guardamos el size el archivo original e inputlist como header */
243 fseek(fpsource,0,SEEK_END);
244 sourcesize = ftell(fpsource);
245 vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
246 vfwrite(shuff->freqtable,sizeof(t_freq),256,fpdest);
249 fseek(fpsource,0,SEEK_SET);
250 while (!feof(fpsource)) {
251 /* Levanto un symbolo (byte) */
252 symbol = fgetc(fpsource);
253 if (symbol == EOF) continue;
255 /* Cargamos el codigo y lo emitimos */
256 symbolcode = ctable[symbol];
257 for (i = symbolcode.codelength; i > 0; --i) {
258 bit = (symbolcode.code >> (i-1)) & 1;
259 putbit(bit,0,0,fpdest);
263 /* Hacemos un flush de lo que haya quedado en el buffer de salida */
264 putbit(0,0,1,fpdest);
270 int shuff_encode_file(HUFF_STATE *shuff)
273 SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
275 /* Veo si debo armar una freqtable o si esta preloaded */
276 if (!shuff->preloadfreq) if (!shuff_scanfreq(shuff->sourcefile,shuff->freqtable)) return 0;
278 /* Genero el arbol de huffman */
279 shuff->codetree = shuff_buildtree(shuff->freqtable);
281 /* Armo la tabla de codigos prefijos para el encoder */
282 shuff_zerocodes(codetable);
283 shuff_buildcodes(codetable,shuff->codetree,0,0);
284 /*shuff_printcodes(codetable,shuff->freqtable);*/
286 /* Encodeo byte per byte */
287 shuff_encode_symbols(shuff,codetable);
289 /* Free up memory baby yeah */
295 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer,
296 int *bitsleft, unsigned short int *symbol)
300 /* Levanto el symbolo y si es uno valido, devuelvo */
301 *symbol = entrynode->symbol;
302 if (*symbol != 256) return entrynode;
303 if (*bitsleft == 0) return entrynode;
305 /* Obtengo otro bit a procesar y me muevo en el arbol */
306 bit = (buffer >> ((*bitsleft)-1)) & 1;
308 if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
309 else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
312 int shuff_decode_chunk(HUFF_STATE *shuff, char *chunk, int chunksize, int *decodedbytes)
314 SHUFFNODE *currnode = shuff->codetree;
315 unsigned short int decoded_symbol;
318 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
320 /* Leo un buffer de 32 bits si es que quedo vacio el anterior */
321 if (shuff->bitsleft == 0) {
322 if (vfread(&(shuff->codebuffer),sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
323 shuff->bitsleft = sizeof(unsigned long int) * 8;
326 /* Proceso el buffer sacando simbolos till se me agote el buffer, file o chunk */
327 while ((shuff->bitsleft > 0) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
328 currnode = shuff_decode_symbols(currnode,shuff->codebuffer,&(shuff->bitsleft),&decoded_symbol);
329 /* Si obtuve un symbolo valido lo emito*/
330 if (decoded_symbol != 256) {
331 chunk[(*decodedbytes)++] = decoded_symbol;
332 currnode = shuff->codetree;
333 --(shuff->bytesleft);
338 if (shuff->bytesleft == 0) return 0;
342 int shuff_decode_file(HUFF_STATE *shuff)
345 unsigned long int codebuffer;
347 unsigned short int decoded_symbol;
350 /* Comienzo a decodificar, pues la tabla ya la levante en el decinit */
351 if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;
352 currnode = shuff->codetree;
354 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
356 /* Leo un buffer de 32 bits */
357 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
358 bitsleft = sizeof(unsigned long int) * 8;
360 /* Proceso el buffer sacando simbolos hasta que se me agote */
361 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {
362 currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
363 /* Si obtuve un symbolo valido lo emito*/
364 if (decoded_symbol != 256) {
365 fputc(decoded_symbol,fpdest);
366 currnode = shuff->codetree;
367 --(shuff->bytesleft);
372 /* Close destination */
378 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
381 HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
382 shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
385 shuff->codebuffer = 0;
387 shuff->coderfp = NULL;
388 shuff->targetfile = NULL;
389 shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
390 strcpy(shuff->sourcefile,inputfile);
391 if (outputfile != NULL) {
392 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
393 strcpy(shuff->targetfile,outputfile);
396 /* Levanto cuantos bytes decodeo y la freq table */
397 if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return NULL;
398 vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
399 vfread(shuff->freqtable,sizeof(unsigned long int),256,shuff->decoderfp);
400 shuff->codetree = shuff_buildtree(shuff->freqtable);
405 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
408 HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
411 /* Inicializo la estructura para trabajar con Huff Static by File */
412 fshuff->coderfp = NULL;
413 fshuff->decoderfp = NULL;
414 fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
415 fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
416 strcpy(fshuff->sourcefile,inputfile);
417 strcpy(fshuff->targetfile,outputfile);
418 fshuff->volsize = volsize;
419 fshuff->preloadfreq = 0;
420 fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
421 for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;
423 fshuff->bytesleft = 0;
424 fshuff->codetree = NULL;
429 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
432 HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
435 /* Inicializo la estructura para trabajar con Huff Static by Chunks */
436 cshuff->decoderfp = NULL;
437 cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
438 cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
439 strcpy(cshuff->targetfile,outputfile);
440 strcpy(cshuff->sourcefile,outputfile);
441 strcat(cshuff->sourcefile,"~");
442 cshuff->volsize = volsize;
443 cshuff->preloadfreq = 1;
444 cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
445 for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;
447 cshuff->bytesleft = 0;
448 cshuff->codetree = NULL;
450 /* Abrimos un archivo temporal para ir tirando los chunks */
451 if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;
456 void shuff_deinit_encoder(HUFF_STATE *shuff)
458 /* Libero mallocs y cierro archivos */
459 free(shuff->freqtable);
460 if (shuff->coderfp != NULL) fclose(shuff->coderfp);
461 if (shuff->preloadfreq == 1) unlink(shuff->sourcefile);
462 if (shuff->targetfile != NULL) free(shuff->targetfile);
463 free(shuff->sourcefile);
465 /* Destruyo recursivamente el arbol de codigos */
468 void shuff_deinit_decoder(HUFF_STATE *shuff)
470 /* Libero mallocs y cierro archivos */
471 free(shuff->freqtable);
472 free(shuff->sourcefile);
473 if (shuff->targetfile != NULL) free(shuff->targetfile);
474 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
476 /* Destruyo recursivamente el arbol de codigos */