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) {
241 fclose(shuff->coderfp); /* close bychunk temp file */
242 shuff->coderfp = NULL;
244 if ((fpsource = fopen(shuff->sourcefile,"r")) == NULL) return 0;
245 if ((fpdest = vfopen(shuff->targetfile,"w",shuff->volsize)) == NULL) return 0;
247 /* Guardamos el size el archivo original e inputlist como header */
248 fseek(fpsource,0,SEEK_END);
249 sourcesize = ftell(fpsource);
250 vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
251 vfwrite(shuff->freqtable,sizeof(t_freq),256,fpdest);
254 fseek(fpsource,0,SEEK_SET);
255 while (!feof(fpsource)) {
256 /* Levanto un symbolo (byte) */
257 symbol = fgetc(fpsource);
258 if (symbol == EOF) continue;
260 /* Cargamos el codigo y lo emitimos */
261 symbolcode = ctable[symbol];
262 for (i = symbolcode.codelength; i > 0; --i) {
263 bit = (symbolcode.code >> (i-1)) & 1;
264 putbit(bit,0,0,fpdest);
268 /* Hacemos un flush de lo que haya quedado en el buffer de salida */
269 putbit(0,0,1,fpdest);
275 int shuff_encode_file(HUFF_STATE *shuff)
278 SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
280 /* Veo si debo armar una freqtable o si esta preloaded */
281 if ((!shuff->canonic) && (!shuff->bychunk))
282 if (!shuff_scanfreq(shuff->sourcefile,shuff->freqtable)) return 0;
284 /* Genero el arbol de huffman */
285 shuff->codetree = shuff_buildtree(shuff->freqtable);
287 /* Armo la tabla de codigos prefijos para el encoder */
288 shuff_zerocodes(codetable);
289 shuff_buildcodes(codetable,shuff->codetree,0,0);
290 /*shuff_printcodes(codetable,shuff->freqtable);*/
292 /* Encodeo byte per byte */
293 shuff_encode_symbols(shuff,codetable);
295 /* Free up memory baby yeah */
301 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer,
302 int *bitsleft, unsigned short int *symbol)
306 /* Levanto el symbolo y si es uno valido, devuelvo */
307 *symbol = entrynode->symbol;
308 if (*symbol != 256) return entrynode;
309 if (*bitsleft == 0) return entrynode;
311 /* Obtengo otro bit a procesar y me muevo en el arbol */
312 bit = (buffer >> ((*bitsleft)-1)) & 1;
314 if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
315 else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
318 int shuff_decode_chunk(HUFF_STATE *shuff, char *chunk, int chunksize, int *decodedbytes)
320 SHUFFNODE *currnode = shuff->codetree;
321 unsigned short int decoded_symbol;
324 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
326 /* Leo un buffer de 32 bits si es que quedo vacio el anterior */
327 if (shuff->bitsleft == 0) {
328 if (vfread(&(shuff->codebuffer),sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
329 shuff->bitsleft = sizeof(unsigned long int) * 8;
332 /* Proceso el buffer sacando simbolos till se me agote el buffer, file o chunk */
333 while ((shuff->bitsleft > 0) && (shuff->bytesleft > 0) && (*decodedbytes < chunksize)) {
334 currnode = shuff_decode_symbols(currnode,shuff->codebuffer,&(shuff->bitsleft),&decoded_symbol);
335 /* Si obtuve un symbolo valido lo emito*/
336 if (decoded_symbol != 256) {
337 chunk[(*decodedbytes)++] = decoded_symbol;
338 currnode = shuff->codetree;
339 --(shuff->bytesleft);
344 if (shuff->bytesleft == 0) return 0;
348 int shuff_decode_file(HUFF_STATE *shuff)
351 unsigned long int codebuffer;
353 unsigned short int decoded_symbol;
356 /* Comienzo a decodificar, pues la tabla ya la levante en el decinit */
357 if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;
358 currnode = shuff->codetree;
360 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
362 /* Leo un buffer de 32 bits */
363 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
364 bitsleft = sizeof(unsigned long int) * 8;
366 /* Proceso el buffer sacando simbolos hasta que se me agote */
367 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {
368 currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
369 /* Si obtuve un symbolo valido lo emito*/
370 if (decoded_symbol != 256) {
371 fputc(decoded_symbol,fpdest);
372 currnode = shuff->codetree;
373 --(shuff->bytesleft);
378 /* Close destination */
384 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
387 HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
388 shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
391 shuff->codebuffer = 0;
393 shuff->coderfp = NULL;
394 shuff->targetfile = NULL;
395 shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
396 strcpy(shuff->sourcefile,inputfile);
397 if (outputfile != NULL) {
398 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
399 strcpy(shuff->targetfile,outputfile);
402 /* Levanto cuantos bytes debo decodificar y la freqtable */
403 if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return NULL;
404 vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
405 vfread(shuff->freqtable,sizeof(t_freq),256,shuff->decoderfp);
406 /* Armo el arbol de huffman que uso para decodificar */
407 shuff->codetree = shuff_buildtree(shuff->freqtable);
412 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
415 HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
418 /* Inicializo la estructura para trabajar con Huff Static by File */
419 fshuff->coderfp = NULL;
420 fshuff->decoderfp = NULL;
421 fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
422 fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
423 strcpy(fshuff->sourcefile,inputfile);
424 strcpy(fshuff->targetfile,outputfile);
425 fshuff->volsize = volsize;
428 fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
429 for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;
431 fshuff->codetree = NULL;
436 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
439 HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
442 /* Inicializo la estructura para trabajar con Huff Static by Chunks */
443 cshuff->decoderfp = NULL;
444 cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
445 cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
446 strcpy(cshuff->targetfile,outputfile);
447 strcpy(cshuff->sourcefile,outputfile);
448 strcat(cshuff->sourcefile,"~");
449 cshuff->volsize = volsize;
452 cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
453 for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;
455 cshuff->codetree = NULL;
457 /* Abrimos un archivo temporal para ir tirando los chunks */
458 if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;
463 int shuff_loadmodel(HUFF_STATE *shuff, char *modelfile) {
467 if ((shuff) && (shuff->freqtable) && (modelfile)) {
468 /* Cargo el modelo de disco */
469 if ((fp = fopen(modelfile,"r")) == NULL) return 0;
470 if (fread(shuff->freqtable,sizeof(t_freq),256,fp) != 256) return 0;
478 int shuff_savemodel(HUFF_STATE *shuff) {
484 if ((shuff) && (shuff->targetfile) && (shuff->freqtable)) {
485 /* Preparo el nombre del archivo con la tabla */
486 auxfilename = (char*)malloc(strlen(shuff->targetfile)+1);
487 stopchar = strrchr(shuff->targetfile,'.');
488 strncpy(auxfilename,shuff->targetfile,stopchar - shuff->targetfile);
489 auxfilename[stopchar - shuff->targetfile] = 0;
490 strcat(auxfilename,".ftb");
492 /* Lo creamos y dumpeamos la tabla de frecuencias (modelo) */
493 if ((fp = fopen(auxfilename,"w")) == NULL) return 0;
494 fwrite(shuff->freqtable,sizeof(t_freq),256,fp);
502 void shuff_deinit_encoder(HUFF_STATE *shuff)
504 /* Libero mallocs y cierro archivos */
505 if (shuff->freqtable) free(shuff->freqtable);
506 if (shuff->coderfp) fclose(shuff->coderfp);
507 if (shuff->bychunk) unlink(shuff->sourcefile);
508 if (shuff->sourcefile) free(shuff->sourcefile);
509 if (shuff->targetfile) free(shuff->targetfile);
511 /* Destruyo recursivamente el arbol de codigos */
514 void shuff_deinit_decoder(HUFF_STATE *shuff)
516 /* Libero mallocs y cierro archivos */
517 if (shuff->freqtable) free(shuff->freqtable);
518 if (shuff->sourcefile != NULL) free(shuff->sourcefile);
519 if (shuff->targetfile != NULL) free(shuff->targetfile);
520 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
522 /* Destruyo recursivamente el arbol de codigos */