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_file(HUFF_STATE *shuff)
314 unsigned long int codebuffer;
316 unsigned short int decoded_symbol;
319 /* Levanto cuantos bytes decodeo y la freq table */
320 if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;
321 currnode = shuff->codetree;
323 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
325 /* Leo un buffer de 32 bits */
326 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
327 bitsleft = sizeof(unsigned long int) * 8;
329 /* Proceso el buffer sacando simbolos hasta que se me agote */
330 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {
331 currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
332 /* Si obtuve un symbolo valido lo emito*/
333 if (decoded_symbol != 256) {
334 fputc(decoded_symbol,fpdest);
335 currnode = shuff->codetree;
336 --(shuff->bytesleft);
346 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
349 HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
350 shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
353 shuff->coderfp = NULL;
354 shuff->targetfile = NULL;
355 shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
356 strcpy(shuff->sourcefile,inputfile);
357 if (outputfile != NULL) {
358 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
359 strcpy(shuff->targetfile,outputfile);
362 /* Levanto cuantos bytes decodeo y la freq table */
363 if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return 0;
364 vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
365 vfread(shuff->freqtable,sizeof(unsigned long int),256,shuff->decoderfp);
366 shuff->codetree = shuff_buildtree(shuff->freqtable);
371 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
374 HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
377 /* Inicializo la estructura para trabajar con Huff Static by File */
378 fshuff->coderfp = NULL;
379 fshuff->decoderfp = NULL;
380 fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
381 fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
382 strcpy(fshuff->sourcefile,inputfile);
383 strcpy(fshuff->targetfile,outputfile);
384 fshuff->volsize = volsize;
385 fshuff->preloadfreq = 0;
386 fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
387 for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;
389 fshuff->bytesleft = 0;
390 fshuff->codetree = NULL;
395 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
398 HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
401 /* Inicializo la estructura para trabajar con Huff Static by Chunks */
402 cshuff->decoderfp = NULL;
403 cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
404 cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
405 strcpy(cshuff->targetfile,outputfile);
406 strcpy(cshuff->sourcefile,outputfile);
407 strcat(cshuff->sourcefile,"~");
408 cshuff->volsize = volsize;
409 cshuff->preloadfreq = 1;
410 cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
411 for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;
413 cshuff->bytesleft = 0;
414 cshuff->codetree = NULL;
416 /* Abrimos un archivo temporal para ir tirando los chunks */
417 if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;
422 void shuff_deinit_encoder(HUFF_STATE *shuff)
424 /* Libero mallocs y cierro archivos */
425 free(shuff->freqtable);
426 if (shuff->coderfp != NULL) fclose(shuff->coderfp);
427 if (shuff->preloadfreq == 1) unlink(shuff->sourcefile);
428 free(shuff->sourcefile);
429 free(shuff->targetfile);
431 /* Destruyo recursivamente el arbol de codigos */
434 void shuff_deinit_decoder(HUFF_STATE *shuff)
436 /* Libero mallocs y cierro archivos */
437 free(shuff->freqtable);
438 free(shuff->sourcefile);
439 if (shuff->targetfile != NULL) free(shuff->targetfile);
440 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
442 /* Destruyo recursivamente el arbol de codigos */