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);
86 int shuff_scanfreq(char *inputfile, t_freq *freqtable)
93 /* Inicializamos la tabla de frecuencias */
94 for (i = 0; i < 256; ++i) freqtable[i] = 0;
97 if ((fp = fopen(inputfile,"r")) == NULL) return 0;
99 /* Contamos las frecuencias */
101 if (symbol == EOF) continue;
106 /* Si llegue al tope de freq acumulada, halve em */
107 if (sumfreq == 14930352)
108 sumfreq = shuff_rescalefreq(freqtable);
115 SHUFFNODE *shuff_buildlist(t_freq *freqtable, int *nonzerofreqs)
117 int i,j = 0,nonzero = 0;
118 SHUFFNODE *inputlist;
120 /* Calculo cuantas frequencias > 0 hay y creo la tabla */
121 for (i = 0; i < 256; ++i) if (freqtable[i] > 0) nonzero++;
122 inputlist = (SHUFFNODE*)malloc(sizeof(SHUFFNODE)*nonzero);
124 /* Cargo la inputlist del huffman solo con freqs > 0 */
125 for (i = 0; i < 256; ++i)
126 if (freqtable[i] > 0) {
127 inputlist[j].symbol = i;
128 inputlist[j].freq = freqtable[i];
129 inputlist[j].lchild = NULL;
130 inputlist[j].rchild = NULL;
134 *nonzerofreqs = nonzero;
138 SHUFFNODE *shuff_buildtree(t_freq *ftable)
140 SHUFFNODE *lastsymbol;
141 SHUFFNODE *node1,*node2,*root;
142 SHUFFNODE *inputlist;
145 /* Genero la input list en base a la cual genera el arbol */
146 inputlist = shuff_buildlist(ftable, &freqcount);
147 lastsymbol = inputlist+(freqcount-1);
149 while (lastsymbol > inputlist) {
150 /* Ordeno la lista por frecuencia descendente */
151 qsort(inputlist,freqcount,sizeof(SHUFFNODE),shuff_compnode);
152 /* Tomo los ultimos dos elementos, generando dos nodos del arbol */
153 node1 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
154 node2 = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
155 shuff_cpynode(node1,lastsymbol-1);
156 shuff_cpynode(node2,lastsymbol);
158 /* Nodo ficticio con la suma de las probs y los ptros a childs */
159 lastsymbol->symbol = 256;
160 lastsymbol->freq = node1->freq + node2->freq;
161 lastsymbol->lchild = node1;
162 lastsymbol->rchild = node2;
166 /* Copio la raiz para poder liberar la lista sin perderla */
167 root = (SHUFFNODE*)malloc(sizeof(SHUFFNODE));
168 shuff_cpynode(root,lastsymbol);
173 /* Devuelvo el puntero a la raiz del arbol de huffman */
177 void shuff_printcodes(SHUFFCODE *codetable,t_freq *freqtable)
180 unsigned short int auxcode;
183 for (i = 0; i < 256; ++i) {
184 if (codetable[i].codelength > 0) {
185 auxcode = codetable[i].code;
186 printf("Symbol:%i Freq: %li Code:",i,freqtable[i]);
187 for (j = codetable[i].codelength-1; j >= 0; --j) {
188 auxcode = codetable[i].code;
189 auxcode = auxcode >> j;
193 printf(" Length:%i\n",codetable[i].codelength);
198 void shuff_zerocodes(SHUFFCODE *table)
202 /* Inicializo los codigos prefijos */
203 for (i = 0; i < 256; ++i) {
205 table[i].codelength = 0;
209 void shuff_buildcodes(SHUFFCODE *table, SHUFFNODE *node, int level, int code)
211 if (node->symbol < 256) {
212 /* Guardo el codigo en la tabla */
213 table[node->symbol].code = code;
214 table[node->symbol].codelength = level;
218 shuff_buildcodes(table,node->lchild,level+1,code);
220 shuff_buildcodes(table,node->rchild,level+1,code);
224 int shuff_encode_symbols(HUFF_STATE *shuff, SHUFFCODE *ctable)
229 unsigned long int sourcesize;
231 SHUFFCODE symbolcode;
233 /* Abrimos el file */
234 if ((fpsource = fopen(shuff->sourcefile,"r")) == NULL) return 0;
235 if ((fpdest = vfopen(shuff->targetfile,"w",shuff->volsize)) == NULL) return 0;
237 /* Guardamos el size el archivo original e inputlist como header */
238 fseek(fpsource,0,SEEK_END);
239 sourcesize = ftell(fpsource);
240 vfwrite(&sourcesize,sizeof(unsigned long int),1,fpdest);
241 vfwrite(shuff->freqtable,sizeof(t_freq),256,fpdest);
244 fseek(fpsource,0,SEEK_SET);
245 while (!feof(fpsource)) {
246 /* Levanto un symbolo (byte) */
247 symbol = fgetc(fpsource);
248 if (symbol == EOF) continue;
250 /* Cargamos el codigo y lo emitimos */
251 symbolcode = ctable[symbol];
252 for (i = symbolcode.codelength; i > 0; --i) {
253 bit = (symbolcode.code >> (i-1)) & 1;
254 putbit(bit,0,0,fpdest);
258 /* Hacemos un flush de lo que haya quedado en el buffer de salida */
259 putbit(0,0,1,fpdest);
265 int shuff_encode_file(HUFF_STATE *shuff)
268 SHUFFCODE *codetable = (SHUFFCODE*)malloc(sizeof(SHUFFCODE)*256);
270 /* Veo si debo armar una freqtable o si esta preloaded */
271 if (!shuff->preloadfreq) if (!shuff_scanfreq(shuff->sourcefile,shuff->freqtable)) return 0;
273 /* Genero el arbol de huffman */
274 shuff->codetree = shuff_buildtree(shuff->freqtable);
276 /* Armo la tabla de codigos prefijos para el encoder */
277 shuff_zerocodes(codetable);
278 shuff_buildcodes(codetable,shuff->codetree,0,0);
279 /*shuff_printcodes(codetable,shuff->freqtable);*/
281 /* Encodeo byte per byte */
282 shuff_encode_symbols(shuff,codetable);
284 /* Free up memory baby yeah */
290 SHUFFNODE *shuff_decode_symbols(SHUFFNODE *entrynode, unsigned long int buffer,
291 int *bitsleft, unsigned short int *symbol)
295 /* Levanto el symbolo y si es uno valido, devuelvo */
296 *symbol = entrynode->symbol;
297 if (*symbol != 256) return entrynode;
298 if (*bitsleft == 0) return entrynode;
300 /* Obtengo otro bit a procesar y me muevo en el arbol */
301 bit = (buffer >> ((*bitsleft)-1)) & 1;
303 if (bit == 0) return shuff_decode_symbols(entrynode->lchild,buffer,bitsleft,symbol);
304 else return shuff_decode_symbols(entrynode->rchild,buffer,bitsleft,symbol);
307 int shuff_decode_file(HUFF_STATE *shuff)
310 unsigned long int codebuffer;
312 unsigned short int decoded_symbol;
315 /* Levanto cuantos bytes decodeo y la freq table */
316 if ((fpdest = fopen(shuff->targetfile,"w")) == NULL) return 0;
317 currnode = shuff->codetree;
319 while (!vfeof(shuff->decoderfp) && (shuff->bytesleft > 0)) {
321 /* Leo un buffer de 32 bits */
322 if (vfread(&codebuffer,sizeof(unsigned long int),1,shuff->decoderfp) != 1) continue;
323 bitsleft = sizeof(unsigned long int) * 8;
325 /* Proceso el buffer sacando simbolos hasta que se me agote */
326 while ((bitsleft > 0) && (shuff->bytesleft > 0)) {
327 currnode = shuff_decode_symbols(currnode,codebuffer,&bitsleft,&decoded_symbol);
328 /* Si obtuve un symbolo valido lo emito*/
329 if (decoded_symbol != 256) {
330 fputc(decoded_symbol,fpdest);
331 currnode = shuff->codetree;
332 --(shuff->bytesleft);
342 HUFF_STATE *shuff_init_decoder(char *inputfile, char *outputfile)
345 HUFF_STATE *shuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
346 shuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
349 shuff->coderfp = NULL;
350 shuff->targetfile = NULL;
351 shuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
352 strcpy(shuff->sourcefile,inputfile);
353 if (outputfile != NULL) {
354 shuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
355 strcpy(shuff->targetfile,outputfile);
358 /* Levanto cuantos bytes decodeo y la freq table */
359 if ((shuff->decoderfp = vfopen(shuff->sourcefile,"r",0)) == NULL) return 0;
360 vfread(&(shuff->bytesleft),sizeof(unsigned long int),1,shuff->decoderfp);
361 vfread(shuff->freqtable,sizeof(unsigned long int),256,shuff->decoderfp);
362 shuff->codetree = shuff_buildtree(shuff->freqtable);
367 HUFF_STATE *shuff_init_encoder_byfile(char *inputfile, char *outputfile, long volsize)
370 HUFF_STATE *fshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
373 /* Inicializo la estructura para trabajar con Huff Static by File */
374 fshuff->coderfp = NULL;
375 fshuff->decoderfp = NULL;
376 fshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(inputfile)+1));
377 fshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
378 strcpy(fshuff->sourcefile,inputfile);
379 strcpy(fshuff->targetfile,outputfile);
380 fshuff->volsize = volsize;
381 fshuff->preloadfreq = 0;
382 fshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
383 for (i = 0; i < 256; ++i) fshuff->freqtable[i] = 0;
385 fshuff->bytesleft = 0;
386 fshuff->codetree = NULL;
391 HUFF_STATE *shuff_init_encoder_bychunk(char *outputfile, long volsize)
394 HUFF_STATE *cshuff = (HUFF_STATE*)malloc(sizeof(HUFF_STATE));
397 /* Inicializo la estructura para trabajar con Huff Static by Chunks */
398 cshuff->decoderfp = NULL;
399 cshuff->sourcefile = (char*)malloc(sizeof(char)*(strlen(outputfile)+2));
400 cshuff->targetfile = (char*)malloc(sizeof(char)*(strlen(outputfile)+1));
401 strcpy(cshuff->targetfile,outputfile);
402 strcpy(cshuff->sourcefile,outputfile);
403 strcat(cshuff->sourcefile,"~");
404 cshuff->volsize = volsize;
405 cshuff->preloadfreq = 1;
406 cshuff->freqtable = (t_freq*)malloc(sizeof(t_freq)*256);
407 for (i = 0; i < 256; ++i) cshuff->freqtable[i] = 0;
409 cshuff->bytesleft = 0;
410 cshuff->codetree = NULL;
412 /* Abrimos un archivo temporal para ir tirando los chunks */
413 if ((cshuff->coderfp = fopen(cshuff->sourcefile,"w")) == NULL) return NULL;
418 void shuff_deinit_encoder(HUFF_STATE *shuff)
420 /* Libero mallocs y cierro archivos */
421 free(shuff->freqtable);
422 free(shuff->sourcefile);
423 free(shuff->targetfile);
424 if (shuff->coderfp != NULL) fclose(shuff->coderfp);
425 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
427 /* Destruyo recursivamente el arbol de codigos */
430 void shuff_deinit_decoder(HUFF_STATE *shuff)
432 /* Libero mallocs y cierro archivos */
433 free(shuff->freqtable);
434 free(shuff->sourcefile);
435 if (shuff->targetfile != NULL) free(shuff->targetfile);
436 if (shuff->decoderfp != NULL) vfclose(shuff->decoderfp);
438 /* Destruyo recursivamente el arbol de codigos */