Exemplo n.º 1
0
value caml_bz2_compress(value dest, value src)
{
  CAMLparam2 (dest, src);

  char* destBuf = String_val(dest);
  unsigned int destlen = caml_string_length(dest);

  char* srcBuf = String_val(src);
  unsigned int srclen = caml_string_length(src);

  switch(BZ2_bzBuffToBuffCompress(destBuf, &destlen, srcBuf, srclen,
				9, 0, 0)) {
  case BZ_OK:
	  break;

  case BZ_OUTBUFF_FULL:
	  caml_failwith("dest is too small for bz2_compress");
	  break;

  default:
	  caml_failwith("bz2_compress failed");
	  break;
  }

  CAMLreturn (Val_int(destlen));
}
Exemplo n.º 2
0
Arquivo: stream.c Projeto: epa/lrzip
static void bzip2_compress_buf(struct stream *s, int *c_type, i64 *c_len)
{
	uchar *c_buf;
	u32 dlen = s->buflen;

	if (!lzo_compresses(s))
		return;

	c_buf = malloc(dlen);
	if (!c_buf)
		return;

	if (BZ2_bzBuffToBuffCompress((char*)c_buf, &dlen, (char*)s->buf, s->buflen,
				     control.compression_level, 0,
				     control.compression_level * 10) != BZ_OK) {
		free(c_buf);
		return;
	}

	if (dlen >= *c_len) {
		/* Incompressible, leave as CTYPE_NONE */
		free(c_buf);
		return;
	}

	*c_len = dlen;
	free(s->buf);
	s->buf = c_buf;
	*c_type = CTYPE_BZIP2;
}
Exemplo n.º 3
0
int main(int argc, char *argv[]) {

    FILE *file;
    Byte  *buffer [512];
    Byte  *buff_dest [512];
    long filelen;
    int i, st;

    file = fopen(argv[1], "rw");
    fseek(file, SEEK_SET, 0);

    unsigned  int destLen=100;
    unsigned  int sourceLen=100;

    /*uLong destLen = st; // "Hello, world!" + NULL delimiter.
      	uLong sourceLen = st;*/

    while (st = fread(buffer, 1, SIZE, file)) { // Send the file
        printf("va a comprimir\n");
        if( BZ2_bzBuffToBuffCompress(buff_dest, &destLen, buffer, sourceLen, 1, 0,30 )!= BZ_OK ) {
            printf(" error\n");
        } else {
            printf(" correcto\n");
        }
    }

    /*if( BZ2_bzBuffToBuffCompress(buff_dest, &destLen, buffer, sourceLen, 1, 0,30 )!= BZ_OK ){
    	printf(" error\n");
         }else{
    	printf(" correcto\n");
         }*/

    return 0;

}
Exemplo n.º 4
0
static SquashStatus
squash_bz2_compress_buffer (SquashCodec* codec,
                            uint8_t* compressed, size_t* compressed_length,
                            const uint8_t* uncompressed, size_t uncompressed_length,
                            SquashOptions* options) {
  int block_size_100k;
  int work_factor;
  int bz2_res;
  unsigned int compressed_length_ui = (unsigned int) *compressed_length;

  if (options != NULL) {
    block_size_100k = ((SquashBZ2Options*) options)->block_size_100k;
    work_factor     = ((SquashBZ2Options*) options)->work_factor;
  } else {
    block_size_100k = SQUASH_BZ2_DEFAULT_BLOCK_SIZE_100K;
    work_factor     = SQUASH_BZ2_DEFAULT_WORK_FACTOR;
  }

  bz2_res = BZ2_bzBuffToBuffCompress ((char*) compressed, &compressed_length_ui,
                                      (char*) uncompressed, (unsigned int) uncompressed_length,
                                      block_size_100k, 0, work_factor);
  if (bz2_res == BZ_OK) {
    *compressed_length = compressed_length_ui;
  }

  return squash_bz2_status_to_squash_status (bz2_res);
}
Exemplo n.º 5
0
int
G_bz2_compress(unsigned char *src, int src_sz, unsigned char *dst,
		int dst_sz)
{
    int err;
    unsigned int i, nbytes, buf_sz;
    unsigned char *buf;

#ifndef HAVE_BZLIB_H
    G_fatal_error(_("GRASS needs to be compiled with BZIP2 for BZIP2 compression"));
    return -1;
#else

    /* Catch errors early */
    if (src == NULL || dst == NULL)
	return -1;

    /* Don't do anything if src is empty */
    if (src_sz <= 0)
	return 0;

    /* Output buffer has to be 1% + 600 bytes bigger for single pass compression */
    buf_sz = (unsigned int)((double)dst_sz * 1.01 + (double)600);

    if (NULL == (buf = (unsigned char *)
		 G_calloc(buf_sz, sizeof(unsigned char))))
	return -1;

    /* Do single pass compression */
    nbytes = buf_sz;
    err = BZ2_bzBuffToBuffCompress((char *)buf, &nbytes, /* destination */
                                   (char *)src, src_sz,  /* source */
				   9,			 /* blockSize100k */ 
				   0,                    /* verbosity */
				   0);                   /* workFactor */
    if (err != BZ_OK) {
	G_free(buf);
	return -1;
    }

    /* updated buf_sz is bytes of compressed data */
    if (nbytes >= (unsigned int)src_sz) {
	/* compression not possible */
	G_free(buf);
	return -2;
    }

    /* dst too small */
    if ((unsigned int)dst_sz < nbytes)
	return -2;

    /* Copy the data from buf to dst */
    for (i = 0; i < nbytes; i++)
	dst[i] = buf[i];

    G_free(buf);

    return nbytes;
#endif
}				/* G_bz2_compress() */
Exemplo n.º 6
0
Variant HHVM_FUNCTION(bzcompress, const String& source, int blocksize /* = 4 */,
                                  int workfactor /* = 0 */) {
  char *dest = NULL;
  int error;
  unsigned int source_len, dest_len;

  source_len = source.length();
  dest_len = source.length() + (0.01*source.length()) + 600;

  if (!(dest = (char *)malloc(dest_len + 1))) {
    return BZ_MEM_ERROR;
  }

  error = BZ2_bzBuffToBuffCompress(dest, &dest_len, (char *) source.c_str(),
                                   source_len, blocksize, 0, workfactor);
  if (error != BZ_OK) {
    free(dest);
    return error;
  } else {
    // this is to shrink the allocation, since we probably over allocated
    dest = (char *)realloc(dest, dest_len + 1);
    dest[dest_len] = '\0';
    String ret = String(dest, dest_len, AttachString);
    return ret;
  }
}
Exemplo n.º 7
0
int main ( int argc, char** argv )
{
   FILE* f;
   int   r;
   int   bit;
   int   i;

   if (argc != 2) {
      fprintf ( stderr, "usage: unzcrash filename\n" );
      return 1;
   }

   f = fopen ( argv[1], "r" );
   if (!f) {
      fprintf ( stderr, "unzcrash: can't open %s\n", argv[1] );
      return 1;
   }

   nIn = fread ( inbuf, 1, M_BLOCK, f );
   fprintf ( stderr, "%d bytes read\n", nIn );

   nZ = M_BLOCK;
   r = BZ2_bzBuffToBuffCompress (
         zbuf, &nZ, inbuf, nIn, 9, 0, 30 );

   assert (r == BZ_OK);
   fprintf ( stderr, "%d after compression\n", nZ );

   for (bit = 0; bit < nZ*8; bit++) {
      fprintf ( stderr, "bit %d  ", bit );
      flip_bit ( bit );
      nOut = M_BLOCK_OUT;
      r = BZ2_bzBuffToBuffDecompress (
            outbuf, &nOut, zbuf, nZ, 0, 0 );
      fprintf ( stderr, " %d  %s ", r, bzerrorstrings[-r] );

      if (r != BZ_OK) {
         fprintf ( stderr, "\n" );
      } else {
         if (nOut != nIn) {
           fprintf(stderr, "nIn/nOut mismatch %d %d\n", nIn, nOut );
           return 1;
         } else {
           for (i = 0; i < nOut; i++)
             if (inbuf[i] != outbuf[i]) { 
                fprintf(stderr, "mismatch at %d\n", i ); 
                return 1; 
           }
           if (i == nOut) fprintf(stderr, "really ok!\n" );
         }
      }

      flip_bit ( bit );
   }

   fprintf ( stderr, "all ok\n" );
   return 0;
}
Exemplo n.º 8
0
 virtual raft::kstatus run()
 {
     auto &in_ele( input[ "in" ].template peek< chunktype >() );
     auto &out_ele(  output[ "out" ].template allocate< chunktype >() );
     unsigned int length_out( chunktype::getChunkSize() );
     const auto ret_val( BZ2_bzBuffToBuffCompress( out_ele.buffer,
                                   &length_out,
                                   in_ele.buffer,
                                   in_ele.length,
                                   blocksize,
                                   verbosity,
                                   workfactor ) );
     if( ret_val == BZ_OK )
     {
         
         out_ele.length = length_out;
         out_ele.index  = in_ele.index;
         output[ "out" ].send();
         input[ "in" ].recycle( 1 );
     }
     else
     {
         switch( ret_val )
         {
             case BZ_CONFIG_ERROR:
             {
                 std::cerr << "if the library has been mis-compiled\n";
             }
             break;
             case BZ_PARAM_ERROR:
             {
                 std::cerr << "if dest is NULL or destLen is NULL\n";
                 std::cerr << "or blockSize100k < 1 or blockSize100k > 9\n";
                 std::cerr << "or verbosity < 0 or verbosity > 4\n";
                 std::cerr << "or workFactor < 0 or workFactor > 250\n";
             }
             break;
             case BZ_MEM_ERROR:
             {
                 std::cerr << "if insufficient memory is available\n";
             }
             break;
             case BZ_OUTBUFF_FULL:
             {
                 std::cerr << "if the size of the compressed data exceeds *destLen\n";
             }
             default:
             {
                 std::cerr << "undefined error\n";
             }
         }
         /** we need to fail here **/
         output[ "out" ].deallocate();
         input[ "in" ].unpeek();
         exit( EXIT_FAILURE );
     }
     return( raft::proceed );
 }
Exemplo n.º 9
0
int compressData(char *data) {
    char *buf;
    unsigned int bufLen;

    bufLen = (int)(strlen(data) * 1.001 + 12);
    buf = (char *)malloc(sizeof(char) * bufLen);
    BZ2_bzBuffToBuffCompress(buf, &bufLen, data, strlen(data), 5, 0, 0);
    memcpy(data, buf, bufLen);
    free(buf);
    return bufLen;
}
Exemplo n.º 10
0
/** \brief compress the \ref datum_t and return the compressed result
 * 
 * @param datum		the data \ref datum_t to compress
 * @param max_len	the maximum length of the result
 * @return		a \ref datum_t containing the compressed data. the \ref datum_t
 * 			is null if the result is larger than \ref max_len.
 */
datum_t	compress_bzip_t::compress(const datum_t &datum, size_t max_len)	throw()
{
	unsigned int	outlen  = max_len;
	// allocate the output buffer
	char	*outbuf = (char *)nipmem_alloca(max_len);
	// try to compress the data and put them in the output buffer
	int	err	= BZ2_bzBuffToBuffCompress(outbuf, &outlen, (char *)datum.get_data()
							, datum.get_len(), 3, 0, 0);
	// if the compression failed, return a NULL datum_t()
	if( err != BZ_OK )	return	datum_t();
	// copy the compressed data into a datum_t
	return datum_t(outbuf, outlen);
}
Exemplo n.º 11
0
static void ZIP_Compress( DaoProcess *proc, DaoValue *p[], int N )
{
	DString *source = p[0]->xString.value;
	DString *res = DaoProcess_PutChars( proc, "" );
	unsigned int resLen = source->size;
	int block = 100000;
	daoint size = source->size;

	DString_Reserve( res, size );
	size = 1 + size / block;
	if( size > 9 ) size = 9;
	BZ2_bzBuffToBuffCompress( res->chars, & resLen, source->chars, source->size, size, 0, 30 );
	DString_Reset( res, resLen );
}
Exemplo n.º 12
0
extern int
bzip2_encode
(const unsigned char *in_start, size_t in_len, unsigned char *out_start, size_t *pout_len, size_t out_max)
{
	int	blockSize100k =  9;
	int verbosity     =  0;
	int workFactor    = 30;
	size_t destlen    = out_max;

	int x = BZ2_bzBuffToBuffCompress( (char*)out_start, &destlen, (char*)in_start, in_len,
								blockSize100k, verbosity, workFactor);
	*pout_len = destlen;
	return x == BZ_OK;
}
Exemplo n.º 13
0
static void
convert_xml_child(HA_Message * msg, xmlNode * xml)
{
    int orig = 0;
    int rc = BZ_OK;
    unsigned int len = 0;

    char *buffer = NULL;
    char *compressed = NULL;
    const char *name = NULL;

    name = (const char *)xml->name;
    buffer = dump_xml_unformatted(xml);
    orig = strlen(buffer);
    if (orig < CRM_BZ2_THRESHOLD) {
        ha_msg_add(msg, name, buffer);
        goto done;
    }

    len = (orig * 1.1) + 600;   /* recomended size */

    compressed = malloc(len);
    rc = BZ2_bzBuffToBuffCompress(compressed, &len, buffer, orig, CRM_BZ2_BLOCKS, 0, CRM_BZ2_WORK);

    if (rc != BZ_OK) {
        crm_err("Compression failed: %d", rc);
        free(compressed);
        convert_xml_message_struct(msg, xml, name);
        goto done;
    }

    free(buffer);
    buffer = compressed;
    crm_trace("Compression details: %d -> %d", orig, len);
    ha_msg_addbin(msg, name, buffer, len);
  done:
    free(buffer);

#  if 0
    {
        unsigned int used = orig;
        char *uncompressed = NULL;

        crm_debug("Trying to decompress %d bytes", len);
        uncompressed = calloc(1, orig);
        rc = BZ2_bzBuffToBuffDecompress(uncompressed, &used, compressed, len, 1, 0);
        CRM_CHECK(rc == BZ_OK,;
            );
        CRM_CHECK(used == orig,;
            );
Exemplo n.º 14
0
bool
crm_compress_string(const char *data, int length, int max, char **result, unsigned int *result_len)
{
    int rc;
    char *compressed = NULL;
    char *uncompressed = strdup(data);
    struct timespec after_t;
    struct timespec before_t;

    if(max == 0) {
        max = (length * 1.1) + 600; /* recommended size */
    }

#ifdef CLOCK_MONOTONIC
    clock_gettime(CLOCK_MONOTONIC, &before_t);
#endif

    compressed = calloc(max, sizeof(char));
    CRM_ASSERT(compressed);

    *result_len = max;
    rc = BZ2_bzBuffToBuffCompress(compressed, result_len, uncompressed, length, CRM_BZ2_BLOCKS, 0,
                                  CRM_BZ2_WORK);

    free(uncompressed);

    if (rc != BZ_OK) {
        crm_err("Compression of %d bytes failed: %s " CRM_XS " bzerror=%d",
                length, bz2_strerror(rc), rc);
        free(compressed);
        return FALSE;
    }

#ifdef CLOCK_MONOTONIC
    clock_gettime(CLOCK_MONOTONIC, &after_t);

    crm_trace("Compressed %d bytes into %d (ratio %d:1) in %.0fms",
             length, *result_len, length / (*result_len),
             difftime (after_t.tv_sec, before_t.tv_sec) * 1000 +
             (after_t.tv_nsec - before_t.tv_nsec) / 1e6);
#else
    crm_trace("Compressed %d bytes into %d (ratio %d:1)",
             length, *result_len, length / (*result_len));
#endif

    *result = compressed;
    return TRUE;
}
Exemplo n.º 15
0
size_t
bz2_compress(void *s_start, void *d_start, size_t s_len, size_t d_len, int n)
{
	ASSERT(d_len <= s_len);

	if (BZ2_bzBuffToBuffCompress(d_start,(unsigned int *) &d_len, s_start,
				s_len, n, 0, 50) != BZ_OK) {
		if (d_len != s_len) // unchanged in case of error
			return (s_len);

		bcopy(s_start, d_start, s_len);
		return (s_len);
	}

	return (d_len);
}
Exemplo n.º 16
0
EXPORT BOOL WINAPI bz2compress(HSPEXINFO *hei)
{
	char* dest = (char *)hei->HspFunc_prm_getv();
	unsigned int destBufSize = hei->HspFunc_prm_geti();
	char* source = (char *)hei->HspFunc_prm_getv();
	unsigned int sourceLen = hei->HspFunc_prm_geti();
	int blockSize100k = hei->HspFunc_prm_getdi(5);
	unsigned int* destLen = &destBufSize;
	int ret;

	if (*hei->er) return *hei->er;
	ret = BZ2_bzBuffToBuffCompress(dest, destLen, source, sourceLen, blockSize100k, 0, 30);
	if (ret == BZ_OK) *hei->strsize = *destLen;

	return -abs(ret);

	return 0;
}
Exemplo n.º 17
0
void *Graphics::ptif_pack(pixel *src, int w, int h, int *result_size){
	int i = 0, datalen = (w*h)*3, cx = 0, cy = 0;
	unsigned char *red_chan = (unsigned char*)calloc(1, w*h);
	unsigned char *green_chan = (unsigned char*)calloc(1, w*h);
	unsigned char *blue_chan = (unsigned char*)calloc(1, w*h);
	unsigned char *data = (unsigned char*)malloc(((w*h)*3)+8);
	unsigned char *result = (unsigned char*)malloc(((w*h)*3)+8);

	for(cx = 0; cx<w; cx++){
		for(cy = 0; cy<h; cy++){
			red_chan[w*(cy)+(cx)] = PIXR(src[w*(cy)+(cx)]);
			green_chan[w*(cy)+(cx)] = PIXG(src[w*(cy)+(cx)]);
			blue_chan[w*(cy)+(cx)] = PIXB(src[w*(cy)+(cx)]);
		}
	}

	memcpy(data, red_chan, w*h);
	memcpy(data+(w*h), green_chan, w*h);
	memcpy(data+((w*h)*2), blue_chan, w*h);
	free(red_chan);
	free(green_chan);
	free(blue_chan);

	result[0] = 'P';
	result[1] = 'T';
	result[2] = 'i';
	result[3] = 1;
	result[4] = w;
	result[5] = w>>8;
	result[6] = h;
	result[7] = h>>8;

	i -= 8;

	if(BZ2_bzBuffToBuffCompress((char *)(result+8), (unsigned *)&i, (char *)data, datalen, 9, 0, 0) != 0){
		free(data);
		free(result);
		return NULL;
	}

	*result_size = i+8;
	free(data);
	return result;
}
Exemplo n.º 18
0
/*
 * Compress a buffer.
 */
static int
bzlib_compress(Transformation *xform, struct tapebuf *tpbin, unsigned long *destlen,
		const char *src, int srclen) {
#ifdef HAVE_BZLIB
	int compresult;
	unsigned int destlen2 = *destlen;
	compresult = BZ2_bzBuffToBuffCompress(
			tpbin->buf,
			&destlen2,
			(char *) src,
			srclen,
			xform->state.bzlib.complvl,
			0, 30);
	*destlen = destlen2;
	return compresult == BZ_OK ? 1 : 0;
#else
	return 1;
#endif /* HAVE_BZLIB */
}
Exemplo n.º 19
0
int compress_block_bzip2(u64 origsize, u64 *compsize, u8 *origbuf, u8 *compbuf, u64 compbufsize, int level)
{
    unsigned int destsize=compbufsize;

    switch (BZ2_bzBuffToBuffCompress((char*)compbuf, &destsize, (char*)origbuf, origsize, 9, 0, 30))
    {
    case BZ_OK:
        *compsize=(u64)destsize;
        return FSAERR_SUCCESS;
    case BZ_MEM_ERROR:
        errprintf("BZ2_bzBuffToBuffCompress(): BZIP2 compression failed "
                  "with an out of memory error.\nYou should use a lower "
                  "compression level to reduce the memory requirement.\n");
        return FSAERR_ENOMEM;
    default:
        return FSAERR_UNKNOWN;
    }

    return FSAERR_UNKNOWN;
}
Exemplo n.º 20
0
/**
 * compress_frame_buffer() - Compress the frame buffer and return its size
 *
 * We want to write tests which perform operations on the video console and
 * check that the frame buffer ends up with the correct contents. But it is
 * painful to store 'known good' images for comparison with the frame
 * buffer. As an alternative, we can compress the frame buffer and check the
 * size of the compressed data. This provides a pretty good level of
 * certainty and the resulting tests need only check a single value.
 *
 * @dev:	Video device
 * @return compressed size of the frame buffer, or -ve on error
 */
static int compress_frame_buffer(struct udevice *dev)
{
	struct video_priv *priv = dev_get_uclass_priv(dev);
	uint destlen;
	void *dest;
	int ret;

	destlen = priv->fb_size;
	dest = malloc(priv->fb_size);
	if (!dest)
		return -ENOMEM;
	ret = BZ2_bzBuffToBuffCompress(dest, &destlen,
				       priv->fb, priv->fb_size,
				       3, 0, 0);
	free(dest);
	if (ret)
		return ret;

	return destlen;
}
Exemplo n.º 21
0
static SquashStatus
squash_bz2_compress_buffer (SquashCodec* codec,
                            size_t* compressed_length,
                            uint8_t compressed[SQUASH_ARRAY_PARAM(*compressed_length)],
                            size_t uncompressed_length,
                            const uint8_t uncompressed[SQUASH_ARRAY_PARAM(uncompressed_length)],
                            SquashOptions* options) {
  int bz2_res;
  unsigned int compressed_length_ui = (unsigned int) *compressed_length;

  bz2_res = BZ2_bzBuffToBuffCompress ((char*) compressed, &compressed_length_ui,
                                      (char*) uncompressed, (unsigned int) uncompressed_length,
                                      squash_codec_get_option_int_index (codec, options, SQUASH_BZ2_OPT_LEVEL),
                                      0,
                                      squash_codec_get_option_int_index (codec, options, SQUASH_BZ2_OPT_WORK_FACTOR));
  if (bz2_res == BZ_OK) {
    *compressed_length = compressed_length_ui;
  }

  return squash_bz2_status_to_squash_status (bz2_res);
}
Exemplo n.º 22
0
void Bzip2Compress::Encode(void)
{
	direct = 0;	// set direction needed by parent [Get|Send]Chars()

	// get buffer
	char chunk[1024];
	char *buf = (char *)calloc(1, 1024);
	char *chunkbuf = buf;
	unsigned long chunklen;
	unsigned long len = 0;
	while((chunklen = GetChars(chunk, 1023))) {
		memcpy(chunkbuf, chunk, chunklen);
		len += chunklen;
		if (chunklen < 1023)
			break;
		else	buf = (char *)realloc(buf, len + 1024);
		chunkbuf = buf+len;
	}


	zlen = (long) (len*1.01)+600;
	char *zbuf = new char[zlen+1];
	if (len)
	{
		//printf("Doing compress\n");
		if (BZ2_bzBuffToBuffCompress(zbuf, (unsigned int*)&zlen, buf, len, level, 0, 0) != BZ_OK)
		{
			printf("ERROR in compression\n");
		}
		else {
			SendChars(zbuf, zlen);
		}
	}
	else
	{
		fprintf(stderr, "ERROR: no buffer to compress\n");
	}
	delete [] zbuf;
	free (buf);
}
Exemplo n.º 23
0
Cvirtual_binary Cxif_key::export_bz() const
{
	Cvirtual_binary d;
	int size = get_size();
	int external_size = get_external_size();
	Cvirtual_binary s;
	byte* w = s.write_start(size);
	save(w);
	unsigned int cb_d = s.size() + (s.size() + 99) / 100 + 600;
	t_xif_header_fast& header = *reinterpret_cast<t_xif_header_fast*>(d.write_start(sizeof(t_xif_header_fast) + cb_d + external_size));
	if (BZ_OK != BZ2_bzBuffToBuffCompress(reinterpret_cast<char*>(d.data_edit() + sizeof(t_xif_header_fast)), &cb_d, const_cast<char*>(reinterpret_cast<const char*>(s.data())), s.size(), 9, 0, 0))
		return Cvirtual_binary();
	w = d.data_edit() + sizeof(t_xif_header_fast) + cb_d;
	external_save(w);
	header.id = file_id;
	header.version = file_version_fast;
	header.size_uncompressed = size;
	header.size_compressed = cb_d;
	header.size_external = external_size;
	d.size(sizeof(t_xif_header_fast) + cb_d + external_size);
	return d;
}
Exemplo n.º 24
0
    unsigned long
    Bzip2Compressor::compressBlock(char* dst, unsigned long dst_len, char* src, unsigned long src_len)
    {
      // Get proper compression level.
      int plevel = level();
      if (plevel < 1)
        plevel = 1;

      unsigned compressed_length = dst_len;
      int rv = BZ2_bzBuffToBuffCompress(dst, &compressed_length, src, src_len, plevel, 0, 0);

      if (rv == BZ_OK)
        return compressed_length;

      if (rv == BZ_MEM_ERROR)
        throw OutOfMemory();

      if (rv == BZ_OUTBUFF_FULL)
        throw BufferTooShort(dst_len);

      return 0;
    }
Exemplo n.º 25
0
/* replacement for GZCLOSE */
static int mem_close(gzFile *stream)
{
	int status = -1;
	unsigned int comprlen = ALLOC_LEN - HDR_LEN;
	if (openmode != OM_WRITE) {
		/* was opened for read */
		free(plainmembuf);
		return 0;
	}
	comprmembuf = Util_malloc(ALLOC_LEN);
	if (BZ2_bzBuffToBuffCompress(comprmembuf + HDR_LEN, &comprlen, plainmembuf, plainmemoff, 9, 0, 0) == BZ_OK) {
		FILE *f;
		f = fopen(savename, "wb");
		if (f != NULL) {
			char icon[32 + 512];
#ifdef DEBUG
			printf("mem_close: plain len %lu, compr len %lu\n",
			       (unsigned long) plainmemoff, (unsigned long) comprlen);
#endif
			memcpy(icon, palette, 32);
			memcpy(icon + 32, bitmap, 512);
			ndc_vmu_create_vmu_header(comprmembuf, "Atari800DC",
						  "Atari800DC " A800DCVERASC " saved state",
						  comprlen, icon);
			comprlen = (comprlen + HDR_LEN + 511) & ~511;
			ndc_vmu_do_crc(comprmembuf, comprlen);
			status = (fwrite(comprmembuf, 1, comprlen, f) == comprlen) ? 0 : -1;
			status |= fclose(f);
#ifdef DEBUG
			if (status != 0)
				printf("mem_close: fwrite: error!!\n");
#endif
		}
	}
	free(comprmembuf);
	free(plainmembuf);
	return status;
}
Exemplo n.º 26
0
void TCPServer::sendData(signed char* data, int len)
{
    unsigned int initialSize = len;
    unsigned int resultingSize = len*0.25;
    char compressedData[resultingSize]; bzero(compressedData, resultingSize);
    BZ2_bzBuffToBuffCompress(compressedData, &resultingSize, (char *)data, initialSize, 5, 0, 0);
    __android_log_print(ANDROID_LOG_ERROR, "JNIDummy", "COMPRESSED SIZE: %d", resultingSize);

    //int n = write(newsockfd,data,len);
    char lenStr[10];
    sprintf(lenStr, "%d", resultingSize);
    int n = write(newsockfd,lenStr,10);


    n = write(newsockfd,compressedData,resultingSize);
    if (n < 0){
        __android_log_write(ANDROID_LOG_DEBUG, "JNIDummy", "ERROR writing to socket");
        //CommonFuncs::error("ERROR writing to socket");
    }
    else {
        __android_log_write(ANDROID_LOG_DEBUG, "JNIDummy", "SERVER WROTE TO SOCKET");
    }
}
Exemplo n.º 27
0
int main(int argc,char *argv[]) {
    int doCompress = 1;

    if (argc < 2) {
        printf("Nothing to do!\n");
        return 1;
    }
    if (argc == 3) {
        doCompress = 0;
    }
    FILE *f = fopen(argv[1],"r");
    if (!f) {
        perror(argv[1]);
        return 1;
    }
    char* infile = ArrayAlloc(0,1);
    int ch;
    while (!feof(f)) {
        ch = fgetc(f);
        if (ch == EOF) break;
        ArraySize(infile,ArrayLength(infile)+1);
        infile[ArrayLength(infile)-1] = ch;
    }
    fclose(f);
    //printf("Read %d bytes\n",ArrayLength(infile));
    unsigned char* outfile = ArrayAlloc(ArrayLength(infile)*101/100+600,1);
    int len = ArrayLength(outfile);
    if (doCompress) {
        int ret = BZ2_bzBuffToBuffCompress(outfile,&len,
                                           infile,ArrayLength(infile),9,0,30);
        if (ret != BZ_OK) {
            fprintf(stderr,"Error ");
            switch (ret) {
            case BZ_CONFIG_ERROR:
                fprintf(stderr,"BZ_CONFIG_ERROR\n");
                break;
            case BZ_PARAM_ERROR:
                fprintf(stderr,"BZ_PARAM_ERROR\n");
                break;
            case BZ_MEM_ERROR:
                fprintf(stderr,"BZ_MEM_ERROR\n");
                break;
            case BZ_OUTBUFF_FULL:
                fprintf(stderr,"BZ_OUTBUFF_FULL\n");
                break;
            default:
                fprintf(stderr,"UNKNOWN\n");
                break;
            }
        }
    } else {
        memcpy(outfile,infile,len=ArrayLength(infile));
    }
    //printf("Out %d bytes\n",len);
    fprintf(stderr,"%s: %d/%d=%.3f\n",argv[1],ArrayLength(infile),len,(float)ArrayLength(infile)/len);

    printf("int Y");
    int i;
    for (i=0; argv[1][i]; i++) {
        if (argv[1][i] == '.') {
            printf("_");
        } else {
            printf("%c",argv[1][i]);
        }
    }
    printf("_len=%d;\n",ArrayLength(infile));

    printf("int X");
    for (i=0; argv[1][i]; i++) {
        if (argv[1][i] == '.') {
            printf("_");
        } else {
            printf("%c",argv[1][i]);
        }
    }
    printf("_len=%d;\n",len);

    printf("char X");
    for (i=0; argv[1][i]; i++) {
        if (argv[1][i] == '.') {
            printf("_");
        } else {
            printf("%c",argv[1][i]);
        }
    }
    printf("[%d] = {",len);
    for (i=0; i<len; i++) {
        if (i % 8 == 0) printf("\n\t");
        printf("0x%02X",outfile[i]);
        if (i+1 < len) printf(",");
    }
    printf("\n};\n");
}
Exemplo n.º 28
0
Arquivo: bz2main.c Projeto: hww3/pexts
/*
 * This is the Gz module-compatible STRING compressor
 * Takes a string to compress and returns a compressed string.
 * Allows an optional INT argument for Gz.deflate compat, but
 * ignores it.
 *
 * It uses a very high-level libbz2 call for simplicity.
 */
static void
f_deflate_deflate(INT32 args)
{
    char               *dest;
    unsigned           dlen;
    struct pike_string *src;
    int                retval;
    struct pike_string *retstr;
    int                verbosity = 0;
    switch(args) {
     case 2:
      if(ARG(2).type != T_INT) {
	  Pike_error("bzip2.deflate->deflate(): argument 2 not an integer.\n");
      }
      verbosity = ARG(2).u.integer;
      if( verbosity > 4 || verbosity < 0 ) {
	Pike_error("bzip2.deflate->deflate(): verbosity should be between 0 and 4.\n");
      }
      /* FALLTHROUGH */

     case 1:
      if (ARG(1).type != T_STRING)
	  Pike_error("bzip2.deflate->deflate(): argument 1 must be a string.\n");
      if (!ARG(1).u.string->str || !ARG(1).u.string->len)
	  Pike_error("bzip2.deflate->deflate(): cannot compress an empty string!\n");
      src = ARG(1).u.string;
      break;
     default:
      Pike_error("bzip2.deflate->deflate(): expected  1 to 2 arguments.\n");
    }
    
    /*
     * We assume the worst case when the destination string doesn't compress
     * and will instead grow. The assumption is that it can grow by 1/3 of the
     * source string. We also add an extra 40 bytes since that is what the
     * minimum size seems to be.
     */
    dlen = (src->len << src->size_shift) + 1;
    dlen += dlen / 3 + 40;
    
destalloc: /* Yep, I know. goto's are ugly. But efficient. :P */
    dest = (char*)calloc(dlen, sizeof(char));
    if (!dest)
	Pike_error("bzip2.deflate->deflate(): out of memory (needed %u bytes)\n",
	      dlen);
	
#ifdef HAVE_OLD_LIBBZ2
    retval = bzBuffToBuffCompress(dest, &dlen, src->str,
				  src->len << src->size_shift,
				  THIS->blkSize, verbosity, 0);
#else
    retval = BZ2_bzBuffToBuffCompress(dest, &dlen, src->str,
				      src->len << src->size_shift,
				      THIS->blkSize, verbosity, 0);
#endif
    switch(retval) {
#ifdef BZ_CONFIG_ERROR
     case BZ_CONFIG_ERROR:
      Pike_error("bzip2.deflate->deflate(): your copy of libbz2 is seriously damaged!\n");
      break; /* never reached */
#endif	    
     case BZ_MEM_ERROR:
      Pike_error("bzip2.deflate->deflate(): out of memory compressing block.\n");
      break; /* never reached */
	    
     case BZ_OUTBUFF_FULL:
      if (dest)
	free(dest);
      dlen <<= 1;
      goto destalloc;
      break; /* never reached */
	    
     case BZ_OK:
      break;

     case BZ_PARAM_ERROR:
      Pike_error("bzip2.deflate->deflate(): Invalid parameters.\n");
      break;
      
     default:
      Pike_error("bzip2.deflate->deflate(): unknown error code %d\n", retval);
      break; /* never reached */
    }
    
    pop_n_elems(args);
    if (dest) {
	retstr = make_shared_binary_string(dest, dlen);
	free(dest);
	push_string(retstr);
    } else
	push_int(0);
}
Exemplo n.º 29
0
int Netchan_CreateFileFragments_(qboolean server, netchan_t *chan, const char *filename)
#endif // REHLDS_FIXES
{
	int chunksize;
	int compressedFileTime;
	FileHandle_t hfile;
	signed int filesize;
	int remaining;
	fragbufwaiting_t *p;
	int send;
	fragbuf_t *buf;
	char compressedfilename[MAX_PATH];
	qboolean firstfragment;
	int bufferid;
	qboolean bCompressed;
	int pos;
	fragbufwaiting_t *wait;
	int uncompressed_size;

	bufferid = 1;
	firstfragment = TRUE;
	bCompressed = FALSE;
	chunksize = chan->pfnNetchan_Blocksize(chan->connection_status);

	Q_snprintf(compressedfilename, sizeof compressedfilename, "%s.ztmp", filename);
	compressedFileTime = FS_GetFileTime(compressedfilename);
	if (compressedFileTime >= FS_GetFileTime(filename) && (hfile = FS_Open(compressedfilename, "rb")))
	{
		filesize = FS_Size(hfile);
		FS_Close(hfile);
		bCompressed = TRUE;
		hfile = FS_Open(filename, "rb");
		if (!hfile)
		{
			Con_Printf("Warning:  Unable to open %s for transfer\n", filename);
			return 0;
		}

		uncompressed_size = FS_Size(hfile);
		if (uncompressed_size > sv_filetransfermaxsize.value)
		{
			FS_Close(hfile);
			Con_Printf("Warning:  File %s is too big to transfer from host %s\n", filename, NET_AdrToString(chan->remote_address));
			return 0;
		}
	}
	else
	{
		hfile = FS_Open(filename, "rb");
		if (!hfile)
		{
			Con_Printf("Warning:  Unable to open %s for transfer\n", filename);
			return 0;
		}
		filesize = FS_Size(hfile);
		if (filesize > sv_filetransfermaxsize.value)
		{
			FS_Close(hfile);
			Con_Printf("Warning:  File %s is too big to transfer from host %s\n", filename, NET_AdrToString(chan->remote_address));
			return 0;
		}

		uncompressed_size = filesize;
		if (sv_filetransfercompression.value != 0.0)
		{
			unsigned char* uncompressed = (unsigned char*)Mem_Malloc(filesize);
			unsigned char* compressed = (unsigned char*)Mem_Malloc(filesize);
			unsigned int compressedSize = filesize;
			FS_Read(uncompressed, filesize, 1, hfile);
			if (BZ_OK == BZ2_bzBuffToBuffCompress((char*)compressed, &compressedSize, (char*)uncompressed, filesize, 9, 0, 30))
			{
				FileHandle_t destFile = FS_Open(compressedfilename, "wb");
				if (destFile)
				{
					Con_DPrintf("Creating compressed version of file %s (%d -> %d)\n", filename, filesize, compressedSize);
					FS_Write(compressed, compressedSize, 1, destFile);
					FS_Close(destFile);
					filesize = compressedSize;
					bCompressed = TRUE;
				}
			}
			Mem_Free(uncompressed);
			Mem_Free(compressed);
		}
	}
	FS_Close(hfile);

	wait = (fragbufwaiting_t *)Mem_ZeroMalloc(0xCu);
	remaining = filesize;
	pos = 0;

	while (remaining)
	{
		send = min(chunksize, remaining);
		buf = Netchan_AllocFragbuf();
		if (!buf)
		{
			Con_Printf("Couldn't allocate fragbuf_t\n");
			Mem_Free(wait);
			if (server)
			{
#ifdef REHLDS_FIXES
				SV_DropClient(&g_psvs.clients[chan->player_slot - 1], 0, "Malloc problem");
#else // REHLDS_FIXES
				SV_DropClient(host_client, 0, "Malloc problem");
#endif // REHLDS_FIXES
				return 0;
			}
			else
			{
				rehlds_syserror("%s: Reverse clientside code", __func__);
				//return 0;
			}
		}

		buf->bufferid = bufferid++;
		SZ_Clear(&buf->frag_message);
		if (firstfragment)
		{
			firstfragment = FALSE;
			MSG_WriteString(&buf->frag_message, filename);
			MSG_WriteString(&buf->frag_message, bCompressed ? "bz2" : "uncompressed");
			MSG_WriteLong(&buf->frag_message, uncompressed_size);
			send -= buf->frag_message.cursize;
		}
		buf->isfile = TRUE;
		buf->iscompressed = bCompressed;
		buf->size = send;
		buf->foffset = pos;

		Q_strncpy(buf->filename, filename, MAX_PATH - 1);
		buf->filename[MAX_PATH - 1] = 0;

		pos += send;
		remaining -= send;

		Netchan_AddFragbufToTail(wait, buf);
	}

	if (!chan->waitlist[FRAG_FILE_STREAM])
	{
		chan->waitlist[FRAG_FILE_STREAM] = wait;
	}
	else
	{
		p = chan->waitlist[FRAG_FILE_STREAM];
		while (p->next)
			p = p->next;

		p->next = wait;
	}

	return 1;
}
Exemplo n.º 30
0
bool DebugInfo::SendReplay()
{
    LOG.lprintf("Sending replay...\n");

    // Replay mode is on, no recording of replays active
    if (!GAMECLIENT.IsReplayModeOn())
    {
        Replay rpl = GAMECLIENT.GetReplay();

        if(!rpl.IsValid())
            return true;

        BinaryFile* f = rpl.GetFile();

        if(!f) // no replay to send
            return true;

        f->Flush();

        unsigned replay_len = f->Tell();

        LOG.lprintf("- Replay length: %u\n", replay_len);

        boost::interprocess::unique_ptr<char, Deleter<char[]> > replay(new char[replay_len]);

        f->Seek(0, SEEK_SET);

        f->ReadRawData(replay.get(), replay_len);

        unsigned int compressed_len = replay_len * 2 + 600;
        boost::interprocess::unique_ptr<char, Deleter<char[]> > compressed(new char[compressed_len]);

        // send size of replay via socket
        if (!SendString("Replay"))
        {
            return false;
        }

        LOG.lprintf("- Compressing...\n");
        if (BZ2_bzBuffToBuffCompress(compressed.get(), (unsigned int*) &compressed_len, replay.get(), replay_len, 9, 0, 250) == BZ_OK)
        {
            LOG.lprintf("- Sending...\n");

            if (SendString(compressed.get(), compressed_len))
            {
                LOG.lprintf("-> success\n");
                return true;
            }

            LOG.lprintf("-> Sending replay failed :(\n");
        }
        else
        {
            LOG.lprintf("-> BZ2 compression failed.\n");
        }

        SendUnsigned(0);
        return false;
    }
    else
    {
        LOG.lprintf("-> Already in replay mode, do not send replay\n");
    }

    return true;
}