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 a menos que se use un canonico */
74 if (!chunkshuff->canonic) {
75 for (i = 0; i < chunksize; ++i) {
77 chunkshuff->freqtable[symbol] += 1;
78 chunkshuff->sumfreq += 1;
80 /* Si llegue al tope de freq acumulada, halve em */
81 if (chunkshuff->sumfreq == 14930352)
82 chunkshuff->sumfreq = shuff_rescalefreq(chunkshuff->freqtable);
86 /* Dumpeamos el chunk en el temporal homero */
87 fwrite(chunk,chunksize,1,chunkshuff->coderfp);
92 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
99 /* Inicializamos la tabla de frecuencias */
100 for (i = 0; i < 256; ++i) freqtable[i] = 0;
102 /* Abrimos el file */
103 if ((fp = fopen(inputfile,"r")) == NULL) return 0;
105 /* Contamos las frecuencias */
107 if (symbol == EOF) continue;
112 /* Si llegue al tope de freq acumulada, halve em */
113 if (sumfreq == 14930352)
114 sumfreq = shuff_rescalefreq(freqtable);
121 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
123 int i,j = 0,nonzero = 0;
124 SHUFFNODE *inputlist;
126 /* Calculo cuantas frequencias > 0 hay y creo la tabla */
127 for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
128 inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
130 /* Cargo la inputlist del huffman solo con freqs > 0 */
131 for (i = 0; i < 256; ++i)
132 if (freqtable[i] > 0) {
133 inputlist[j].symbol = i;
134 inputlist[j].freq = freqtable[i];
135 inputlist[j].lchild = NULL;
136 inputlist[j].rchild = NULL;
140 *nonzerofreqs = nonzero;
144 SHUFFNODE *shuff_buildtree(t_freq *ftable)
146 SHUFFNODE *lastsymbol;
147 SHUFFNODE *node1,*node2,*root;
148 SHUFFNODE *inputlist;
151 /* Genero la input list en base a la cual genera el arbol */
152 inputlist = shuff_buildlist(ftable, &freqcount);
153 lastsymbol = inputlist+(freqcount-1);
155 while (lastsymbol > inputlist) {
156 /* Ordeno la lista por frecuencia descendente */
157 qsort(inputlist,freqcount,sizeof(SHUFFNODE),shuff_compnode);
158 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
159 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
160 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
161 shuff_cpynode(node1,lastsymbol-1);
162 shuff_cpynode(node2,lastsymbol);
164 /* Nodo ficticio con la suma de las probs y los ptros a childs */
165 lastsymbol->symbol = 256;
166 lastsymbol->freq = node1->freq + node2->freq;
167 lastsymbol->lchild = node1;
168 lastsymbol->rchild = node2;
172 /* Copio la raiz para poder liberar la lista sin perderla */
173 root = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
174 shuff_cpynode(root,lastsymbol);
179 /* Devuelvo el puntero a la raiz del arbol de huffman */
183 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
186 unsigned short int auxcode;
189 for (i = 0; i < 256; ++i) {
190 if (codetable[i].codelength > 0) {
191 auxcode = codetable[i].code;
192 printf("Symbol:%i Freq: %lu Code:",i,freqtable[i]);
193 for (j = codetable[i].codelength-1; j >= 0; --j) {
194 auxcode = codetable[i].code;
195 auxcode = auxcode >> j;
199 printf(" Length:%i\n",codetable[i].codelength);
204 void shuff_zerocodes(SHUFFCODE *table)
208 /* Inicializo los codigos prefijos */
209 for (i = 0; i < 256; ++i) {
211 table[i].codelength = 0;
215 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
217 if (node->symbol < 256) {
218 /* Guardo el codigo en la tabla */
219 table[node->symbol].code = code;
220 table[node->symbol].codelength = level;
224 shuff_buildcodes(table,node->lchild,level+1,code);
226 shuff_buildcodes(table,node->rchild,level+1,code);
230 int shuff_encode_symbols(HUFF_STATE *shuff, SHUFFCODE *ctable)
235 unsigned long int sourcesize;
237 SHUFFCODE symbolcode;
239 /* Abrimos el source y el destino */
240 if (shuff->coderfp != NULL) fclose(shuff->coderfp); /* close bychunk temp file */
241 if ((fpsource = fopen(shuff->sourcefile,"r")) == NULL) return 0;
242 if ((fpdest = vfopen(shuff->targetfile,"w",shuff->volsize)) == NULL) return 0;
244 /* Guardamos el size el archivo original e inputlist como header */
245 fseek(fpsource,0,SEEK_END);
246 sourcesize = ftell(fpsource);
247 vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
248 vfwrite(shuff->freqtable,sizeof(t_freq),256,fpdest);
251 fseek(fpsource,0,SEEK_SET);
252 while (!feof(fpsource)) {
253 /* Levanto un symbolo (byte) */
254 symbol = fgetc(fpsource);
255 if (symbol == EOF) continue;
257 /* Cargamos el codigo y lo emitimos */
258 symbolcode = ctable[symbol];
259 for (i = symbolcode.codelength; i > 0; --i) {
260 bit = (symbolcode.code >> (i-1)) & 1;
261 putbit(bit,0,0,fpdest);
265 /* Hacemos un flush de lo que haya quedado en el buffer de salida */
266 putbit(0,0,1,fpdest);
272 int shuff_encode_file(HUFF_STATE *shuff)
275 SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
277 /* Veo si debo armar una freqtable o si esta preloaded */
278 if ((!shuff->canonic) && (!shuff->bychunk))
279 if (!shuff_scanfreq(shuff->sourcefile,shuff->freqtable)) return 0;
281 /* Genero el arbol de huffman */
282 shuff->codetree = shuff_buildtree(shuff->freqtable);
284 /* Armo la tabla de codigos prefijos para el encoder */
285 shuff_zerocodes(codetable);
286 shuff_buildcodes(codetable,shuff->codetree,0,0);
287 /*shuff_printcodes(codetable,shuff->freqtable);*/
289 /* Encodeo byte per byte */
290 shuff_encode_symbols(shuff,codetable);
292 /* Free up memory baby yeah */
298 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer,
299 int *bitsleft, unsigned short int *symbol)
303 /* Levanto el symbolo y si es uno valido, devuelvo */
304 *symbol = entrynode->symbol;
305 if (*symbol != 256) return entrynode;
306 if (*bitsleft == 0) return entrynode;
308 /* Obtengo otro bit a procesar y me muevo en el arbol */
309 bit = (buffer >> ((*bitsleft)-1)) & 1;
311 if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
312 else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
315 int shuff_decode_chunk(HUFF_STATE *shuff, char *chunk, int chunksize, int *decodedbytes)
317 SHUFFNODE *currnode = shuff->codetree;
318 unsigned short int decoded_symbol;
321 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
323 /* Leo un buffer de 32 bits si es que quedo vacio el anterior */
324 if (shuff->bitsleft == 0) {
325 if (vfread(&(shuff->codebuffer),sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
326 shuff->bitsleft = sizeof(unsigned long int) * 8;
329 /* Proceso el buffer sacando simbolos till se me agote el buffer, file o chunk */
330 while ((shuff->bitsleft > 0) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
331 currnode = shuff_decode_symbols(currnode,shuff->codebuffer,&(shuff->bitsleft),&decoded_symbol);
332 /* Si obtuve un symbolo valido lo emito*/
333 if (decoded_symbol != 256) {
334 chunk[(*decodedbytes)++] = decoded_symbol;
335 currnode = shuff->codetree;
336 --(shuff->bytesleft);
341 if (shuff->bytesleft == 0) return 0;
345 int shuff_decode_file(HUFF_STATE *shuff)
348 unsigned long int codebuffer;
350 unsigned short int decoded_symbol;
353 /* Comienzo a decodificar, pues la tabla ya la levante en el decinit */
354 if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;
355 currnode = shuff->codetree;
357 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
359 /* Leo un buffer de 32 bits */
360 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
361 bitsleft = sizeof(unsigned long int) * 8;
363 /* Proceso el buffer sacando simbolos hasta que se me agote */
364 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {
365 currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
366 /* Si obtuve un symbolo valido lo emito*/
367 if (decoded_symbol != 256) {
368 fputc(decoded_symbol,fpdest);
369 currnode = shuff->codetree;
370 --(shuff->bytesleft);
375 /* Close destination */
381 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
384 HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
385 shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
388 shuff->codebuffer = 0;
390 shuff->coderfp = NULL;
391 shuff->targetfile = NULL;
392 shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
393 strcpy(shuff->sourcefile,inputfile);
394 if (outputfile != NULL) {
395 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
396 strcpy(shuff->targetfile,outputfile);
399 /* Levanto cuantos bytes debo decodificar y la freqtable */
400 if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return NULL;
401 vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
402 vfread(shuff->freqtable,sizeof(t_freq),256,shuff->decoderfp);
403 /* Armo el arbol de huffman que uso para decodificar */
404 shuff->codetree = shuff_buildtree(shuff->freqtable);
409 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
412 HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
415 /* Inicializo la estructura para trabajar con Huff Static by File */
416 fshuff->coderfp = NULL;
417 fshuff->decoderfp = NULL;
418 fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
419 fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
420 strcpy(fshuff->sourcefile,inputfile);
421 strcpy(fshuff->targetfile,outputfile);
422 fshuff->volsize = volsize;
425 fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
426 for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;
428 fshuff->codetree = NULL;
433 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
436 HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
439 /* Inicializo la estructura para trabajar con Huff Static by Chunks */
440 cshuff->decoderfp = NULL;
441 cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
442 cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
443 strcpy(cshuff->targetfile,outputfile);
444 strcpy(cshuff->sourcefile,outputfile);
445 strcat(cshuff->sourcefile,"~");
446 cshuff->volsize = volsize;
449 cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
450 for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;
452 cshuff->codetree = NULL;
454 /* Abrimos un archivo temporal para ir tirando los chunks */
455 if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;
460 int shuff_loadmodel(HUFF_STATE *shuff, char *modelfile) {
464 if ((shuff) && (shuff->freqtable) && (modelfile)) {
465 /* Cargo el modelo de disco */
466 if ((fp = fopen(modelfile,"r")) == NULL) return 0;
467 if (fread(shuff->freqtable,sizeof(t_freq),256,fp) != 256) return 0;
475 int shuff_savemodel(HUFF_STATE *shuff) {
481 if ((shuff) && (shuff->targetfile) && (shuff->freqtable)) {
482 /* Preparo el nombre del archivo con la tabla */
483 auxfilename = (char*)malloc(strlen(shuff->targetfile)+1);
484 stopchar = strrchr(shuff->targetfile,'.');
485 strncpy(auxfilename,shuff->targetfile,stopchar - shuff->targetfile);
486 auxfilename[stopchar - shuff->targetfile] = 0;
487 strcat(auxfilename,".ftb");
489 /* Lo creamos y dumpeamos la tabla de frecuencias (modelo) */
490 if ((fp = fopen(auxfilename,"w")) == NULL) return 0;
491 fwrite(shuff->freqtable,sizeof(t_freq),256,fp);
499 void shuff_deinit_encoder(HUFF_STATE *shuff)
501 /* Libero mallocs y cierro archivos */
502 if (shuff->freqtable) free(shuff->freqtable);
503 if (shuff->coderfp) fclose(shuff->coderfp);
504 if (shuff->bychunk) unlink(shuff->sourcefile);
505 if (shuff->sourcefile) free(shuff->sourcefile);
506 if (shuff->targetfile) free(shuff->targetfile);
508 /* Destruyo recursivamente el arbol de codigos */
511 void shuff_deinit_decoder(HUFF_STATE *shuff)
513 /* Libero mallocs y cierro archivos */
514 if (shuff->freqtable) free(shuff->freqtable);
515 if (shuff->sourcefile != NULL) free(shuff->sourcefile);
516 if (shuff->targetfile != NULL) free(shuff->targetfile);
517 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
519 /* Destruyo recursivamente el arbol de codigos */