Beispiel #1
0
bool DotNetDecodeWithInfo(MarshalledImage* image)
{
	opj_dparameters dparameters;
	opj_codestream_info_t info;
	
	try
	{
		opj_set_default_decoder_parameters(&dparameters);
		opj_dinfo_t* dinfo = opj_create_decompress(CODEC_J2K);
		opj_setup_decoder(dinfo, &dparameters);
		opj_cio* cio = opj_cio_open((opj_common_ptr)dinfo, image->encoded, image->length);

		opj_image* jp2_image = opj_decode_with_info(dinfo, cio, &info); // decode happens here
		if (jp2_image == NULL)
			throw "opj_decode failed";

		// maximum number of decompositions
		int max_numdecompos = 0;
		for (int compno = 0; compno < info.numcomps; compno++)
		{
			if (max_numdecompos < info.numdecompos[compno])
				max_numdecompos = info.numdecompos[compno];
		}

		image->width = jp2_image->x1 - jp2_image->x0;
		image->height = jp2_image->y1 - jp2_image->y0;
		image->layers = info.numlayers;
		image->resolutions = max_numdecompos + 1;
		image->components = info.numcomps;
		image->packet_count = info.packno;
		image->packets = info.tile->packet;
		int n = image->width * image->height;
		image->decoded = new unsigned char[n * image->components];
		
		for (int i = 0; i < image->components; i++)
			std::copy(jp2_image->comps[i].data, jp2_image->comps[i].data + n, image->decoded + i * n);

		opj_image_destroy(jp2_image);
		opj_destroy_decompress(dinfo);
		opj_cio_close(cio);

		return true;
	}
	catch (...)
	{
		return false;
	}
}
Beispiel #2
0
opj_image_t* OPJ_CALLCONV opj_decode(opj_dinfo_t *dinfo, opj_cio_t *cio) {
	return opj_decode_with_info(dinfo, cio, NULL);
}
Beispiel #3
0
static int libopenjpeg_decode_frame(AVCodecContext *avctx,
                                    void *data, int *data_size,
                                    AVPacket *avpkt)
{
    const uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    LibOpenJPEGContext *ctx = avctx->priv_data;
    AVFrame *picture = &ctx->image, *output = data;
    opj_dinfo_t *dec;
    opj_cio_t *stream;
    opj_image_t *image;
    int width, height, has_alpha = 0, ret = -1;
    int x, y, index;
    uint8_t *img_ptr;
    int adjust[4];

    *data_size = 0;

    // Check if input is a raw jpeg2k codestream or in jp2 wrapping
    if((AV_RB32(buf) == 12) &&
       (AV_RB32(buf + 4) == JP2_SIG_TYPE) &&
       (AV_RB32(buf + 8) == JP2_SIG_VALUE)) {
        dec = opj_create_decompress(CODEC_JP2);
    } else {
        // If the AVPacket contains a jp2c box, then skip to
        // the starting byte of the codestream.
        if (AV_RB32(buf + 4) == AV_RB32("jp2c"))
            buf += 8;
        dec = opj_create_decompress(CODEC_J2K);
    }

    if(!dec) {
        av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");
        return -1;
    }
    opj_set_event_mgr((opj_common_ptr)dec, NULL, NULL);

    ctx->dec_params.cp_reduce = avctx->lowres;
    // Tie decoder with decoding parameters
    opj_setup_decoder(dec, &ctx->dec_params);
    stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
    if(!stream) {
        av_log(avctx, AV_LOG_ERROR, "Codestream could not be opened for reading.\n");
        opj_destroy_decompress(dec);
        return -1;
    }

    // Decode the codestream
    image = opj_decode_with_info(dec, stream, NULL);
    opj_cio_close(stream);
    if(!image) {
        av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
        opj_destroy_decompress(dec);
        return -1;
    }
    width  = image->comps[0].w << avctx->lowres;
    height = image->comps[0].h << avctx->lowres;
    if(av_check_image_size(width, height, 0, avctx) < 0) {
        av_log(avctx, AV_LOG_ERROR, "%dx%d dimension invalid.\n", width, height);
        goto done;
    }
    avcodec_set_dimensions(avctx, width, height);

    switch(image->numcomps)
    {
        case 1:  avctx->pix_fmt = PIX_FMT_GRAY8;
                 break;
        case 3:  if(check_image_attributes(image)) {
                     avctx->pix_fmt = PIX_FMT_RGB24;
                 } else {
                     avctx->pix_fmt = PIX_FMT_GRAY8;
                     av_log(avctx, AV_LOG_ERROR, "Only first component will be used.\n");
                 }
                 break;
        case 4:  has_alpha = 1;
                 avctx->pix_fmt = PIX_FMT_RGBA;
                 break;
        default: av_log(avctx, AV_LOG_ERROR, "%d components unsupported.\n", image->numcomps);
                 goto done;
    }

    if(picture->data[0])
        avctx->release_buffer(avctx, picture);

    if(avctx->get_buffer(avctx, picture) < 0) {
        av_log(avctx, AV_LOG_ERROR, "Couldn't allocate image buffer.\n");
        return -1;
    }

    for(x = 0; x < image->numcomps; x++) {
        adjust[x] = FFMAX(image->comps[x].prec - 8, 0);
    }

    for(y = 0; y < avctx->height; y++) {
        index = y*avctx->width;
        img_ptr = picture->data[0] + y*picture->linesize[0];
        for(x = 0; x < avctx->width; x++, index++) {
            *img_ptr++ = image->comps[0].data[index] >> adjust[0];
            if(image->numcomps > 2 && check_image_attributes(image)) {
                *img_ptr++ = image->comps[1].data[index] >> adjust[1];
                *img_ptr++ = image->comps[2].data[index] >> adjust[2];
                if(has_alpha)
                    *img_ptr++ = image->comps[3].data[index] >> adjust[3];
            }
        }
    }
int main(int argc, char **argv) {
	opj_dparameters_t parameters;	/* decompression parameters */
	img_fol_t img_fol;
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *image = NULL;
	FILE *fsrc = NULL;
	unsigned char *src = NULL;
	int file_length;
	int num_images;
	int i,imageno;
	dircnt_t *dirptr = NULL;
	opj_dinfo_t* dinfo = NULL;	/* handle to a decompressor */
	opj_cio_t *cio = NULL;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */
	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = error_callback;
	event_mgr.warning_handler = warning_callback;
	event_mgr.info_handler = info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* Initialize indexfilename and img_fol */
	*indexfilename = 0;
	memset(&img_fol,0,sizeof(img_fol_t));

	/* parse input and get user encoding parameters */
	if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
		return 1;
	}

	/* Initialize reading of directory */
	if(img_fol.set_imgdir==1){	
		num_images=get_num_images(img_fol.imgdirpath);

		dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
		if(dirptr){
			dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));	/* Stores at max 10 image file names*/
			dirptr->filename = (char**) malloc(num_images*sizeof(char*));

			if(!dirptr->filename_buf){
				return 1;
			}
			for(i=0;i<num_images;i++){
				dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
			}
		}
		if(load_images(dirptr,img_fol.imgdirpath)==1){
			return 1;
		}
		if (num_images==0){
			fprintf(stdout,"Folder is empty\n");
			return 1;
		}
	}else{
		num_images=1;
	}

	/*Encoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)	{
		image = NULL;
		fprintf(stderr,"\n");

		if(img_fol.set_imgdir==1){
			if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
				fprintf(stderr,"skipping file...\n");
				continue;
			}
		}

		/* read the input file and put it in memory */
		/* ---------------------------------------- */
		fsrc = fopen(parameters.infile, "rb");
		if (!fsrc) {
			fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
			return 1;
		}
		fseek(fsrc, 0, SEEK_END);
		file_length = ftell(fsrc);
		fseek(fsrc, 0, SEEK_SET);
		src = (unsigned char *) malloc(file_length);
		if (fread(src, 1, file_length, fsrc) != (size_t)file_length)
		{
			free(src);
			fclose(fsrc);
			fprintf(stderr, "\nERROR: fread return a number of element different from the expected.\n");
			return 1;
		}
		fclose(fsrc);

		/* decode the code-stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
		case J2K_CFMT:
		{
			/* JPEG-2000 codestream */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_J2K);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				/* If need to extract codestream information*/
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				free(src);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				opj_bool bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JP2_CFMT:
		{
			/* JPEG 2000 compressed image data */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JP2);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using the current image and user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				/* If need to extract codestream information*/
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);			
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				free(src);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				opj_bool bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JPT_CFMT:
		{
			/* JPEG 2000, JPIP */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JPT);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				/* If need to extract codestream information*/
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				free(src);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				opj_bool bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		default:
			fprintf(stderr, "skipping file..\n");
			continue;
	}

		/* free the memory containing the code-stream */
		free(src);
		src = NULL;

	if(image->color_space == CLRSPC_SYCC)
   {
	color_sycc_to_rgb(image);
   }

	if(image->icc_profile_buf)
   {
#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
	color_apply_icc_profile(image);
#endif

	free(image->icc_profile_buf);
	image->icc_profile_buf = NULL; image->icc_profile_len = 0;
   }

		/* create output image */
		/* ------------------- */
		switch (parameters.cod_format) {
		case PXM_DFMT:			/* PNM PGM PPM */
			if (imagetopnm(image, parameters.outfile)) {
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case PGX_DFMT:			/* PGX */
			if(imagetopgx(image, parameters.outfile)){
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case BMP_DFMT:			/* BMP */
			if(imagetobmp(image, parameters.outfile)){
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef HAVE_LIBTIFF
		case TIF_DFMT:			/* TIFF */
			if(imagetotif(image, parameters.outfile)){
				fprintf(stdout,"Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* HAVE_LIBTIFF */
		case RAW_DFMT:			/* RAW */
			if(imagetoraw(image, parameters.outfile)){
				fprintf(stdout,"Error generating raw file. Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;

		case TGA_DFMT:			/* TGA */
			if(imagetotga(image, parameters.outfile)){
				fprintf(stdout,"Error generating tga file. Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef HAVE_LIBPNG
		case PNG_DFMT:			/* PNG */
			if(imagetopng(image, parameters.outfile)){
				fprintf(stdout,"Error generating png file. Outfile %s not generated\n",parameters.outfile);
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* HAVE_LIBPNG */
/* Can happen if output file is TIFF or PNG
 * and HAVE_LIBTIF or HAVE_LIBPNG is undefined
*/
			default:
				fprintf(stderr,"Outfile %s not generated\n",parameters.outfile);
		}

		/* free remaining structures */
		if(dinfo) {
			opj_destroy_decompress(dinfo);
		}
		/* free codestream information structure */
		if (*indexfilename)	
			opj_destroy_cstr_info(&cstr_info);
		/* free image data structure */
		opj_image_destroy(image);

	}
	return 0;
}
Beispiel #5
0
int main(int argc, char *argv[])
{
	opj_dparameters_t parameters;	/* decompression parameters */
	img_fol_t img_fol;
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *image = NULL;
	FILE *fsrc = NULL, *fout = NULL;
	unsigned char *src = NULL;
	int file_length;
	int num_images;
	int i,imageno;
	dircnt_t *dirptr = NULL;
	opj_dinfo_t* dinfo = NULL;	/* handle to a decompressor */
	opj_cio_t *cio = NULL;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */
	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = error_callback;
	event_mgr.warning_handler = warning_callback;
	event_mgr.info_handler = info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* Initialize indexfilename and img_fol */
	*indexfilename = 0;
	memset(&img_fol,0,sizeof(img_fol_t));

	/* parse input and get user encoding parameters */
	if(parse_cmdline_decoder(argc, argv, &parameters,&img_fol, indexfilename) == 1) {
		return 1;
	}

	/* Initialize reading of directory */
	if(img_fol.set_imgdir==1){	
		num_images=get_num_images(img_fol.imgdirpath);

		dirptr=(dircnt_t*)malloc(sizeof(dircnt_t));
		if(dirptr){
			dirptr->filename_buf = (char*)malloc(num_images*OPJ_PATH_LEN*sizeof(char));	/* Stores at max 10 image file names*/
			dirptr->filename = (char**) malloc(num_images*sizeof(char*));

			if(!dirptr->filename_buf){
				return 1;
			}
			for(i=0;i<num_images;i++){
				dirptr->filename[i] = dirptr->filename_buf + i*OPJ_PATH_LEN;
			}
		}
		if(load_images(dirptr,img_fol.imgdirpath)==1){
			return 1;
		}
		if (num_images==0){
			fprintf(stdout,"Folder is empty\n");
			return 1;
		}
	}else{
		num_images=1;
	}

	/* */
	if (parameters.outfile[0] != 0)
	  {
	  fout = fopen(parameters.outfile,"w");
    if (!fout)
      {
      fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.outfile);
      return 1;
      }
	  }
	else
	  fout = stdout;

	/*Encoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)
  {
		image = NULL;
		fprintf(stderr,"\n");

		if(img_fol.set_imgdir==1){
			if (get_next_file(imageno, dirptr,&img_fol, &parameters)) {
				fprintf(stderr,"skipping file...\n");
				continue;
			}
		}

		/* read the input file and put it in memory */
		/* ---------------------------------------- */
		fsrc = fopen(parameters.infile, "rb");
		if (!fsrc) {
			fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
			return 1;
		}
		fseek(fsrc, 0, SEEK_END);
		file_length = ftell(fsrc);
		fseek(fsrc, 0, SEEK_SET);
		src = (unsigned char *) malloc(file_length);
		if (fread(src, 1, file_length, fsrc) != (size_t)file_length)
		{
			free(src);
			fclose(fsrc);
			fclose(fout);
			fprintf(stderr, "\nERROR: fread return a number of element different from the expected.\n");
			return 1;
		}
		fclose(fsrc);

		/* decode the code-stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
		case J2K_CFMT:
		{
			/* JPEG-2000 codestream */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_J2K);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				/* If need to extract codestream information*/
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				fclose(fout);
				free(src);
				return 1;
			}
			/* dump image */
      j2k_dump_image(fout, image);

			/* dump cp */
      j2k_dump_cp(fout, image, ((opj_j2k_t*)dinfo->j2k_handle)->cp);

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				opj_bool bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JP2_CFMT:
		{
			/* JPEG 2000 compressed image data */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JP2);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using the current image and user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				/* If need to extract codestream information*/
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);			
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				fclose(fout);
				free(src);
				return 1;
			}
			/* dump image */
	  if(image->icc_profile_buf)
	 {
	  free(image->icc_profile_buf); image->icc_profile_buf = NULL;
	 }	
      j2k_dump_image(fout, image);

			/* dump cp */
      j2k_dump_cp(fout, image, ((opj_jp2_t*)dinfo->jp2_handle)->j2k->cp);

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				opj_bool bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		case JPT_CFMT:
		{
			/* JPEG 2000, JPIP */

			/* get a decoder handle */
			dinfo = opj_create_decompress(CODEC_JPT);

			/* catch events using our callbacks and give a local context */
			opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

			/* setup the decoder decoding parameters using user parameters */
			opj_setup_decoder(dinfo, &parameters);

			/* open a byte stream */
			cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);

			/* decode the stream and fill the image structure */
			if (*indexfilename)				/* If need to extract codestream information*/
				image = opj_decode_with_info(dinfo, cio, &cstr_info);
			else
				image = opj_decode(dinfo, cio);
			if(!image) {
				fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				fclose(fout);
				free(src);
				return 1;
			}

			/* close the byte stream */
			opj_cio_close(cio);

			/* Write the index to disk */
			if (*indexfilename) {
				opj_bool bSuccess;
				bSuccess = write_index_file(&cstr_info, indexfilename);
				if (bSuccess) {
					fprintf(stderr, "Failed to output index file\n");
				}
			}
		}
		break;

		default:
			fprintf(stderr, "skipping file..\n");
			continue;
	}

		/* free the memory containing the code-stream */
		free(src);
		src = NULL;

		/* free remaining structures */
		if(dinfo) {
			opj_destroy_decompress(dinfo);
		}
		/* free codestream information structure */
		if (*indexfilename)	
			opj_destroy_cstr_info(&cstr_info);
		/* free image data structure */
		opj_image_destroy(image);

	}

	fclose(fout);

  return EXIT_SUCCESS;
}
Beispiel #6
0
// load the jpeg2000 file format
bool wxJPEG2000Handler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)
{
	opj_dparameters_t parameters;	/* decompression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *opjimage = NULL;
	unsigned char *src = NULL;
    unsigned char *ptr;
	int file_length, jp2c_point, jp2h_point;
	unsigned long int jp2hboxlen, jp2cboxlen;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */
    unsigned char hdr[24];
	int jpfamform;

	// destroy the image
    image->Destroy();

	/* read the beginning of the file to check the type */ 
    if (!stream.Read(hdr, WXSIZEOF(hdr)))
        return false;
	if ((jpfamform = jpeg2000familytype(hdr, WXSIZEOF(hdr))) < 0)
		return false;
	stream.SeekI(0, wxFromStart);

	/* handle to a decompressor */
	opj_dinfo_t* dinfo = NULL;	
	opj_cio_t *cio = NULL;

	/* configure the event callbacks */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = jpeg2000_error_callback;
	event_mgr.warning_handler = jpeg2000_warning_callback;
	event_mgr.info_handler = jpeg2000_info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* prepare parameters */
	strncpy(parameters.infile, "", sizeof(parameters.infile) - 1);
	strncpy(parameters.outfile, "", sizeof(parameters.outfile) - 1);
	parameters.decod_format = jpfamform;
	parameters.cod_format = BMP_DFMT;
	if (m_reducefactor)
		parameters.cp_reduce = m_reducefactor;
	if (m_qualitylayers)
		parameters.cp_layer = m_qualitylayers;
	/*if (n_components)
		parameters. = n_components;*/

	/* JPWL only */
#ifdef USE_JPWL
	parameters.jpwl_exp_comps = m_expcomps;
	parameters.jpwl_max_tiles = m_maxtiles;
	parameters.jpwl_correct = m_enablejpwl;
#endif /* USE_JPWL */

	/* get a decoder handle */
	if (jpfamform == JP2_CFMT || jpfamform == MJ2_CFMT)
		dinfo = opj_create_decompress(CODEC_JP2);
	else if (jpfamform == J2K_CFMT)
		dinfo = opj_create_decompress(CODEC_J2K);
	else
		return false;

	/* find length of the stream */
	stream.SeekI(0, wxFromEnd);
	file_length = (int) stream.TellI();

	/* it's a movie */
	if (jpfamform == MJ2_CFMT) {
		/* search for the first codestream box and the movie header box  */
		jp2c_point = searchjpeg2000c(stream, file_length, m_framenum);
		jp2h_point = searchjpeg2000headerbox(stream, file_length);

		// read the jp2h box and store it
		stream.SeekI(jp2h_point, wxFromStart);
		stream.Read(&jp2hboxlen, sizeof(unsigned long int));
		jp2hboxlen = BYTE_SWAP4(jp2hboxlen);

		// read the jp2c box and store it
		stream.SeekI(jp2c_point, wxFromStart);
		stream.Read(&jp2cboxlen, sizeof(unsigned long int));
		jp2cboxlen = BYTE_SWAP4(jp2cboxlen);

		// malloc memory source
		src = (unsigned char *) malloc(jpeg2000headSIZE + jp2hboxlen + jp2cboxlen);

		// copy the jP and ftyp
		memcpy(src, jpeg2000head, jpeg2000headSIZE);

		// copy the jp2h
		stream.SeekI(jp2h_point, wxFromStart);
		stream.Read(&src[jpeg2000headSIZE], jp2hboxlen);

		// copy the jp2c
		stream.SeekI(jp2c_point, wxFromStart);
		stream.Read(&src[jpeg2000headSIZE + jp2hboxlen], jp2cboxlen);
	} else 	if (jpfamform == JP2_CFMT || jpfamform == J2K_CFMT) {
		/* It's a plain image */
		/* get data */
		stream.SeekI(0, wxFromStart);
		src = (unsigned char *) malloc(file_length);
		stream.Read(src, file_length);
	} else
		return false;

	/* catch events using our callbacks and give a local context */
	opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

	/* setup the decoder decoding parameters using user parameters */
	opj_setup_decoder(dinfo, &parameters);

	/* open a byte stream */
	if (jpfamform == MJ2_CFMT)
		cio = opj_cio_open((opj_common_ptr)dinfo, src, jpeg2000headSIZE + jp2hboxlen + jp2cboxlen);
	else if (jpfamform == JP2_CFMT || jpfamform == J2K_CFMT)
		cio = opj_cio_open((opj_common_ptr)dinfo, src, file_length);
	else {
		free(src);
		return false;
	}

	/* decode the stream and fill the image structure */
	opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);
	if (!opjimage) {
		wxMutexGuiEnter();
		wxLogError(wxT("JPEG 2000 failed to decode image!"));
		wxMutexGuiLeave();
		opj_destroy_decompress(dinfo);
		opj_cio_close(cio);
		free(src);
		return false;
	}

	/* close the byte stream */
	opj_cio_close(cio);

	/*

	- At this point, we have the structure "opjimage" that is filled with decompressed
	  data, as processed by the OpenJPEG decompression engine

	- We need to fill the class "image" with the proper pixel sample values

	*/
	{
		int shiftbpp;
		int c, tempcomps;

		// check components number
		if (m_components > opjimage->numcomps)
			m_components = opjimage->numcomps;

		// check image depth (only on the first one, for now)
		if (m_components)
			shiftbpp = opjimage->comps[m_components - 1].prec - 8;
		else
			shiftbpp = opjimage->comps[0].prec - 8;

		// prepare image size
		if (m_components)
			image->Create(opjimage->comps[m_components - 1].w, opjimage->comps[m_components - 1].h, true);
		else
			image->Create(opjimage->comps[0].w, opjimage->comps[0].h, true);

		// access image raw data
		image->SetMask(false);
		ptr = image->GetData();

		// workaround for components different from 1 or 3
		if ((opjimage->numcomps != 1) && (opjimage->numcomps != 3)) {
#ifndef __WXGTK__ 
			wxMutexGuiEnter();
#endif /* __WXGTK__ */
			wxLogMessage(wxT("JPEG2000: weird number of components"));
#ifndef __WXGTK__ 
			wxMutexGuiLeave();
#endif /* __WXGTK__ */
			tempcomps = 1;
		} else
			tempcomps = opjimage->numcomps;

		// workaround for subsampled components
		for (c = 1; c < tempcomps; c++) {
			if ((opjimage->comps[c].w != opjimage->comps[c - 1].w) || (opjimage->comps[c].h != opjimage->comps[c - 1].h)) {
				tempcomps = 1;
				break;
			}
		}

		// workaround for different precision components
		for (c = 1; c < tempcomps; c++) {
			if (opjimage->comps[c].bpp != opjimage->comps[c - 1].bpp) {
				tempcomps = 1;
				break;
			}
		}

		// only one component selected
		if (m_components)
			tempcomps = 1;

		// RGB color picture
		if (tempcomps == 3) {
			int row, col;
			int *r = opjimage->comps[0].data;
			int *g = opjimage->comps[1].data;
			int *b = opjimage->comps[2].data;
			if (shiftbpp > 0) {
				for (row = 0; row < opjimage->comps[0].h; row++) {
					for (col = 0; col < opjimage->comps[0].w; col++) {
						
						*(ptr++) = (*(r++)) >> shiftbpp;
						*(ptr++) = (*(g++)) >> shiftbpp;
						*(ptr++) = (*(b++)) >> shiftbpp;

					}
				}

			} else if (shiftbpp < 0) {
				for (row = 0; row < opjimage->comps[0].h; row++) {
					for (col = 0; col < opjimage->comps[0].w; col++) {
						
						*(ptr++) = (*(r++)) << -shiftbpp;
						*(ptr++) = (*(g++)) << -shiftbpp;
						*(ptr++) = (*(b++)) << -shiftbpp;

					}
				}
				
			} else {
				for (row = 0; row < opjimage->comps[0].h; row++) {
					for (col = 0; col < opjimage->comps[0].w; col++) {

						*(ptr++) = *(r++);
						*(ptr++) = *(g++);
						*(ptr++) = *(b++);
					
					}
				}
			}
		}
BOOL LLImageJ2COJ::decodeImpl(LLImageJ2C &base, LLImageRaw &raw_image, F32 decode_time, S32 first_channel, S32 max_channel_count)
{
	raw_image.decodedComment = LLImageMetaDataReader::ExtractKDUUploadComment(base.getData(), base.getDataSize());

	LLTimer decode_timer;

	opj_dparameters_t parameters;	/* decompression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *image = NULL;

	opj_dinfo_t* dinfo = NULL;	/* handle to a decompressor */
	opj_cio_t *cio = NULL;


	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = error_callback;
	event_mgr.warning_handler = warning_callback;
	event_mgr.info_handler = info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	parameters.cp_reduce = base.getRawDiscardLevel();

	/* decode the code-stream */
	/* ---------------------- */

	/* JPEG-2000 codestream */

	/* get a decoder handle */
	dinfo = opj_create_decompress(CODEC_J2K);

	/* catch events using our callbacks and give a local context */
	opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);			

	/* setup the decoder decoding parameters using user parameters */
	opj_setup_decoder(dinfo, &parameters);

	/* open a byte stream */
	cio = opj_cio_open((opj_common_ptr)dinfo, base.getData(), base.getDataSize());

	/* decode the stream and fill the image structure.
	   Also fill in an additional structur to get the decoding result.
	   This structure is a bit unusual in that it is not received through
	   opj, but still has somt dynamically allocated fields that need to
	   be cleared up at the end by calling a destroy function. */
	opj_codestream_info_t cinfo;
	memset(&cinfo, 0, sizeof(opj_codestream_info_t));
	image = opj_decode_with_info(dinfo, cio, &cinfo);

	/* close the byte stream */
	opj_cio_close(cio);

	/* free remaining structures */
	if(dinfo)
	{
		opj_destroy_decompress(dinfo);
	}

	// The image decode failed if the return was NULL or the component
	// count was zero.  The latter is just a sanity check before we
	// dereference the array.
	if(!image) 
	{
		LL_WARNS ("Openjpeg")  << "Failed to decode image at discard: " << (S32)base.getRawDiscardLevel() << ". No image." << LL_ENDL;
		if (base.getRawDiscardLevel() == 0)
		{
			base.decodeFailed();
		}
		return TRUE; // done
	}

	S32 img_components = image->numcomps;

	if( !img_components ) // < 1 ||img_components > 4 )
	{
		LL_WARNS("Openjpeg") << "Failed to decode image at discard: " << (S32)base.getRawDiscardLevel() << ". Wrong number of components: " << img_components << LL_ENDL;
		if (image)
		{
			opj_destroy_cstr_info(&cinfo);
			opj_image_destroy(image);
		}
		if (base.getRawDiscardLevel() == 0)
		{
			base.decodeFailed();
		}
		return TRUE; // done
	}

	// sometimes we get bad data out of the cache - check to see if the decode succeeded
	int decompdifference = 0;
	if (cinfo.numdecompos) // sanity
	{
		for (int comp = 0; comp < image->numcomps; comp++)
		{	
			/* get maximum decomposition level difference, first
			   field is from the COD header and the second
			   is what is actually met in the codestream, NB: if
			   everything was ok, this calculation will return
			   what was set in the cp_reduce value! */
			decompdifference = llmax(decompdifference, cinfo.numdecompos[comp] - image->comps[comp].resno_decoded);
		}
		if (decompdifference < 0) // sanity
		{
			decompdifference = 0;
		}
	}
	

	/* if OpenJPEG failed to decode all requested decomposition levels
	   the difference will be greater than this level */
	if (decompdifference > base.getRawDiscardLevel())
	{
		LL_WARNS("Openjpeg") << "Not enough data for requested discard level " << (S32)base.getRawDiscardLevel() << ", difference: " << (decompdifference - base.getRawDiscardLevel()) << llendl;
		opj_destroy_cstr_info(&cinfo);
		opj_image_destroy(image);
		if (base.getRawDiscardLevel() == 0)
		{
			base.decodeFailed();
		}
		return TRUE;
	}

	if(img_components <= first_channel)
	{
		LL_WARNS("Openjpeg") << "Trying to decode more channels than are present in image, numcomps: " << img_components << " first_channel: " << first_channel << LL_ENDL;
		if (image)
		{
			opj_destroy_cstr_info(&cinfo);
			opj_image_destroy(image);
		}
		if (base.getRawDiscardLevel() == 0)
		{
			base.decodeFailed();
		}
		return TRUE;
	}

	// Copy image data into our raw image format (instead of the separate channel format


	S32 channels = img_components - first_channel;
	if( channels > max_channel_count )
		channels = max_channel_count;

	// Component buffers are allocated in an image width by height buffer.
	// The image placed in that buffer is ceil(width/2^factor) by
	// ceil(height/2^factor) and if the factor isn't zero it will be at the
	// top left of the buffer with black filled in the rest of the pixels.
	// It is integer math so the formula is written in ceildivpo2.
	// (Assuming all the components have the same width, height and
	// factor.)
	S32 comp_width = image->comps[0].w;
	S32 f=image->comps[0].factor;
	S32 width = ceildivpow2(image->x1 - image->x0, f);
	S32 height = ceildivpow2(image->y1 - image->y0, f);
	raw_image.resize(width, height, channels);
	U8 *rawp = raw_image.getData();

	// first_channel is what channel to start copying from
	// dest is what channel to copy to.  first_channel comes from the
	// argument, dest always starts writing at channel zero.
	for (S32 comp = first_channel, dest=0; comp < first_channel + channels;
		comp++, dest++)
	{
		if (image->comps[comp].data)
		{
			S32 offset = dest;
			for (S32 y = (height - 1); y >= 0; y--)
			{
				for (S32 x = 0; x < width; x++)
				{
					rawp[offset] = image->comps[comp].data[y*comp_width + x];
					offset += channels;
				}
			}
		}
		else // Some rare OpenJPEG versions have this bug.
		{
			LL_WARNS("Openjpeg") << "Failed to decode image! (NULL comp data - OpenJPEG bug)" << LL_ENDL;
			opj_destroy_cstr_info(&cinfo);
			opj_image_destroy(image);

			if (base.getRawDiscardLevel() == 0)
			{
				base.decodeFailed();
			}
			return TRUE; // done
		}
	}

	/* free opj data structures */
	if (image)
	{
		opj_destroy_cstr_info(&cinfo);
		opj_image_destroy(image);
	}
	
	return TRUE; // done
}
static int libopenjpeg_decode_frame(AVCodecContext *avctx,
                                    void *data, int *data_size,
                                    AVPacket *avpkt)
{
    uint8_t *buf = avpkt->data;
    int buf_size = avpkt->size;
    LibOpenJPEGContext *ctx = avctx->priv_data;
    AVFrame *picture = &ctx->image, *output = data;
    opj_dinfo_t *dec;
    opj_cio_t *stream;
    opj_image_t *image;
    int width, height, ret = -1;
    int pixel_size = 0;
    int ispacked = 0;

    *data_size = 0;

    // Check if input is a raw jpeg2k codestream or in jp2 wrapping
    if((AV_RB32(buf) == 12) &&
       (AV_RB32(buf + 4) == JP2_SIG_TYPE) &&
       (AV_RB32(buf + 8) == JP2_SIG_VALUE)) {
        dec = opj_create_decompress(CODEC_JP2);
    } else {
        // If the AVPacket contains a jp2c box, then skip to
        // the starting byte of the codestream.
        if (AV_RB32(buf + 4) == AV_RB32("jp2c"))
            buf += 8;
        dec = opj_create_decompress(CODEC_J2K);
    }

    if(!dec) {
        av_log(avctx, AV_LOG_ERROR, "Error initializing decoder.\n");
        return -1;
    }
    opj_set_event_mgr((opj_common_ptr)dec, NULL, NULL);

    ctx->dec_params.cp_limit_decoding = LIMIT_TO_MAIN_HEADER;
    // Tie decoder with decoding parameters
    opj_setup_decoder(dec, &ctx->dec_params);
    stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
    if(!stream) {
        av_log(avctx, AV_LOG_ERROR, "Codestream could not be opened for reading.\n");
        opj_destroy_decompress(dec);
        return -1;
    }

    // Decode the header only
    image = opj_decode_with_info(dec, stream, NULL);
    opj_cio_close(stream);
    if(!image) {
        av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
        opj_destroy_decompress(dec);
        return -1;
    }
    width  = image->x1 - image->x0;
    height = image->y1 - image->y0;
    if(av_image_check_size(width, height, 0, avctx) < 0) {
        av_log(avctx, AV_LOG_ERROR, "%dx%d dimension invalid.\n", width, height);
        goto done;
    }
    avcodec_set_dimensions(avctx, width, height);

    if (avctx->pix_fmt != PIX_FMT_NONE) {
        if (!libopenjpeg_matches_pix_fmt(image, avctx->pix_fmt)) {
            avctx->pix_fmt = PIX_FMT_NONE;
        }
    }

    if (avctx->pix_fmt == PIX_FMT_NONE) {
        avctx->pix_fmt = libopenjpeg_guess_pix_fmt(image);
    }

    if (avctx->pix_fmt == PIX_FMT_NONE) {
        av_log(avctx, AV_LOG_ERROR, "Unable to determine pixel format\n");
        goto done;
    }

    if(picture->data[0])
        ff_thread_release_buffer(avctx, picture);

    if(ff_thread_get_buffer(avctx, picture) < 0){
        av_log(avctx, AV_LOG_ERROR, "ff_thread_get_buffer() failed\n");
        goto done;
    }

    ctx->dec_params.cp_limit_decoding = NO_LIMITATION;
    ctx->dec_params.cp_reduce = avctx->lowres;
    // Tie decoder with decoding parameters
    opj_setup_decoder(dec, &ctx->dec_params);
    stream = opj_cio_open((opj_common_ptr)dec, buf, buf_size);
    if(!stream) {
        av_log(avctx, AV_LOG_ERROR, "Codestream could not be opened for reading.\n");
        goto done;
    }

    opj_image_destroy(image);
    // Decode the codestream
    image = opj_decode_with_info(dec, stream, NULL);
    opj_cio_close(stream);
    if(!image) {
        av_log(avctx, AV_LOG_ERROR, "Error decoding codestream.\n");
        goto done;
    }

    pixel_size = av_pix_fmt_descriptors[avctx->pix_fmt].comp[0].step_minus1 + 1;
    ispacked = libopenjpeg_ispacked(avctx->pix_fmt);

    switch (pixel_size) {
    case 1:
        if (ispacked) {
            libopenjpeg_copy_to_packed8(picture, image);
        } else {
            libopenjpeg_copyto8(picture, image);
        }
        break;
    case 2:
        if (ispacked) {
            libopenjpeg_copy_to_packed8(picture, image);
        } else {
            libopenjpeg_copyto16(picture, image);
        }
        break;
    case 3:
    case 4:
        if (ispacked) {
            libopenjpeg_copy_to_packed8(picture, image);
        }
        break;
    case 6:
    case 8:
        if (ispacked) {
            libopenjpeg_copy_to_packed16(picture, image);
        }
        break;
    default:
        av_log(avctx, AV_LOG_ERROR, "unsupported pixel size %d\n", pixel_size);
        goto done;
    }

    *output    = ctx->image;
    *data_size = sizeof(AVPicture);
    ret = buf_size;

done:
    opj_image_destroy(image);
    opj_destroy_decompress(dec);
    return ret;
}
Beispiel #9
0
    void OpenJpegDecoder::PerformDecode(DecodeRequestPtr request)
    {
        if (!request)
            return;

        DecodeResultPtr result(new DecodeResult());

        result->id_ = request->id_;
        result->level_ = -1; // no level decoded yet
        result->max_levels_ = 5;
        result->original_width_ = 0;
        result->original_height_ = 0;
        result->components_ = 0;
        result->tag_ = request->tag_;

        // Guard against OpenJpeg crash on illegal data at an early phase
        unsigned char *data = (unsigned char *)request->source_->GetData();
        if (data[0] != 0xFF)
        {
            TextureDecoderModule::LogError("Invalid data passed to PerformDecode!");
            QueueResult<DecodeResult>(result);
            return;
        }

        opj_dinfo_t* dinfo = 0; // decoder
        opj_image_t *image = 0; // decoded image
        opj_dparameters_t parameters; // decoder parameters
        opj_cio_t *cio = 0; // decode stream
        opj_codestream_info_t cstr_info;  // codestream info
        memset(&cstr_info, 0, sizeof(opj_codestream_info_t));
       
        opj_event_mgr_t event_mgr; // decode event manager
        memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
        event_mgr.error_handler = HandleError;
        //event_mgr.warning_handler = HandleWarning;
        //event_mgr.info_handler = HandleInfo;
        
        opj_set_default_decoder_parameters(&parameters);
        parameters.cp_reduce = request->level_;
        
        dinfo = opj_create_decompress(CODEC_J2K);
        opj_setup_decoder(dinfo, &parameters);
        opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, this);
        
        cio = opj_cio_open((opj_common_ptr)dinfo, (unsigned char *)request->source_->GetData(), request->source_->GetSize());
        
        image = opj_decode_with_info(dinfo, cio, &cstr_info);
        result->max_levels_ = cstr_info.numlayers;

        opj_cio_close(cio);
        opj_destroy_decompress(dinfo);
        
        if ((image) && (image->numcomps))
        {
            result->original_width_ = image->x1 - image->x0;
            result->original_height_ = image->y1 - image->y0;
            result->components_ = image->numcomps;
            result->level_ = request->level_;

            // Assume all components are same size
            int actual_width = image->comps[0].w;
            int actual_height = image->comps[0].h;

            // Create a (possibly temporary, if no-one stores the pointer) raw texture resource
            Foundation::ResourcePtr resource(new TextureResource(request->source_->GetId(), actual_width, actual_height, image->numcomps));
            TextureResource* texture = checked_static_cast<TextureResource*>(resource.get());
            u8* data = texture->GetData();
            texture->SetLevel(request->level_);
            for (int y = 0; y < actual_height; ++y)
            {
                for (int x = 0; x < actual_width; ++x)
                {
                    for (int c = 0; c < image->numcomps; ++c)
                    {
                        *data = image->comps[c].data[y * actual_width + x];
                        data++;
                    }
                }
            }
     
            result->texture_ = resource;
        }

        if (image)
            opj_image_destroy(image);

        QueueResult<DecodeResult>(result);
    }
Beispiel #10
0
static GF_Err JP2_ProcessData(GF_MediaDecoder *ifcg, 
							  char *inBuffer, u32 inBufferLength,
							  u16 ES_ID,
							  char *outBuffer, u32 *outBufferLength,
							  u8 PaddingBits, u32 mmlevel)
{
	u32 i, w, wr, h, hr, wh;
	opj_dparameters_t parameters;	/* decompression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_dinfo_t* dinfo = NULL;	/* handle to a decompressor */
	opj_cio_t *cio = NULL;
	opj_codestream_info_t cinfo;

	JP2CTX();

#if 1
	switch (mmlevel) {
	case GF_CODEC_LEVEL_SEEK:
	case GF_CODEC_LEVEL_DROP:
		*outBufferLength = 0;
		return GF_OK;
	}
#endif

	if (!ctx->image) {
		/* configure the event callbacks (not required) */
		memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
		event_mgr.error_handler = error_callback;
		event_mgr.warning_handler = warning_callback;
		event_mgr.info_handler = info_callback;

		/* set decoding parameters to default values */
		opj_set_default_decoder_parameters(&parameters);

		/* get a decoder handle */
		dinfo = opj_create_decompress(CODEC_JP2);

		/* catch events using our callbacks and give a local context */
		opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

		/* setup the decoder decoding parameters using the current image and user parameters */
		opj_setup_decoder(dinfo, &parameters);


		/* open a byte stream */
		if (ctx->dsi) {
			char *data;

			data = gf_malloc(sizeof(char) * (ctx->dsi_size+inBufferLength));
			memcpy(data, ctx->dsi, ctx->dsi_size);
			memcpy(data+ctx->dsi_size, inBuffer, inBufferLength);
			cio = opj_cio_open((opj_common_ptr)dinfo, data, ctx->dsi_size+inBufferLength);
			/* decode the stream and fill the image structure */
			ctx->image = opj_decode(dinfo, cio);
			gf_free(data);
		} else {
			cio = opj_cio_open((opj_common_ptr)dinfo, inBuffer, inBufferLength);
			/* decode the stream and fill the image structure */
			ctx->image = opj_decode_with_info(dinfo, cio, &cinfo);
		}

		//Fill the ctx info because dsi was not present
		if (ctx->image) {
			ctx->nb_comp = cinfo.numcomps;
			ctx->width = cinfo.image_w;
			ctx->height = cinfo.image_h;
			ctx->bpp = ctx->nb_comp * 8;
			ctx->out_size = ctx->width * ctx->height * ctx->nb_comp /* * ctx->bpp / 8 */;

			switch (ctx->nb_comp) {
			case 1: ctx->pixel_format = GF_PIXEL_GREYSCALE; break;
			case 2: ctx->pixel_format = GF_PIXEL_ALPHAGREY; break;
			case 3: ctx->pixel_format = GF_PIXEL_RGB_24; break;
			case 4: ctx->pixel_format = GF_PIXEL_RGBA; break;
			default: return GF_NOT_SUPPORTED;
			}

			if ( *outBufferLength < ctx->out_size ) {
				*outBufferLength = ctx->out_size;
				opj_destroy_decompress(dinfo);
				opj_cio_close(cio);
				return GF_BUFFER_TOO_SMALL;
			}
		}

		if(!ctx->image) {
			opj_destroy_decompress(dinfo);
			opj_cio_close(cio);
			return GF_IO_ERR;
		}

		/* close the byte stream */
		opj_cio_close(cio);
		cio = NULL;

		/* gf_free( remaining structures */
		if(dinfo) {
			opj_destroy_decompress(dinfo);
			dinfo = NULL;
		}
	}

	w = ctx->image->comps[0].w;
	wr = int_ceildivpow2(ctx->image->comps[0].w, ctx->image->comps[0].factor);
	h = ctx->image->comps[0].h;
	hr = int_ceildivpow2(ctx->image->comps[0].h, ctx->image->comps[0].factor);
	wh = wr*hr;

	if (ctx->nb_comp==1) {
		if ((w==wr) && (h==hr)) {
			for (i=0; i<wh; i++) {
				outBuffer[i] = ctx->image->comps[0].data[i];
			}
		} else {
			for (i=0; i<wh; i++) {
				outBuffer[i] = ctx->image->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
			}
		}
	}
	else if (ctx->nb_comp==3) {

		if ((ctx->image->comps[0].w==2*ctx->image->comps[1].w) && (ctx->image->comps[1].w==ctx->image->comps[2].w)
			&& (ctx->image->comps[0].h==2*ctx->image->comps[1].h) && (ctx->image->comps[1].h==ctx->image->comps[2].h)) {

				if (ctx->pixel_format != GF_PIXEL_YV12) {
					ctx->pixel_format = GF_PIXEL_YV12;
					ctx->out_size = 3*ctx->width*ctx->height/2;
					*outBufferLength = ctx->out_size;
					return GF_BUFFER_TOO_SMALL;
				}

				if ((w==wr) && (h==hr)) {
					for (i=0; i<wh; i++) {
						*outBuffer = ctx->image->comps[0].data[i];
						outBuffer++;
					}
					w = ctx->image->comps[1].w;
					wr = int_ceildivpow2(ctx->image->comps[1].w, ctx->image->comps[1].factor);
					h = ctx->image->comps[1].h;
					hr = int_ceildivpow2(ctx->image->comps[1].h, ctx->image->comps[1].factor);
					wh = wr*hr;
					for (i=0; i<wh; i++) {
						*outBuffer = ctx->image->comps[1].data[i];
						outBuffer++;
					}
					for (i=0; i<wh; i++) {
						*outBuffer = ctx->image->comps[2].data[i];
						outBuffer++;
					}
				} else {
					for (i=0; i<wh; i++) {
						*outBuffer = ctx->image->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
					}
					w = ctx->image->comps[1].w;
					wr = int_ceildivpow2(ctx->image->comps[1].w, ctx->image->comps[1].factor);
					h = ctx->image->comps[1].h;
					hr = int_ceildivpow2(ctx->image->comps[1].h, ctx->image->comps[1].factor);
					wh = wr*hr;
					for (i=0; i<wh; i++) {
						*outBuffer = ctx->image->comps[1].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
					}
					for (i=0; i<wh; i++) {
						*outBuffer = ctx->image->comps[2].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
					}
				}


		} else if ((ctx->image->comps[0].w==ctx->image->comps[1].w) && (ctx->image->comps[1].w==ctx->image->comps[2].w)
			&& (ctx->image->comps[0].h==ctx->image->comps[1].h) && (ctx->image->comps[1].h==ctx->image->comps[2].h)) {

				if ((w==wr) && (h==hr)) {
					for (i=0; i<wh; i++) {
						u32 idx = 3*i;
						outBuffer[idx] = ctx->image->comps[0].data[i];
						outBuffer[idx+1] = ctx->image->comps[1].data[i];
						outBuffer[idx+2] = ctx->image->comps[2].data[i];
					}
				} else {
					for (i=0; i<wh; i++) {
						u32 idx = 3*i;
						outBuffer[idx] = ctx->image->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
						outBuffer[idx+1] = ctx->image->comps[1].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
						outBuffer[idx+2] = ctx->image->comps[2].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
					}
				}
		}
	}
	else if (ctx->nb_comp==4) {
		if ((ctx->image->comps[0].w==ctx->image->comps[1].w) && (ctx->image->comps[1].w==ctx->image->comps[2].w) && (ctx->image->comps[2].w==ctx->image->comps[3].w)
			&& (ctx->image->comps[0].h==ctx->image->comps[1].h) && (ctx->image->comps[1].h==ctx->image->comps[2].h) && (ctx->image->comps[2].h==ctx->image->comps[3].h)) {

				if ((w==wr) && (h==hr)) {
					for (i=0; i<wh; i++) {
						u32 idx = 4*i;
						outBuffer[idx] = ctx->image->comps[0].data[i];
						outBuffer[idx+1] = ctx->image->comps[1].data[i];
						outBuffer[idx+2] = ctx->image->comps[2].data[i];
						outBuffer[idx+3] = ctx->image->comps[3].data[i];
					}
				} else {
					for (i=0; i<wh; i++) {
						u32 idx = 4*i;
						outBuffer[idx] = ctx->image->comps[0].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
						outBuffer[idx+1] = ctx->image->comps[1].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
						outBuffer[idx+2] = ctx->image->comps[2].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
						outBuffer[idx+3] = ctx->image->comps[3].data[w * hr - ((i) / (wr) + 1) * w + (i) % (wr)];
					}
				}
		}
	}	

	/* gf_free( image data structure */
	if (ctx->image) {
		opj_image_destroy(ctx->image);
		ctx->image = NULL;
	}

	*outBufferLength = ctx->out_size;
	return GF_OK;
}
// load the mxf file format
bool wxMXFHandler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)
{
	opj_dparameters_t parameters;	/* decompression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *opjimage = NULL;
	unsigned char *src = NULL;
    unsigned char *ptr;
	int file_length, j2k_point, j2k_len;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */

	// destroy the image
    image->Destroy();

	/* handle to a decompressor */
	opj_dinfo_t* dinfo = NULL;	
	opj_cio_t *cio = NULL;

	/* configure the event callbacks (not required) */
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = mxf_error_callback;
	event_mgr.warning_handler = mxf_warning_callback;
	event_mgr.info_handler = mxf_info_callback;

	/* set decoding parameters to default values */
	opj_set_default_decoder_parameters(&parameters);

	/* prepare parameters */
	strncpy(parameters.infile, "", sizeof(parameters.infile)-1);
	strncpy(parameters.outfile, "", sizeof(parameters.outfile)-1);
	parameters.decod_format = J2K_CFMT;
	parameters.cod_format = BMP_DFMT;
	if (m_reducefactor)
		parameters.cp_reduce = m_reducefactor;
	if (m_qualitylayers)
		parameters.cp_layer = m_qualitylayers;
	/*if (n_components)
		parameters. = n_components;*/

	/* JPWL only */
#ifdef USE_JPWL
	parameters.jpwl_exp_comps = m_expcomps;
	parameters.jpwl_max_tiles = m_maxtiles;
	parameters.jpwl_correct = m_enablejpwl;
#endif /* USE_JPWL */

	/* get a decoder handle */
	dinfo = opj_create_decompress(CODEC_J2K);

	/* find length of the stream */
	stream.SeekI(0, wxFromEnd);
	file_length = (int) stream.TellI();

	/* search for the m_framenum codestream position and length  */
	//jp2c_point = searchjp2c(stream, file_length, m_framenum);
	//jp2c_len = searchjp2c(stream, file_length, m_framenum);
	j2k_point = 0;
	j2k_len = 10;

	// malloc memory source
    src = (unsigned char *) malloc(j2k_len);

	// copy the jp2c
	stream.SeekI(j2k_point, wxFromStart);
	stream.Read(src, j2k_len);

	/* catch events using our callbacks and give a local context */
	opj_set_event_mgr((opj_common_ptr)dinfo, &event_mgr, stderr);

	/* setup the decoder decoding parameters using user parameters */
	opj_setup_decoder(dinfo, &parameters);

	/* open a byte stream */
	cio = opj_cio_open((opj_common_ptr)dinfo, src, j2k_len);

	/* decode the stream and fill the image structure */
	opjimage = opj_decode_with_info(dinfo, cio, &cstr_info);
	if (!opjimage) {
		wxMutexGuiEnter();
		wxLogError(wxT("MXF: failed to decode image!"));
		wxMutexGuiLeave();
		opj_destroy_decompress(dinfo);
		opj_cio_close(cio);
		free(src);
		return false;
	}

	/* close the byte stream */
	opj_cio_close(cio);

	/* common rendering method */
#include "imagjpeg2000.cpp"

    wxMutexGuiEnter();
    wxLogMessage(wxT("MXF: image loaded."));
    wxMutexGuiLeave();

	/* close openjpeg structs */
	opj_destroy_decompress(dinfo);
	opj_image_destroy(opjimage);
	free(src);

	if (!image->Ok())
		return false;
	else
		return true;

}