]> git.llucax.com Git - z.facultad/75.06/jacu.git/blobdiff - src/jacu.c
Cambios minimos, no se si entraran en la impresion :(
[z.facultad/75.06/jacu.git] / src / jacu.c
index 3d18ed3be44af85c1c97ae75db13ec99fe6283ff..d8f6de344f5606fba36779270ed2662336988ac2 100644 (file)
+/*----------------------------------------------------------------------------
+ *                   jacu - Just Another Compression Utility
+ *----------------------------------------------------------------------------
+ * This file is part of jacu.
+ *
+ * jacu is free software; you can redistribute it and/or modify it under the
+ * terms of the GNU General Public License as published by the Free Software
+ * Foundation; either version 2 of the License, or (at your option) any later
+ * version.
+ *
+ * jacu is distributed in the hope that it will be useful, but WITHOUT ANY
+ * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
+ * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with jacu; if not, write to the Free Software Foundation, Inc., 59 Temple
+ * Place, Suite 330, Boston, MA  02111-1307  USA
+ *----------------------------------------------------------------------------
+ */
 
-#include "statichuff/statichuff.h"
 #include "blocksorting/bs.h"
 #include "mtf/mtf.h"
+#include "zerogrouping/zerogrouping.h"
+#include "statichuff/statichuff.h"
 #include "vfile/vfile.h"
+#include "vfile/common.h"
 #include <stdlib.h>
 #include <stdio.h>
 #include <unistd.h>
 
+long fsize(const char* filename);
+
+/* Flags del archivo comprimido */
+#define FLAGS_ZG 0x1
+#define FLAGS_WS 0x2
+#define FLAGS_RESERVED_1 0x4
+#define FLAGS_RESERVED_2 0x8
+#define FLAGS_RESERVED_3 0x16
+#define FLAGS_RESERVED_4 0x64
+#define FLAGS_RESERVED_5 0x128
+#define FLAGS_RESERVED_6 0x255
+
+typedef struct _flags_ {
+       int cflag;
+       int dflag;
+       int zflag;
+       int tflag;
+       int qflag;
+       int sflag;
+       int mflag;
+       int rflag; /* Richard Dictionary :-) */
+} t_Flags;
+
+int comprimir(char *src, char *dst, Uint32 pagesize, Uint32 volumesize, t_Flags *flags, char *staticmodel);
+int descomprimir(char *src, char *dst);
+
+char is_flags_on(unsigned char flags, unsigned char flag)
+{
+       return (flags & flag);
+}
+
+char flag_on(unsigned char flags, unsigned char flag)
+{
+       return (flags | flag);
+}
+
+char flag_off(unsigned char flags, unsigned char flag)
+{
+       return (flags & (~flag));
+}
+
 int main(int argc, char* argv[])
 {      
-       int cflag = 0;
-       int dflag = 0;
-       int tflag = 0;
-       int pflag = 0;
        long int volumesize = 0;
-       size_t pagesize = 32768; /* 32KB */
+       Uint32 pagesize = 32768; /* 32KB */
        int ch;
-       t_BlockSort *bs;
+       t_Flags flags;
+       char *staticmodel = NULL;
                        
-       while ((ch = getopt(argc, argv, "cdt:p:")) != -1) { 
+       memset(&flags, 0, sizeof(t_Flags));
+
+       while ((ch = getopt(argc, argv, "rscdzm:t:q:")) != -1) { 
                 
                switch (ch) { 
-                       case 'c': cflag = 1; 
+                       case 'c': flags.cflag = 1; 
                                          break;
 
-                       case 'd': dflag = 1; 
+                       case 'd': flags.dflag = 1; 
                                          break; 
 
-                       case 't': tflag = 1; 
-                                         volumesize = atol(optarg);
+                       case 'z': flags.zflag = 1; 
                                          break; 
-
-                       case 'p': pflag = 1; 
-                                         pagesize = atoi(optarg);
+                       
+                       case 'm': flags.mflag = 1;
+                                         staticmodel = optarg;
                                          break; 
+                       
+                       case 's': flags.sflag = 1;                                        
+                                         break;
+
+                       case 't': flags.tflag = 1; 
+                               volumesize = atol(optarg);
+                               break; 
 
-                       default: fprintf(stderr, "Usage: %s [-cdpt] sourcefile targetfile\n", argv[0]); 
+                       case 'r': flags.rflag = 1;
+                               break;
+                       case 'q': flags.qflag = 1; 
+                               switch (atoi(optarg))
+                               {
+                                       case 0: pagesize = 1024; /* 1K */
+                                               break;
+                                       case 1: pagesize = 2048; /* 2K */
+                                               break;
+                                       case 2: pagesize = 4096; /* 4K */
+                                               break;
+                                       case 3: pagesize = 8192; /* 8K */
+                                               break;
+                                       case 4: pagesize = 16384; /* 16K */
+                                               break;
+                                       case 5: pagesize = 32768; /* 32K */
+                                               break;
+                                       case 6: pagesize = 65536; /* 64K */
+                                               break;
+                                       case 7: pagesize = 131072; /* 128K */
+                                               break;
+                                       case 8: pagesize = 262144; /* 256K */
+                                               break;
+                                       case 9: pagesize = 524288; /* 512K */
+                                               break;
+                                       default: pagesize = 0; /* error */
+                               }
+                               break; 
+
+                       default: fprintf(stderr, "Usage: %s [-cdzsr][-q blksize][-t volsize][-m modeldumpfile] source target\n", argv[0]); 
                                         return(2);
                }
        }
                
-       if ( (argc == 1) || (cflag & dflag) || !(cflag | dflag) || ((argc - optind) < 2) ) {
-               fprintf(stderr, "Usage: %s [-cdt] sourcefile targetfile\n", argv[0]); 
+       if ( (argc == 1) || (flags.cflag & flags.dflag) || !(flags.cflag | flags.dflag) || ((argc - optind) < 2) || (flags.mflag & flags.sflag)) {
+               fprintf(stderr, "Usage: %s [-cdzsr][-q compressionquality][-t volsize][-m modeldumpfile] source target\n", argv[0]); 
                return (3);
        }
-       if ((tflag) && (volumesize <= 0l)) {
+       if ((flags.tflag) && (volumesize <= 0l)) {
                fprintf(stderr,"Error: The volume size must be a non-zero value\n");
                return (4);
        }
-       if ((pflag) && (pagesize <= 1u)) {
-               fprintf(stderr,"Error: El tamaño de página debe ser mayor a 1 byte.\n");
+       if ((flags.qflag) && (pagesize <= 1u)) {
+               fprintf(stderr,"Error: El nivel de compresión debe ser entre 0 (menor) y 9 (mayor).\n");
                return (5);
        }
                
-       if (cflag == 1) {
-               /* Comprimo */
-               /* No me gusta el tmpfile ... es para probar como anda todo junto */
-               FILE *fp, *fp_out;
-               unsigned long int i, j, total, k;
-               char *mtf;
-               char *salida, *data, c;
-               data = malloc(sizeof(char)*pagesize);
-               /* Reservo lugar tambien para guardar el k y el tamaño  */
-               salida = malloc(sizeof(char)*(pagesize)+sizeof(unsigned long int)*2);
-               bs = bs_create(pagesize);
-
-               fp = fopen(argv[optind], "rb");
-               fp_out = fopen("tmp.comp", "wb");
-
-               c = fgetc(fp);
-               total = 0;
-               while (!feof(fp)) {
-                       i = 0;
-                       while ((!feof(fp)) && (i < pagesize)) {
-                               data[i++] = c;
-                               c = fgetc(fp);
-                               total++;
-                       }
+       if (flags.cflag == 1) {
+               return comprimir(argv[optind], argv[optind+1], pagesize, volumesize, &flags, staticmodel);
+       }
+       
+       if (flags.dflag == 1) { 
+               return descomprimir(argv[optind], argv[optind+1]);
+       }
+
+       return 0;
+}
 
-                       /* Hago el BS */
-                       bs_solve(data, salida, bs, &k, i);
+long fsize(const char* filename)
+{
+       FILE* file;
+       long  file_size;
 
-                       /* Le aplico el MTF, salteo el tamaño del bloque para que no se pierda. */
-                       mtf = jacu_mtf(salida+sizeof(unsigned long int), i+sizeof(unsigned long int));
-                       for(j=0; j<i; j++)
-                               fputc(mtf[j], fp_out);
-                       free(mtf);
-               }
+       if (!(file = fopen(filename, "ab"))) return -1;
+       file_size = ftell(file);
+       fclose(file);
+       return file_size;
+}
+
+int comprimir(char *src, char *dst, Uint32 pagesize, Uint32 volumesize, t_Flags *flags, char *staticmodel)
+{
+       /* Comprimo */          
+       t_BlockSort *bs;
+       HUFF_STATE *shuff;
+       FILE *fp;
+       Uint32 i, j, total, k;
+       unsigned char *mtf;
+       unsigned char *salida, *data;
+       unsigned char *z;
+       unsigned char file_flags = 0;
+       int z_len;
+       
+       /* Abrimos el archivo a comprimir y encodeamos bloques */
+       if ((fp = fopen(src, "rb")) == NULL) return 1;
+       
+       /* Preparo el compresor huffman */
+       if ((shuff = shuff_init_encoder_bychunk(dst, volumesize*1024)) == NULL) return 1;
+       if (flags->mflag == 1) shuff_loadmodel(shuff, staticmodel);
+       
+       /* Preparo el BS alocando mem para la Salida: V(vector) + K(colnum) */
+       data = malloc(sizeof(unsigned char)*pagesize);
+       salida = malloc(sizeof(unsigned char)*pagesize+sizeof(Uint32));
+       bs = bs_create(pagesize);
+
+       /* Guardamos el pagesize como header (huffencoded) */
+       shuff_scanfreq_chunk(shuff,(char*)&pagesize,sizeof(Uint32));
+
+       /* Guardamos cabecera para indicar si usamos ZG (huffencoded) */
+       if (flags->zflag)
+               file_flags = flag_on(file_flags, FLAGS_ZG);
+       if (flags->rflag)
+               file_flags = flag_on(file_flags, FLAGS_WS);
+
+       shuff_scanfreq_chunk(shuff, &file_flags, 1);
 
-               /* Limpiando */
-               fclose(fp);
-               fclose(fp_out);
-               bs_destroy(bs);
+       total = 0;
+       while (!feof(fp)) {
+               i = 0;
+               i = bs_readblock(fp, data, pagesize, flags->rflag);
+               total += i;
 
-               /* Comprimo con huffman */
-               i = shuff_encode_file("tmp.comp",argv[optind+1], volumesize);
 
-               /* borro el temporal */
-               unlink("tmp.comp");
-               return i;
+               /* Aplico BS guardando su resultado + el K en salida */
+               bs_solve(data, salida, bs, &k, i);
+
+               /* Le aplico el MTF a salida */
+               mtf = jacu_mtf(salida, i+sizeof(Uint32), &z, &z_len);
+                               
+               /* Guardo el z_len y el Z */
+               shuff_scanfreq_chunk(shuff,(char*)&z_len,sizeof(int));
+               shuff_scanfreq_chunk(shuff,z,z_len);                    
+               
+               /* Si me lo piden, aplico ZG. */
+               if (flags->zflag) {
+                       Uint32 len;
+                       unsigned char buff[2];
+                       Uint32 total_size = i + sizeof(Uint32);
+                       ZG zg;
+                       /* Guardo la salida del MTF con ceros agrupados (ZG) */
+                       zg_init(&zg);
+                       for (j = 0; j < total_size; ++j)
+                               if ((len = zg_group(&zg, buff, mtf[j])))
+                                       shuff_scanfreq_chunk(shuff, buff, len);
+
+                               /* Flusheo ultimo zgrouping */
+                               if ((len = zg_group_finish(&zg,buff)))
+                                       shuff_scanfreq_chunk(shuff, buff, len);
+               } else {
+                       /* Comprimo la salida del MTF */
+                       shuff_scanfreq_chunk(shuff,mtf,i+sizeof(Uint32));
+               }
+               free(mtf);
+               free(z);
        }
+
+       /* Limpiando */
+       if (fclose(fp)) fprintf(stderr, "Error al cerrar archivo de entrada!\n");
+       bs_destroy(bs);
+       free(data);
+       free(salida);
+
+       /* Comprimo con Huffman */              
+       shuff_encode_file(shuff);
+       if (flags->sflag == 1) shuff_savemodel(shuff);
+       /* Shutdown Huffman */
+       shuff_deinit_encoder(shuff);
+       free(shuff);
+
+       /* Muestro bpb */
+       printf("%s: %.04f bits/byte.\n", dst, vfsize(dst)*8.0f/fsize(src));
+       return 0;
+}
+
+int descomprimir(char *src, char *dst)
+{
+       /* Descomprimo */
+       FILE *fp_out;
+       Uint32 block_size = 0, k;
+       unsigned char *block, *mtf, *orig;
+       unsigned char *z;
+       Uint32 z_len=0,moredata = 0,decoded = 0;
+       unsigned char file_flags = 0,retbytes = 0;
+       HUFF_STATE *shuff;
+
+       /* Inicializo el descompresor */
+       if ((shuff = shuff_init_decoder(src, NULL)) == NULL) return 1;
+                       
+       /* Abrimos el archivo de salida */
+       fp_out = fopen(dst, "wb");
        
-       if (dflag == 1) { 
-               /* Descomprimo */
-               FILE *fp_out;
-               VFILE *fp_in;
-               unsigned long int block_size, k;
-               char *block, *mtf, *orig;
-               int *pos;
-
-               shuff_decode_file(argv[optind], "tmp.comp"); /*argv[optind+1]);*/
-               fp_in = vfopen("tmp.comp", "r", 0);
-               fp_out = fopen(argv[optind+1], "wb");
-
-               while (!vfeof(fp_in)) {
-                       block_size = 0;
-                       vfread(&block_size, sizeof(unsigned long int), 1, fp_in);
-                       if (block_size > 0) {
-                               block = malloc((block_size+sizeof(unsigned long int))*sizeof(char));
-                               orig = malloc(block_size*sizeof(char));
-                               vfread(block, block_size, sizeof(char), fp_in);
-
-                               mtf = jacu_mtf_inv(block, /*XXX NO LO TENGO XXX */pos, block_size);
-
-                               memcpy(&k, block, sizeof(unsigned long int));
-
-                               bs_restore(orig, block+sizeof(unsigned long int), k, block_size);
-
-                               fwrite(orig, block_size, sizeof(char), fp_out);
-                               free(block);
-                               free(orig);
-                               free(mtf);
+       /* Descomprimo primero que nada el pagesize utilizado para comprimir */
+       if (!(moredata = shuff_decode_chunk(shuff,(char*)&block_size,sizeof(Uint32),&decoded))) return 1;
+
+       /* Descomprimo byte que indica si se usa ZG */
+       if (!(moredata = shuff_decode_chunk(shuff, &file_flags, 1, &decoded))) return 1;
+
+       /* Creo buffers */
+       block = malloc(block_size*sizeof(unsigned char)+sizeof(Uint32));
+       orig = malloc(block_size*sizeof(unsigned char));
+
+       /* Descomprimimos de a chunks segun convenga */
+       do {                    
+               if (block_size > 0) {
+                       /* Descomprimo el Zlen y el Z del MTF*/
+                       moredata = shuff_decode_chunk(shuff,(char*)&z_len,sizeof(int),&decoded);                                        
+                       z = malloc(sizeof(unsigned char)*z_len);
+                       moredata = shuff_decode_chunk(shuff,z,z_len,&decoded);                          
+                       
+                       /* Veo si se uso Zero Grouping para comprimir */
+                       if (is_flags_on(file_flags, FLAGS_ZG)) {
+                               ZG zg;
+                               unsigned char zgbuffer[255];
+                               unsigned char zgbyte = 0;
+                               int zgmoved = 0;
+                               Uint32 zgungrouped = 0;
+                               /* Desagrupo bytes hasta completar la pagina or End of Source File */
+                               zg_init(&zg);
+                               do {
+                                       /* Levanto un byte zerogrouped y lo paso por el zg_ungroup */
+                                       zgmoved = 0;
+                                       moredata = shuff_decode_chunk(shuff,&zgbyte,1,&decoded);
+                                       retbytes = zg_ungroup(&zg,zgbuffer,zgbyte);
+                                       /* Muevo del zgbuffer a mi bloque lo que corresponda */
+                                       while ((zgmoved < retbytes) && (zgungrouped < block_size+sizeof(Uint32))) {
+                                               block[zgungrouped++] = zgbuffer[zgmoved++];
+                                       }
+                               } while ((moredata) && (zgungrouped < block_size+sizeof(Uint32)));
+
+                               /* Me fijo si el ultimo byte procesado que me completo la pagina fue un 0 */
+                               if (zgbyte == 0) {
+                                       /* Leo un byte mas (un 0 seguro) y zg_ungroup cambiara su estado */
+                                       moredata = shuff_decode_chunk(shuff,&zgbyte,1,&decoded);
+                                       zg_ungroup(&zg,zgbuffer,zgbyte);
+                               }
+
+                               /* Normalizo variables para continuar en common code */
+                               decoded = zgungrouped;
+                       }
+                       else {
+                               /* Levanto una salida de MTF */
+                               moredata = shuff_decode_chunk(shuff,block,block_size+sizeof(Uint32),&decoded);
+                       }
+                       
+                       /* Le aplico MTF inverso a la salida de MTF levantada previamente */
+                       mtf = jacu_mtf_inv(z, block, decoded);
+
+                       /* Ya tengo la salida del BS, tonces levanto su K */
+                       memcpy(&k, mtf, sizeof(Uint32));
+
+                       /* Obtengo el chunk original aplicando BS Inverso */
+                       bs_restore(orig, mtf+sizeof(Uint32), k, decoded - sizeof(Uint32));
+
+                       decoded -= sizeof(Uint32);
+                       if (is_flags_on(file_flags, FLAGS_WS)) {
+                               orig = bs_finalblock(orig, decoded, &decoded);
                        }
+
+                       fwrite(orig, decoded, sizeof(unsigned char), fp_out);
+                       free(mtf);
+                       free(z);
                }
-               vfclose(fp_in);
-               fclose(fp_out);
-       }
+               else return 1;
+       } while (moredata);
+       
+       /* Close up files and free mem */
+       fclose(fp_out);
+       free(block);
+       free(orig);
 
+       /* Shutdown Huffman */
+       shuff_deinit_decoder(shuff);
+       free(shuff);
        return 0;
 }