Пример #1
0
int opj_init_from_stream(opj_dparameters_t *parameters, struct opj_res *resources) {

	resources->image = NULL;
	resources->l_codec = opj_create_decompress(OPJ_CODEC_JP2);

	if(!opj_setup_decoder(resources->l_codec, parameters)) {
		opj_stream_destroy(resources->l_stream);
		opj_destroy_codec(resources->l_codec);
		resources->l_stream = NULL;
		resources->l_codec = NULL;
		return 2;
	}

	if(!opj_read_header(resources->l_stream, resources->l_codec, &(resources->image))) {
		opj_stream_destroy(resources->l_stream);
		opj_destroy_codec(resources->l_codec);
		opj_image_destroy(resources->image);
		resources->l_stream = NULL;
		resources->l_codec = NULL;
		resources->image = NULL;
		return 3;
	}

	if(getenv("JP2_VERBOSE") != NULL) {
		opj_set_info_handler(resources->l_codec, info_callback,00);
		opj_set_warning_handler(resources->l_codec, warning_callback,00);
	}

	if(getenv("JP2_SUPPRESS_ERRORS") == NULL) {
		opj_set_error_handler(resources->l_codec, error_callback,00);
	}

	return 0;
}
Пример #2
0
opj_codec_t* ossimOpjCompressor::createOpjCodec( bool jp2 ) const
{
   opj_codec_t* codec = 0;
   if ( jp2 )
   {
      codec = opj_create_compress(OPJ_CODEC_JP2);
   }
   else
   {
      codec = opj_create_compress(OPJ_CODEC_J2K);
   }

   if ( codec )
   {
      // Catch events using our callbacks and give a local context.
      opj_set_info_handler   (codec, ossim::opj_info_callback,   00);
      opj_set_warning_handler(codec, ossim::opj_warning_callback,00);
      opj_set_error_handler  (codec, ossim::opj_error_callback,  00);
   }
   return codec;
   
} // End: opj_codec_t* createOpjCodec()
Пример #3
0
int main (int argc, char *argv[])
{
        opj_dparameters_t l_param;
        opj_codec_t * l_codec;
        opj_image_t * l_image;
        opj_stream_t * l_stream;
        OPJ_UINT32 l_data_size;
        OPJ_UINT32 l_max_data_size = 1000;
        OPJ_UINT32 l_tile_index;
        OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
        OPJ_BOOL l_go_on = OPJ_TRUE;
        OPJ_UINT32 l_nb_comps=0 ;
        OPJ_INT32 l_current_tile_x0,l_current_tile_y0,l_current_tile_x1,l_current_tile_y1;

        int da_x0=0;
        int da_y0=0;
        int da_x1=1000;
        int da_y1=1000;
        char input_file[64];

        /* should be test_tile_decoder 0 0 1000 1000 tte1.j2k */
        if( argc == 6 )
        {
                da_x0=atoi(argv[1]);
                da_y0=atoi(argv[2]);
                da_x1=atoi(argv[3]);
                da_y1=atoi(argv[4]);
                strcpy(input_file,argv[5]);

        }
        else
        {
                da_x0=0;
                da_y0=0;
                da_x1=1000;
                da_y1=1000;
                strcpy(input_file,"test.j2k");
        }

        if (! l_data) {
                return EXIT_FAILURE;
        }

        l_stream = opj_stream_create_default_file_stream(input_file,OPJ_TRUE);
        if (!l_stream){
                free(l_data);
                fprintf(stderr, "ERROR -> failed to create the stream from the file\n");
                return EXIT_FAILURE;
        }

        /* Set the default decoding parameters */
        opj_set_default_decoder_parameters(&l_param);

        /* */
        l_param.decod_format = infile_format(input_file);

        /** you may here add custom decoding parameters */
        /* do not use layer decoding limitations */
        l_param.cp_layer = 0;

        /* do not use resolutions reductions */
        l_param.cp_reduce = 0;

        /* to decode only a part of the image data */
        /*opj_restrict_decoding(&l_param,0,0,1000,1000);*/


        switch(l_param.decod_format) {
                case J2K_CFMT:	/* JPEG-2000 codestream */
                        {
                                /* Get a decoder handle */
                                l_codec = opj_create_decompress(OPJ_CODEC_J2K);
                                break;
                        }
                case JP2_CFMT:	/* JPEG 2000 compressed image data */
                        {
                                /* Get a decoder handle */
                                l_codec = opj_create_decompress(OPJ_CODEC_JP2);
                                break;
                        }
                default:
                        {
                                fprintf(stderr, "ERROR -> Not a valid JPEG2000 file!\n");
                                free(l_data);
                                opj_stream_destroy(l_stream);
                                return EXIT_FAILURE;
                        }
        }

        /* catch events using our callbacks and give a local context */
        opj_set_info_handler(l_codec, info_callback,00);
        opj_set_warning_handler(l_codec, warning_callback,00);
        opj_set_error_handler(l_codec, error_callback,00);

        /* Setup the decoder decoding parameters using user parameters */
        if (! opj_setup_decoder(l_codec, &l_param))
        {
                fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
                free(l_data);
                opj_stream_destroy(l_stream);
                opj_destroy_codec(l_codec);
                return EXIT_FAILURE;
        }

        /* Read the main header of the codestream and if necessary the JP2 boxes*/
        if (! opj_read_header(l_stream, l_codec, &l_image))
        {
                fprintf(stderr, "ERROR -> j2k_to_image: failed to read the header\n");
                free(l_data);
                opj_stream_destroy(l_stream);
                opj_destroy_codec(l_codec);
                return EXIT_FAILURE;
        }

        if (!opj_set_decode_area(l_codec, l_image, da_x0, da_y0,da_x1, da_y1)){
                fprintf(stderr,	"ERROR -> j2k_to_image: failed to set the decoded area\n");
                free(l_data);
                opj_stream_destroy(l_stream);
                opj_destroy_codec(l_codec);
                opj_image_destroy(l_image);
                return EXIT_FAILURE;
        }


        while (l_go_on)
        {
                if (! opj_read_tile_header( l_codec,
                                        l_stream,
                                        &l_tile_index,
                                        &l_data_size,
                                        &l_current_tile_x0,
                                        &l_current_tile_y0,
                                        &l_current_tile_x1,
                                        &l_current_tile_y1,
                                        &l_nb_comps,
                                        &l_go_on))
                {
                        free(l_data);
                        opj_stream_destroy(l_stream);
                        opj_destroy_codec(l_codec);
                        opj_image_destroy(l_image);
                        return EXIT_FAILURE;
                }

                if (l_go_on)
                {
                        if (l_data_size > l_max_data_size)
                        {
                                OPJ_BYTE *l_new_data = (OPJ_BYTE *) realloc(l_data, l_data_size);
                                if (! l_new_data)
                                {
                                        free(l_new_data);
                                        opj_stream_destroy(l_stream);
                                        opj_destroy_codec(l_codec);
                                        opj_image_destroy(l_image);
                                        return EXIT_FAILURE;
                                }
                                l_data = l_new_data;
                                l_max_data_size = l_data_size;
                        }

                        if (! opj_decode_tile_data(l_codec,l_tile_index,l_data,l_data_size,l_stream))
                        {
                                free(l_data);
                                opj_stream_destroy(l_stream);
                                opj_destroy_codec(l_codec);
                                opj_image_destroy(l_image);
                                return EXIT_FAILURE;
                        }
                        /** now should inspect image to know the reduction factor and then how to behave with data */
                }
        }

        if (! opj_end_decompress(l_codec,l_stream))
        {
                free(l_data);
                opj_stream_destroy(l_stream);
                opj_destroy_codec(l_codec);
                opj_image_destroy(l_image);
                return EXIT_FAILURE;
        }

        /* Free memory */
        free(l_data);
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        opj_image_destroy(l_image);

        /* Print profiling*/
        /*PROFPRINT();*/

        return EXIT_SUCCESS;
}
Пример #4
0
/*!
 *  pixWriteStreamJp2k()
 *
 *      Input:  stream
 *              pix  (any depth, cmap is OK)
 *              quality (SNR > 0; default ~34; 0 for lossless encoding)
 *              nlevels (<= 10)
 *              hint (a bitwise OR of L_JP2K_* values; 0 for default)
 *              debug (output callback messages, etc)
 *      Return: 0 if OK, 1 on error
 *  Notes:
 *      (1) See pixWriteJp2k() for usage.
 *      (2) For an encoder with more encoding options, see, e.g.,
 *    https://github.com/OpenJPEG/openjpeg/blob/master/tests/test_tile_encoder.c
 */
l_int32
pixWriteStreamJp2k(FILE    *fp,
                   PIX     *pix,
                   l_int32  quality,
                   l_int32  nlevels,
                   l_int32  hint,
                   l_int32  debug)
{
l_int32            w, h, d, success, snr;
const char        *opjVersion;
PIX               *pixs;
opj_cparameters_t  parameters;   /* compression parameters */
opj_stream_t      *l_stream = NULL;
opj_codec_t*       l_codec = NULL;;
opj_image_t       *image = NULL;

    PROCNAME("pixWriteStreamJp2k");

    if (!fp)
        return ERROR_INT("stream not open", procName, 1);
    if (!pix)
        return ERROR_INT("pix not defined", procName, 1);
    if (quality < 0)
        return ERROR_INT("quality must be >= 0", procName, 1);
    if (quality > 0 && quality < 27)
        L_WARNING("SNR = %d < 27; very low\n", procName, quality);
    if (quality > 45)
        L_WARNING("SNR = %d > 45; nearly lossless\n", procName, quality);
    snr = (l_float32)quality;

    if (nlevels <= 0) nlevels = 5;  /* default */
    if (nlevels > 10) {
        L_WARNING("nlevels = %d > 10; setting to 10\n", procName, nlevels);
        nlevels = 10;
    }

    opjVersion = opj_version();
    if (opjVersion[0] != '2') {
        L_ERROR("version is %s; must be 2.0 or higher\n", procName, opjVersion);
        return 1;
    }
    if ((opjVersion[2] - 0x30) != OPJ_VERSION_MINOR) {
        L_ERROR("version %s: differs from minor = %d\n",
                procName, opjVersion, OPJ_VERSION_MINOR);
         return 1;
     }

        /* Remove colormap if it exists; result is 8 or 32 bpp */
    pixGetDimensions(pix, &w, &h, &d);
    if (d == 24) {
        pixs = pixConvert24To32(pix);
    } else if (d == 32) {
        pixs = pixClone(pix);
    } else if (pixGetColormap(pix) == NULL) {
        pixs = pixConvertTo8(pix, 0);
    } else {  /* colormap */
        L_INFO("removing colormap; may be better to compress losslessly\n",
               procName);
        pixs = pixRemoveColormap(pix, REMOVE_CMAP_BASED_ON_SRC);
    }

        /* Convert to opj image format. */
    image = pixConvertToOpjImage(pixs);
    pixDestroy(&pixs);

        /* Set encoding parameters to default values.
         * We use one layer with the input SNR. */
    opj_set_default_encoder_parameters(&parameters);
    parameters.cp_fixed_quality = 1;
    parameters.cp_disto_alloc = 0;
    parameters.cp_fixed_alloc =  0;
    parameters.tcp_distoratio[0] = snr;
    parameters.tcp_numlayers = 1;
    parameters.numresolution = nlevels + 1;

        /* Create comment for codestream */
    if (parameters.cp_comment == NULL) {
        const char comment1[] = "Created by Leptonica, version ";
        const char comment2[] = "; using OpenJPEG, version ";
        size_t len1 = strlen(comment1);
        size_t len2 = strlen(comment2);
        char *version1 = getLeptonicaVersion();
        const char *version2 = opj_version();
        len1 += len2 + strlen(version1) + strlen(version2) + 1;
        parameters.cp_comment = (char *)MALLOC(len1);
        snprintf(parameters.cp_comment, len1, "%s%s%s%s", comment1, version1,
                 comment2, version2);
        FREE(version1);
    }

        /* Get the encoder handle */
    if ((l_codec = opj_create_compress(OPJ_CODEC_JP2)) == NULL) {
        opj_image_destroy(image);
        FREE(parameters.cp_comment);
        return ERROR_INT("failed to get the encoder handle\n", procName, 1);
    }

        /* Catch and report events using callbacks */
    if (debug) {
        opj_set_info_handler(l_codec, info_callback, NULL);
        opj_set_warning_handler(l_codec, warning_callback, NULL);
        opj_set_error_handler(l_codec, error_callback, NULL);
    }

        /* Set up the encoder */
    if (!opj_setup_encoder(l_codec, &parameters, image)) {
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        FREE(parameters.cp_comment);
        return ERROR_INT("failed to set up the encoder\n", procName, 1);
    }

        /* Open a compression stream for writing.  In 2.0 we could use this:
         *     opj_stream_create_default_file_stream(fp, 0)
         * but the file stream interface was removed in 2.1.  */
    rewind(fp);
    if ((l_stream = opjCreateStream(fp, 0)) == NULL) {
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        FREE(parameters.cp_comment);
        return ERROR_INT("failed to open l_stream\n", procName, 1);
    }

        /* Encode the image */
    if (!opj_start_compress(l_codec, image, l_stream)) {
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        FREE(parameters.cp_comment);
        return ERROR_INT("opj_start_compress failed\n", procName, 1);
    }
    if (!opj_encode(l_codec, l_stream)) {
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        FREE(parameters.cp_comment);
        return ERROR_INT("opj_encode failed\n", procName, 1);
    }
    success = opj_end_compress(l_codec, l_stream);

        /* Clean up */
    opj_stream_destroy(l_stream);
    opj_destroy_codec(l_codec);
    opj_image_destroy(image);
    FREE(parameters.cp_comment);
    if (success)
        return 0;
    else
        return ERROR_INT("opj_end_compress failed\n", procName, 1);
}
Пример #5
0
int GP_ReadJP2Ex(GP_IO *io, GP_Context **rimg, GP_DataStorage *storage,
                 GP_ProgressCallback *callback)
{
	opj_dparameters_t params;
	opj_codec_t *codec;
	opj_stream_t *stream;
	opj_image_t *img;

	GP_PixelType pixel_type;
	GP_Context *res = NULL;
	unsigned int i, x, y;
	int err = 0, ret = 1;

	opj_set_default_decoder_parameters(&params);

	codec = opj_create_decompress(OPJ_CODEC_JP2);

	if (!codec) {
		GP_DEBUG(1, "opj_create_decompress failed");
		err = ENOMEM;
		goto err0;
	}

	opj_set_error_handler(codec, jp2_err_callback, NULL);
	opj_set_warning_handler(codec, jp2_warn_callback, NULL);
	opj_set_info_handler(codec, jp2_info_callback, callback);

	if (!opj_setup_decoder(codec, &params)) {
		GP_DEBUG(1, "opj_setup_decoder failed");
		err = ENOMEM;
		goto err1;
	}

	stream = opj_stream_default_create(OPJ_TRUE);

	if (!stream) {
		GP_DEBUG(1, "opj_stream_create_default_file_stream faled");
		err = ENOMEM;
		goto err1;
	}

	//TODO: Do we need seek and skip?
	opj_stream_set_read_function(stream, jp2_io_read);
	opj_stream_set_user_data(stream, io);

	if (!opj_read_header(stream, codec, &img)) {
		GP_DEBUG(1, "opj_read_header failed");
		err = EINVAL;
		goto err2;
	}

	if (storage)
		fill_metadata(img, storage);

	GP_DEBUG(1, "Have image %ux%u-%ux%u colorspace=%s numcomps=%u",
	         img->x0, img->y0, img->x1, img->y1,
	         color_space_name(img->color_space), img->numcomps);

	if (!rimg)
		return 0;

	/*
	 * Try to match the image information into pixel type.
	 *
	 * Unfortunately the images I had have color_space set
	 * to unspecified yet they were RGB888.
	 */
	for (i = 0; i < img->numcomps; i++) {
		opj_image_comp_t *comp = &img->comps[i];

		GP_DEBUG(2, "Component %u %ux%u bpp=%u",
		         i, comp->w, comp->h, comp->prec);

		if (comp->w != img->comps[0].w ||
		    comp->h != img->comps[0].h) {
			GP_DEBUG(1, "Component %u has different size", 1);
			err = ENOSYS;
			goto err3;
		}

		if (comp->prec != 8) {
			GP_DEBUG(1, "Component %u has different bpp", 1);
			err = ENOSYS;
			goto err3;
		}
	}

	switch (img->color_space) {
	case OPJ_CLRSPC_UNSPECIFIED:
		if (img->numcomps != 3) {
			GP_DEBUG(1, "Unexpected number of components");
			err = ENOSYS;
			goto err3;
		}
		pixel_type = GP_PIXEL_RGB888;
	break;
	default:
		GP_DEBUG(1, "Unsupported colorspace");
		err = ENOSYS;
		goto err3;
	}

	GP_ProgressCallbackReport(callback, 0, 100, 100);

	if (!opj_decode(codec, stream, img)) {
		GP_DEBUG(1, "opj_decode failed");
		err = EINVAL;
		goto err3;
	}

	res = GP_ContextAlloc(img->comps[0].w, img->comps[0].h, pixel_type);

	if (!res) {
		GP_DEBUG(1, "Malloc failed :(");
		err = ENOMEM;
		goto err3;
	}

	for (y = 0; y < res->h; y++) {
		for (x = 0; x < res->w; x++) {
			i = y * res->w + x;

			GP_Pixel p = img->comps[0].data[i] << 16|
			             img->comps[1].data[i] << 8 |
			             img->comps[2].data[i];

			GP_PutPixel_Raw_24BPP(res, x, y, p);
		}
	}

	GP_ProgressCallbackDone(callback);
	*rimg = res;
	ret = 0;
err3:
	opj_image_destroy(img);
err2:
	opj_stream_destroy(stream);
err1:
	opj_destroy_codec(codec);
err0:
	if (err)
		errno = err;
	return ret;
}
Пример #6
0
static GstFlowReturn
gst_openjpeg_enc_handle_frame (GstVideoEncoder * encoder,
    GstVideoCodecFrame * frame)
{
  GstOpenJPEGEnc *self = GST_OPENJPEG_ENC (encoder);
  GstFlowReturn ret = GST_FLOW_OK;
#ifdef HAVE_OPENJPEG_1
  opj_cinfo_t *enc;
  GstMapInfo map;
  guint length;
  opj_cio_t *io;
#else
  opj_codec_t *enc;
  opj_stream_t *stream;
  MemStream mstream;
#endif
  opj_image_t *image;
  GstVideoFrame vframe;

  GST_DEBUG_OBJECT (self, "Handling frame");

  enc = opj_create_compress (self->codec_format);
  if (!enc)
    goto initialization_error;

#ifdef HAVE_OPENJPEG_1
  if (G_UNLIKELY (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >=
          GST_LEVEL_TRACE)) {
    opj_event_mgr_t callbacks;

    callbacks.error_handler = gst_openjpeg_enc_opj_error;
    callbacks.warning_handler = gst_openjpeg_enc_opj_warning;
    callbacks.info_handler = gst_openjpeg_enc_opj_info;
    opj_set_event_mgr ((opj_common_ptr) enc, &callbacks, self);
  } else {
    opj_set_event_mgr ((opj_common_ptr) enc, NULL, NULL);
  }
#else
  if (G_UNLIKELY (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >=
          GST_LEVEL_TRACE)) {
    opj_set_info_handler (enc, gst_openjpeg_enc_opj_info, self);
    opj_set_warning_handler (enc, gst_openjpeg_enc_opj_warning, self);
    opj_set_error_handler (enc, gst_openjpeg_enc_opj_error, self);
  } else {
    opj_set_info_handler (enc, NULL, NULL);
    opj_set_warning_handler (enc, NULL, NULL);
    opj_set_error_handler (enc, NULL, NULL);
  }
#endif

  if (!gst_video_frame_map (&vframe, &self->input_state->info,
          frame->input_buffer, GST_MAP_READ))
    goto map_read_error;

  image = gst_openjpeg_enc_fill_image (self, &vframe);
  if (!image)
    goto fill_image_error;
  gst_video_frame_unmap (&vframe);

  opj_setup_encoder (enc, &self->params, image);

#ifdef HAVE_OPENJPEG_1
  io = opj_cio_open ((opj_common_ptr) enc, NULL, 0);
  if (!io)
    goto open_error;

  if (!opj_encode (enc, io, image, NULL))
    goto encode_error;

  opj_image_destroy (image);

  length = cio_tell (io);

  ret =
      gst_video_encoder_allocate_output_frame (encoder, frame,
      length + (self->is_jp2c ? 8 : 0));
  if (ret != GST_FLOW_OK)
    goto allocate_error;

  gst_buffer_fill (frame->output_buffer, self->is_jp2c ? 8 : 0, io->buffer,
      length);
  if (self->is_jp2c) {
    gst_buffer_map (frame->output_buffer, &map, GST_MAP_WRITE);
    GST_WRITE_UINT32_BE (map.data, length + 8);
    GST_WRITE_UINT32_BE (map.data + 4, GST_MAKE_FOURCC ('j', 'p', '2', 'c'));
    gst_buffer_unmap (frame->output_buffer, &map);
  }

  opj_cio_close (io);
  opj_destroy_compress (enc);
#else
  stream = opj_stream_create (4096, OPJ_FALSE);
  if (!stream)
    goto open_error;

  mstream.allocsize = 4096;
  mstream.data = g_malloc (mstream.allocsize);
  mstream.offset = 0;
  mstream.size = 0;

  opj_stream_set_read_function (stream, read_fn);
  opj_stream_set_write_function (stream, write_fn);
  opj_stream_set_skip_function (stream, skip_fn);
  opj_stream_set_seek_function (stream, seek_fn);
  opj_stream_set_user_data (stream, &mstream);
  opj_stream_set_user_data_length (stream, mstream.size);

  if (!opj_start_compress (enc, image, stream))
    goto encode_error;

  if (!opj_encode (enc, stream))
    goto encode_error;

  if (!opj_end_compress (enc, stream))
    goto encode_error;

  opj_image_destroy (image);
  opj_stream_destroy (stream);
  opj_destroy_codec (enc);

  frame->output_buffer = gst_buffer_new ();

  if (self->is_jp2c) {
    GstMapInfo map;
    GstMemory *mem;

    mem = gst_allocator_alloc (NULL, 8, NULL);
    gst_memory_map (mem, &map, GST_MAP_WRITE);
    GST_WRITE_UINT32_BE (map.data, mstream.size + 8);
    GST_WRITE_UINT32_BE (map.data + 4, GST_MAKE_FOURCC ('j', 'p', '2', 'c'));
    gst_memory_unmap (mem, &map);
    gst_buffer_append_memory (frame->output_buffer, mem);
  }

  gst_buffer_append_memory (frame->output_buffer,
      gst_memory_new_wrapped (0, mstream.data, mstream.allocsize, 0,
          mstream.size, NULL, (GDestroyNotify) g_free));
#endif

  ret = gst_video_encoder_finish_frame (encoder, frame);

  return ret;

initialization_error:
  {
    gst_video_codec_frame_unref (frame);
    GST_ELEMENT_ERROR (self, LIBRARY, INIT,
        ("Failed to initialize OpenJPEG encoder"), (NULL));
    return GST_FLOW_ERROR;
  }
map_read_error:
  {
#ifdef HAVE_OPENJPEG_1
    opj_destroy_compress (enc);
#else
    opj_destroy_codec (enc);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to map input buffer"), (NULL));
    return GST_FLOW_ERROR;
  }
fill_image_error:
  {
#ifdef HAVE_OPENJPEG_1
    opj_destroy_compress (enc);
#else
    opj_destroy_codec (enc);
#endif
    gst_video_frame_unmap (&vframe);
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, LIBRARY, INIT,
        ("Failed to fill OpenJPEG image"), (NULL));
    return GST_FLOW_ERROR;
  }
open_error:
  {
    opj_image_destroy (image);
#ifdef HAVE_OPENJPEG_1
    opj_destroy_compress (enc);
#else
    opj_destroy_codec (enc);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, LIBRARY, INIT,
        ("Failed to open OpenJPEG data"), (NULL));
    return GST_FLOW_ERROR;
  }
encode_error:
  {
#ifdef HAVE_OPENJPEG_1
    opj_cio_close (io);
    opj_image_destroy (image);
    opj_destroy_compress (enc);
#else
    opj_stream_destroy (stream);
    g_free (mstream.data);
    opj_image_destroy (image);
    opj_destroy_codec (enc);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, STREAM, ENCODE,
        ("Failed to encode OpenJPEG stream"), (NULL));
    return GST_FLOW_ERROR;
  }
#ifdef HAVE_OPENJPEG_1
allocate_error:
  {
    opj_cio_close (io);
    opj_destroy_compress (enc);
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to allocate output buffer"), (NULL));
    return ret;
  }
#endif
}
Пример #7
0
OFCondition DJCompressJP2K::encode( 
  Uint16 columns,
  Uint16 rows,
  EP_Interpretation colorSpace,
  Uint16 samplesPerPixel,
  Uint16 * image_buffer,
  Uint16 * & to,
  Uint32 & length,
  Uint8 bitsAllocated,
  Uint8 pixelRepresentation,
  double minUsed, double maxUsed)
{
	int bitsstored = bitsAllocated;
	
    if( samplesPerPixel > 1)
        bitsstored = bitsAllocated = 8;
    
	OFBool isSigned = pixelRepresentation;
	
	if( bitsAllocated >= 16)
	{
		int amplitude = maxUsed;
		
		if( minUsed < 0)
			amplitude -= minUsed;
		
		int bits = 1, value = 2;
		
		while( value < amplitude && bits <= 16)
		{
			value *= 2;
			bits++;
		}
		
		if( minUsed < 0) // K A10009536850 22.06.12
			bits++;
		
		if( bits < 9)
			bits = 9;
		
		// avoid the artifacts... switch to lossless
		if( (maxUsed >= 32000 && minUsed <= -32000) || maxUsed >= 65000 || bits > 16)
			quality = 0;
		
		if( bits > 16) bits = 16;
		
		bitsstored = bits;
	}
    opj_cparameters_t parameters;
    opj_image_t *image = NULL;
		
//    printf( "JP2K OPJ-DCMTK-Encode ");
		
    opj_set_default_encoder_parameters(&parameters);

    parameters.tcp_numlayers = 1;
    parameters.cp_disto_alloc = 1;
		
    switch( quality)
    {
    case 0: // DCMLosslessQuality
        parameters.tcp_rates[0] = 0;
        break;
            
    case 1: // DCMHighQuality
        parameters.tcp_rates[0] = 4;
        break;
            
    case 2: // DCMMediumQuality
        if( columns <= 600 || rows <= 600)
            parameters.tcp_rates[0] = 6;
        else
            parameters.tcp_rates[0] = 8;
        break;
            
    case 3: // DCMLowQuality
        parameters.tcp_rates[0] = 16;
        break;
            
    default:
        //printf( "****** warning unknown compression rate -> MediumQuality : %d", quality);
        if( columns <= 600 || rows <= 600)
            parameters.tcp_rates[0] = 6;
        else
            parameters.tcp_rates[0] = 8;
        break;
    }

    int image_width = columns;
    int image_height = rows;
    int sample_pixel = samplesPerPixel;

    if (colorSpace == EPI_Monochrome1 || colorSpace == EPI_Monochrome2)
    {

    }
    else
    {
        if( sample_pixel != 3)
            printf( "*** RGB Photometric?, but... SamplesPerPixel != 3 ?");
        sample_pixel = 3;
    }

    image = rawtoimage( (char *)image_buffer, &parameters,  static_cast<int>( columns*rows*samplesPerPixel*bitsAllocated/8),  image_width, image_height, sample_pixel, bitsAllocated, bitsstored, isSigned, quality, 0);

    if(!image) {
        fprintf(stderr, "Unable to load buffer image\n");
        return EC_Normal;
    } 
        
    parameters.cod_format = 0; /* J2K format output */
    int codestream_length;

    opj_codec_t *l_codec = 00;
    l_codec = opj_create_compress(OPJ_CODEC_J2K);
    opj_set_info_handler(l_codec, info_callback,00);
    opj_set_warning_handler(l_codec, warning_callback,00);
    opj_set_error_handler(l_codec, error_callback,00);

    /* setup the encoder parameters using the current image and using user parameters */
    opj_setup_encoder(l_codec, &parameters, image);

    char * l_out;
    size_t l_size;
    FILE * l_file = open_memstream(&l_out, &l_size);

    opj_stream_t * l_stream = opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE, OPJ_FALSE);
    if (! l_stream){
        fprintf(stderr, "failed to create stream\n");
        return EC_Normal;
    }

    opj_stream_set_user_data(l_stream, l_file, (opj_stream_free_user_data_fn)NULL);
    opj_stream_set_write_function(l_stream, (opj_stream_write_fn)_write);
    /* encode the image */
    int bSuccess = opj_start_compress(l_codec, image, l_stream);
    if (!bSuccess) {
        fprintf(stderr, "failed to encode image\n");
        return EC_Normal;
    }

    bSuccess = bSuccess && opj_encode(l_codec, l_stream);
    if (!bSuccess) {
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        fprintf(stderr, "failed to encode image 2\n");
        remove(parameters.outfile);
        return EC_Normal;
    }

    bSuccess = bSuccess && opj_end_compress(l_codec, l_stream);
    if (!bSuccess)  {
        fprintf(stderr, "failed to encode image: opj_end_compress\n");
        return EC_Normal;
    }

    /* l_file memstream must be flushed to allow accessint to l_out and l_size values */
    fflush(l_file);
#ifdef _WIN32
	get_buffer_and_size(l_file);
#endif
    fclose(l_file);
    /* copy compressed stream to "to" UINT8*  */
    to = new Uint16[l_size];
    memcpy( to, l_out, l_size);
    length = l_size;

    /* free remaining compression structures */
    free(l_out);
    opj_stream_destroy(l_stream);
    opj_destroy_codec(l_codec);
    opj_image_destroy(image);
//	}
    return EC_Normal;
}
Пример #8
0
static FIBITMAP * DLL_CALLCONV
Load(FreeImageIO *io, fi_handle handle, int page, int flags, void *data) {
	J2KFIO_t *fio = (J2KFIO_t*)data;
	if (handle && fio) {
		opj_codec_t *d_codec = NULL;	// handle to a decompressor
		opj_dparameters_t parameters;	// decompression parameters
		opj_image_t *image = NULL;		// decoded image 

		FIBITMAP *dib = NULL;

		// check the file format
		if(!Validate(io, handle)) {
			return NULL;
		}

		BOOL header_only = (flags & FIF_LOAD_NOPIXELS) == FIF_LOAD_NOPIXELS;

		// get the OpenJPEG stream
		opj_stream_t *d_stream = fio->stream;

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

		try {
			// decode the JPEG-2000 codestream

			// get a decoder handle
			d_codec = opj_create_decompress(OPJ_CODEC_J2K);
			
			// configure the event callbacks
			// catch events using our callbacks (no local context needed here)
			opj_set_info_handler(d_codec, NULL, NULL);
			opj_set_warning_handler(d_codec, j2k_warning_callback, NULL);
			opj_set_error_handler(d_codec, j2k_error_callback, NULL);

			// setup the decoder decoding parameters using user parameters
			if( !opj_setup_decoder(d_codec, &parameters) ) {
				throw "Failed to setup the decoder\n";
			}
			
			// read the main header of the codestream and if necessary the JP2 boxes
			if( !opj_read_header(d_stream, d_codec, &image)) {
				throw "Failed to read the header\n";
			}

			// --- header only mode

			if (header_only) {
				// create output image 
				dib = J2KImageToFIBITMAP(s_format_id, image, header_only);
				if(!dib) {
					throw "Failed to import JPEG2000 image";
				}
				// clean-up and return header data
				opj_destroy_codec(d_codec);
				opj_image_destroy(image);
				return dib;
			}

			// decode the stream and fill the image structure 
			if( !( opj_decode(d_codec, d_stream, image) && opj_end_decompress(d_codec, d_stream) ) ) {
				throw "Failed to decode image!\n";
			}

			// free the codec context
			opj_destroy_codec(d_codec);
			d_codec = NULL;

			// create output image 
			dib = J2KImageToFIBITMAP(s_format_id, image, header_only);
			if(!dib) {
				throw "Failed to import JPEG2000 image";
			}

			// free image data structure
			opj_image_destroy(image);

			return dib;

		} catch (const char *text) {
			if(dib) {
				FreeImage_Unload(dib);
			}
			// free remaining structures
			opj_destroy_codec(d_codec);
			opj_image_destroy(image);

			FreeImage_OutputMessageProc(s_format_id, text);

			return NULL;
		}
	}

	return NULL;
}
Пример #9
0
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
	opj_decompress_parameters parameters;			/* decompression parameters */
	opj_image_t* image = NULL;
	opj_stream_t *l_stream = NULL;				/* Stream */
	opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
	opj_codestream_index_t* cstr_index = NULL;

	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	OPJ_INT32 num_images, imageno;
	img_fol_t img_fol;
	dircnt_t *dirptr = NULL;
  int failed = 0;
  OPJ_FLOAT64 t, tCumulative = 0;
  OPJ_UINT32 numDecompressedImages = 0;

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

	/* FIXME Initialize indexfilename and img_fol */
	*indexfilename = 0;

	/* Initialize img_fol */
	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) {
		destroy_parameters(&parameters);
		return EXIT_FAILURE;
	}

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

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

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

	/*Decoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)	{

		fprintf(stderr,"\n");

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

		/* read the input file and put it in memory */
		/* ---------------------------------------- */

		l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
		if (!l_stream){
			fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n", parameters.infile);
			destroy_parameters(&parameters);
			return EXIT_FAILURE;
		}

		/* decode the JPEG2000 stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
			case J2K_CFMT:	/* JPEG-2000 codestream */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_J2K);
				break;
			}
			case JP2_CFMT:	/* JPEG 2000 compressed image data */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JP2);
				break;
			}
			case JPT_CFMT:	/* JPEG 2000, JPIP */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JPT);
				break;
			}
			default:
				fprintf(stderr, "skipping file..\n");
				destroy_parameters(&parameters);
				opj_stream_destroy(l_stream);
				continue;
		}

		/* catch events using our callbacks and give a local context */		
		opj_set_info_handler(l_codec, info_callback,00);
		opj_set_warning_handler(l_codec, warning_callback,00);
		opj_set_error_handler(l_codec, error_callback,00);

		t = opj_clock();

		/* Setup the decoder decoding parameters using user parameters */
		if ( !opj_setup_decoder(l_codec, &(parameters.core)) ){
			fprintf(stderr, "ERROR -> opj_decompress: failed to setup the decoder\n");
			destroy_parameters(&parameters);
			opj_stream_destroy(l_stream);
			opj_destroy_codec(l_codec);
			return EXIT_FAILURE;
		}


		/* Read the main header of the codestream and if necessary the JP2 boxes*/
		if(! opj_read_header(l_stream, l_codec, &image)){
			fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
			destroy_parameters(&parameters);
			opj_stream_destroy(l_stream);
			opj_destroy_codec(l_codec);
			opj_image_destroy(image);
			return EXIT_FAILURE;
		}

		if (!parameters.nb_tile_to_decode) {
			/* Optional if you want decode the entire image */
			if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
					(OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
				fprintf(stderr,	"ERROR -> opj_decompress: failed to set the decoded area\n");
				destroy_parameters(&parameters);
				opj_stream_destroy(l_stream);
				opj_destroy_codec(l_codec);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}

			/* Get the decoded image */
			if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,	l_stream))) {
				fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}
		}
		else {

			/* It is just here to illustrate how to use the resolution after set parameters */
			/*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}*/

			if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				return EXIT_FAILURE;
			}
			fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
		}

		tCumulative += opj_clock() - t;
		numDecompressedImages++;

		/* Close the byte stream */
		opj_stream_destroy(l_stream);

		if( image->color_space != OPJ_CLRSPC_SYCC 
			&& image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
			&& image->comps[1].dx != 1 )
			image->color_space = OPJ_CLRSPC_SYCC;
		else if (image->numcomps <= 2)
			image->color_space = OPJ_CLRSPC_GRAY;

		if(image->color_space == OPJ_CLRSPC_SYCC){
			color_sycc_to_rgb(image);
		}
		else if((image->color_space == OPJ_CLRSPC_CMYK) && (parameters.cod_format != TIF_DFMT)){
			color_cmyk_to_rgb(image);
		}
		else if(image->color_space == OPJ_CLRSPC_EYCC){
			color_esycc_to_rgb(image);
		}
		
		if(image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
			if(image->icc_profile_len)
			 color_apply_icc_profile(image);
			else
			 color_cielab_to_rgb(image);
#endif
			free(image->icc_profile_buf);
			image->icc_profile_buf = NULL; image->icc_profile_len = 0;
		}
		
		/* Force output precision */
		/* ---------------------- */
		if (parameters.precision != NULL)
		{
			OPJ_UINT32 compno;
			for (compno = 0; compno < image->numcomps; ++compno)
			{
				OPJ_UINT32 precno = compno;
				OPJ_UINT32 prec;
				
				if (precno >= parameters.nb_precision) {
					precno = parameters.nb_precision - 1U;
				}
				
				prec = parameters.precision[precno].prec;
				if (prec == 0) {
					prec = image->comps[compno].prec;
				}
				
				switch (parameters.precision[precno].mode) {
					case OPJ_PREC_MODE_CLIP:
						clip_component(&(image->comps[compno]), prec);
						break;
					case OPJ_PREC_MODE_SCALE:
						scale_component(&(image->comps[compno]), prec);
						break;
					default:
						break;
				}
				
			}
		}
		
		/* Upsample components */
		/* ------------------- */
		if (parameters.upsample)
		{
			image = upsample_image_components(image);
			if (image == NULL) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to upsample image components!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				return EXIT_FAILURE;
			}
		}
		
		/* Force RGB output */
		/* ---------------- */
		if (parameters.force_rgb)
		{
			switch (image->color_space) {
				case OPJ_CLRSPC_SRGB:
					break;
				case OPJ_CLRSPC_GRAY:
					image = convert_gray_to_rgb(image);
					break;
				default:
					fprintf(stderr, "ERROR -> opj_decompress: don't know how to convert image to RGB colorspace!\n");
					opj_image_destroy(image);
					image = NULL;
					break;
			}
			if (image == NULL) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to convert to RGB image!\n");
				destroy_parameters(&parameters);
				opj_destroy_codec(l_codec);
				return EXIT_FAILURE;
			}
		}

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

		case PGX_DFMT:			/* PGX */
			if(imagetopgx(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;

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

		case RAWL_DFMT:			/* RAWL */
			if(imagetorawl(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;

		case TGA_DFMT:			/* TGA */
			if(imagetotga(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating tga file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;
#ifdef OPJ_HAVE_LIBPNG
		case PNG_DFMT:			/* PNG */
			if(imagetopng(image, parameters.outfile)){
                fprintf(stderr,"[ERROR] Error generating png file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
                fprintf(stdout,"[INFO] Generated Outfile %s\n",parameters.outfile);
			}
			break;
#endif /* OPJ_HAVE_LIBPNG */
/* Can happen if output file is TIFF or PNG
 * and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
*/
			default:
                fprintf(stderr,"[ERROR] Outfile %s not generated\n",parameters.outfile);
        failed = 1;
		}

		/* free remaining structures */
		if (l_codec) {
			opj_destroy_codec(l_codec);
		}


		/* free image data structure */
		opj_image_destroy(image);

		/* destroy the codestream index */
		opj_destroy_cstr_index(&cstr_index);

		if(failed) remove(parameters.outfile);
	}
	destroy_parameters(&parameters);
	if (numDecompressedImages) {
		fprintf(stdout, "decode time: %d ms\n", (int)( (tCumulative * 1000.0) / (OPJ_FLOAT64)numDecompressedImages));
	}
	return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Пример #10
0
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
	FILE *fsrc = NULL;

	opj_dparameters_t parameters;			/* decompression parameters */
	opj_image_t* image = NULL;
	opj_stream_t *l_stream = NULL;				/* Stream */
	opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
	opj_codestream_info_v2_t* cstr_info = NULL;

	/* Index of corner tiles */
	OPJ_UINT32 tile_ul = 0;
	OPJ_UINT32 tile_ur = 0;
	OPJ_UINT32 tile_lr = 0;
	OPJ_UINT32 tile_ll = 0;

	if (argc != 2) {
		fprintf(stderr, "Usage: %s <input_file>\n", argv[0]);
		return EXIT_FAILURE;
	}

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

	strncpy(parameters.infile, argv[1], OPJ_PATH_LEN - 1);

	/* read the input file */
	/* ------------------- */
	fsrc = fopen(parameters.infile, "rb");
	if (!fsrc) {
		fprintf(stderr, "ERROR -> failed to open %s for reading\n", parameters.infile);
		return EXIT_FAILURE;
	}

	/* decode the JPEG2000 stream */
	/* -------------------------- */
	parameters.decod_format = infile_format(parameters.infile);

	switch(parameters.decod_format) {
		case J2K_CFMT:	/* JPEG-2000 codestream */
		{
			/* Get a decoder handle */
			l_codec = opj_create_decompress_v2(CODEC_J2K);
			break;
		}
		case JP2_CFMT:	/* JPEG 2000 compressed image data */
		{
			/* Get a decoder handle */
			l_codec = opj_create_decompress_v2(CODEC_JP2);
			break;
		}
		case JPT_CFMT:	/* JPEG 2000, JPIP */
		{
			/* Get a decoder handle */
			l_codec = opj_create_decompress_v2(CODEC_JPT);
			break;
		}
		default:
			fprintf(stderr,
				"Unrecognized format for input %s [accept only *.j2k, *.jp2, *.jpc or *.jpt]\n\n",
				parameters.infile);
			return EXIT_FAILURE;
	}

	/* catch events using our callbacks and give a local context */		
	opj_set_info_handler(l_codec, info_callback,00);
	opj_set_warning_handler(l_codec, warning_callback,00);
	opj_set_error_handler(l_codec, error_callback,00);

	l_stream = opj_stream_create_default_file_stream(fsrc,1);
	if (!l_stream){
		fclose(fsrc);
		fprintf(stderr, "ERROR -> failed to create the stream from the file\n");
		return EXIT_FAILURE;
	}

	/* Setup the decoder decoding parameters using user parameters */
	if ( !opj_setup_decoder_v2(l_codec, &parameters) ){
		fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
		opj_stream_destroy(l_stream);
		fclose(fsrc);
		opj_destroy_codec(l_codec);
		return EXIT_FAILURE;
	}

	/* Read the main header of the codestream and if necessary the JP2 boxes*/
	if(! opj_read_header(l_stream, l_codec, &image)){
		fprintf(stderr, "ERROR -> j2k_to_image: failed to read the header\n");
		opj_stream_destroy(l_stream);
		fclose(fsrc);
		opj_destroy_codec(l_codec);
		opj_image_destroy(image);
		return EXIT_FAILURE;
	}

	/* Extract some info from the code stream */
	cstr_info = opj_get_cstr_info(l_codec);

	fprintf(stdout, "The file contains %dx%d tiles\n", cstr_info->tw, cstr_info->th);

	tile_ul = 0;
	tile_ur = cstr_info->tw - 1;
	tile_lr = cstr_info->tw * cstr_info->th - 1;
	tile_ll = tile_lr - cstr_info->tw;

#define TEST_TILE( tile_index ) \
	fprintf(stdout, "Decoding tile %d ...\n", tile_index); \
	if(!opj_get_decoded_tile(l_codec, l_stream, image, tile_index )){ \
		fprintf(stderr, "ERROR -> j2k_to_image: failed to decode tile %d\n", tile_index); \
		opj_stream_destroy(l_stream); \
		opj_destroy_cstr_info_v2(&cstr_info); \
		opj_destroy_codec(l_codec); \
		opj_image_destroy(image); \
		fclose(fsrc); \
		return EXIT_FAILURE; \
	} \
	fprintf(stdout, "Tile %d is decoded successfully\n", tile_index);

	TEST_TILE(tile_ul)
	TEST_TILE(tile_lr)
	TEST_TILE(tile_ul)
	TEST_TILE(tile_ll)
	TEST_TILE(tile_ur)
	TEST_TILE(tile_lr)

	/* Close the byte stream */
	opj_stream_destroy(l_stream);

	/* Destroy code stream info */
	opj_destroy_cstr_info_v2(&cstr_info);

	/* Free remaining structures */
	opj_destroy_codec(l_codec);

	/* Free image data structure */
	opj_image_destroy(image);

	/* Close the input file */
	fclose(fsrc);

	return EXIT_SUCCESS;
}
Пример #11
0
fz_pixmap *
fz_load_jpx(fz_context *ctx, unsigned char *data, int size, fz_colorspace *defcs, int indexed)
{
	fz_pixmap *img;
	fz_colorspace *origcs;
	opj_dparameters_t params;
	opj_codec_t *codec;
	opj_image_t *jpx;
	opj_stream_t *stream;
	fz_colorspace *colorspace;
	unsigned char *p;
	OPJ_CODEC_FORMAT format;
	int a, n, w, h, depth, sgnd;
	int x, y, k, v;
	stream_block sb;

	if (size < 2)
		fz_throw(ctx, FZ_ERROR_GENERIC, "not enough data to determine image format");

	/* Check for SOC marker -- if found we have a bare J2K stream */
	if (data[0] == 0xFF && data[1] == 0x4F)
		format = OPJ_CODEC_J2K;
	else
		format = OPJ_CODEC_JP2;

	opj_set_default_decoder_parameters(&params);
	if (indexed)
		params.flags |= OPJ_DPARAMETERS_IGNORE_PCLR_CMAP_CDEF_FLAG;

	codec = opj_create_decompress(format);
	opj_set_info_handler(codec, fz_opj_info_callback, ctx);
	opj_set_warning_handler(codec, fz_opj_warning_callback, ctx);
	opj_set_error_handler(codec, fz_opj_error_callback, ctx);
	if (!opj_setup_decoder(codec, &params))
	{
		fz_throw(ctx, FZ_ERROR_GENERIC, "j2k decode failed");
	}

	stream = opj_stream_default_create(OPJ_TRUE);
	sb.data = data;
	sb.pos = 0;
	sb.size = size;

	opj_stream_set_read_function(stream, fz_opj_stream_read);
	opj_stream_set_skip_function(stream, fz_opj_stream_skip);
	opj_stream_set_seek_function(stream, fz_opj_stream_seek);
	opj_stream_set_user_data(stream, &sb);
	/* Set the length to avoid an assert */
	opj_stream_set_user_data_length(stream, size);

	if (!opj_read_header(stream, codec, &jpx))
	{
		opj_stream_destroy(stream);
		opj_destroy_codec(codec);
		fz_throw(ctx, FZ_ERROR_GENERIC, "Failed to read JPX header");
	}

	if (!opj_decode(codec, stream, jpx))
	{
		opj_stream_destroy(stream);
		opj_destroy_codec(codec);
		opj_image_destroy(jpx);
		fz_throw(ctx, FZ_ERROR_GENERIC, "Failed to decode JPX image");
	}

	opj_stream_destroy(stream);
	opj_destroy_codec(codec);

	/* jpx should never be NULL here, but check anyway */
	if (!jpx)
		fz_throw(ctx, FZ_ERROR_GENERIC, "opj_decode failed");

	for (k = 1; k < (int)jpx->numcomps; k++)
	{
		if (!jpx->comps[k].data)
		{
			opj_image_destroy(jpx);
			fz_throw(ctx, FZ_ERROR_GENERIC, "image components are missing data");
		}
		if (jpx->comps[k].w != jpx->comps[0].w)
		{
			opj_image_destroy(jpx);
			fz_throw(ctx, FZ_ERROR_GENERIC, "image components have different width");
		}
		if (jpx->comps[k].h != jpx->comps[0].h)
		{
			opj_image_destroy(jpx);
			fz_throw(ctx, FZ_ERROR_GENERIC, "image components have different height");
		}
		if (jpx->comps[k].prec != jpx->comps[0].prec)
		{
			opj_image_destroy(jpx);
			fz_throw(ctx, FZ_ERROR_GENERIC, "image components have different precision");
		}
	}

	n = jpx->numcomps;
	w = jpx->comps[0].w;
	h = jpx->comps[0].h;
	depth = jpx->comps[0].prec;
	sgnd = jpx->comps[0].sgnd;

	if (jpx->color_space == OPJ_CLRSPC_SRGB && n == 4) { n = 3; a = 1; }
	else if (jpx->color_space == OPJ_CLRSPC_SYCC && n == 4) { n = 3; a = 1; }
	else if (n == 2) { n = 1; a = 1; }
	else if (n > 4) { n = 4; a = 1; }
	else { a = 0; }

	origcs = defcs;
	if (defcs)
	{
		if (defcs->n == n)
		{
			colorspace = defcs;
		}
		else
		{
			fz_warn(ctx, "jpx file and dict colorspaces do not match");
			defcs = NULL;
		}
	}

	if (!defcs)
	{
		switch (n)
		{
		case 1: colorspace = fz_device_gray(ctx); break;
		case 3: colorspace = fz_device_rgb(ctx); break;
		case 4: colorspace = fz_device_cmyk(ctx); break;
		}
	}

	fz_try(ctx)
	{
		img = fz_new_pixmap(ctx, colorspace, w, h);
	}
	fz_catch(ctx)
	{
		opj_image_destroy(jpx);
		fz_rethrow_message(ctx, "out of memory loading jpx");
	}

	p = img->samples;
	for (y = 0; y < h; y++)
	{
		for (x = 0; x < w; x++)
		{
			for (k = 0; k < n + a; k++)
			{
				v = jpx->comps[k].data[y * w + x];
				if (sgnd)
					v = v + (1 << (depth - 1));
				if (depth > 8)
					v = v >> (depth - 8);
				*p++ = v;
			}
			if (!a)
				*p++ = 255;
		}
	}

	opj_image_destroy(jpx);

	if (a)
	{
		if (n == 4)
		{
			fz_pixmap *tmp = fz_new_pixmap(ctx, fz_device_rgb(ctx), w, h);
			fz_convert_pixmap(ctx, tmp, img);
			fz_drop_pixmap(ctx, img);
			img = tmp;
		}
		fz_premultiply_pixmap(ctx, img);
	}

	if (origcs != defcs)
	{
		fz_pixmap *tmp = fz_new_pixmap(ctx, origcs, w, h);
		fz_convert_pixmap(ctx, tmp, img);
		fz_drop_pixmap(ctx, img);
		img = tmp;
	}

	return img;
}
Пример #12
0
bool Jpeg2000::load (const QString &filename,
                     QImage &imageResult) const
{
  LOG4CPP_INFO_S ((*mainCat)) << "Jpeg2000::load"
                              << " filename=" << filename.toLatin1().data();

  if (invalidFileExtension (filename)) {
    return false;
  }

  opj_dparameters_t parameters;
  initializeParameters (parameters);

  parameters.decod_format = inputFormat (filename.toLatin1().data());

  opj_stream_t *inStream = opj_stream_create_default_file_stream (filename.toLatin1().data(), 1);
  if (!inStream) {
    LOG4CPP_ERROR_S ((*mainCat)) << "Jpeg2000::load encountered error opening stream";
    return false;
  }

  // Create decoder
  opj_codec_t *inCodec = decode (parameters.decod_format);
  if (!inCodec) {
    LOG4CPP_ERROR_S ((*mainCat)) << "Jpeg2000::load encountered error creating decoding stream";
    opj_stream_destroy (inStream);
    return false;
  }

  // Callbacks for local handling of errors
  opj_set_info_handler (inCodec, infoCallback, 0);
  opj_set_warning_handler (inCodec, warningCallback, 0);
  opj_set_error_handler (inCodec, errorCallback, 0);

  if (!opj_setup_decoder (inCodec,
                          &parameters)) {
    LOG4CPP_ERROR_S ((*mainCat)) << "Jpeg2000::load encountered error decoding stream";
    opj_stream_destroy (inStream);
    opj_destroy_codec (inCodec);
    return false;
  }

  // Read header and, if necessary, the JP2 boxes
  opj_image_t *image;
  if (!opj_read_header (inStream,
                        inCodec,
                        &image)) {
    LOG4CPP_ERROR_S ((*mainCat)) << "Jpeg2000::load encountered error reading header";
    opj_stream_destroy (inStream);
    opj_destroy_codec (inCodec);
    opj_image_destroy (image);
    return false;
  }

  // Get the decoded image
  if (!(opj_decode (inCodec,
                    inStream,
                    image) &&
       opj_end_decompress (inCodec,
                           inStream))) {
    LOG4CPP_ERROR_S ((*mainCat)) << "Jpeg2000::load failed to decode image";
    opj_destroy_codec (inCodec);
    opj_stream_destroy (inStream);
    opj_image_destroy (image);
    return false;
  }

  // Close the byte stream
  opj_stream_destroy (inStream);

  applyImageTweaks (image);

  // Transform into ppm image in memory
  bool success = true;
  QBuffer buffer;
  buffer.open (QBuffer::WriteOnly);
  if (imagetopnm (image,
                  buffer)) {
    LOG4CPP_ERROR_S ((*mainCat)) << "Jpeg2000::load failed to generate new image";
    success = false;

  } else {

    // Intermediate file for debugging
//    QFile file ("jpeg2000.ppm");
//    file.open (QIODevice::WriteOnly);
//    file.write (buffer.data());
//    file.close ();

    // Create output
    imageResult.loadFromData(buffer.data());

  }

  // Deallocate
  if (inCodec) {
    opj_destroy_codec (inCodec);
  }
  opj_image_destroy (image);

  return success;
}
Пример #13
0
char* J2kConverter::encode(int16_t* data, unsigned int imageWidth, unsigned int imageHeight, size_t& outSize, float distoRatio) {
    opj_cparameters_t params;
    opj_image_cmptparm_t compParams;
    
    opj_set_default_encoder_parameters(&params);
    params.tcp_numlayers = 1;
    params.cp_fixed_quality = 1;
    params.tcp_distoratio[0] = distoRatio;
    
    params.cp_tx0 = 0;
    params.cp_ty0 = 0;
    params.tile_size_on = OPJ_FALSE;
    params.irreversible = true;

    params.numresolution = 1;
    params.prog_order = OPJ_LRCP;

    compParams.w = imageWidth;
    compParams.h = imageHeight;
    compParams.sgnd = 0;
    compParams.prec = 16;
    compParams.bpp = 16;
    compParams.x0 = 0;
    compParams.y0 = 0;
    compParams.dx = 1;
    compParams.dy = 1;
    
    opj_codec_t *codec = opj_create_compress(OPJ_CODEC_J2K);

    opj_set_info_handler(codec, infoCallback, nullptr);
    opj_set_warning_handler(codec, warningCallback, nullptr);
    opj_set_error_handler(codec, errorCallback, nullptr);

    opj_image_t *image = opj_image_create(1, &compParams, OPJ_CLRSPC_GRAY);
    if (!image) {
        opj_destroy_codec(codec);
        return nullptr;
    }
    
    unsigned int nPixels = imageWidth * imageHeight;
    for (unsigned int i = 0; i < nPixels; ++i) {
        image->comps[0].data[i] = data[i];
    }
    
    image->x0 = 0;
    image->y0 = 0;
    image->x1 = static_cast<OPJ_UINT32>(imageWidth);
    image->y1 = static_cast<OPJ_UINT32>(imageHeight);
    image->color_space = OPJ_CLRSPC_GRAY;
    
    if (!opj_setup_encoder(codec, &params, image)) {
        std::cout << "Could not set up encoder." << std::endl;
        opj_destroy_codec(codec);
        opj_image_destroy(image);
        return nullptr;
    }

    MemoryStream* ms = new MemoryStream;
    opj_stream_t *stream = createOpjMemoryStream(OPJ_FALSE, ms);
    if (!stream) {
        std::cout << "Could not set up stream" << std::endl;
        opj_destroy_codec(codec);
        opj_image_destroy(image);
        return nullptr;
    }

    if (!opj_start_compress(codec, image, stream)) {
        std::cout << "Could not start compression." << std::endl;
        opj_stream_destroy(stream);
        opj_destroy_codec(codec);
        opj_image_destroy(image);
        return nullptr;
    }

    if (!opj_encode(codec, stream)) {
        std::cout << "Could not encode data." << std::endl;
        opj_stream_destroy(stream);
        opj_destroy_codec(codec);
        opj_image_destroy(image);
        return nullptr;
    }

    if (!opj_end_compress(codec, stream)) {
        std::cout << "Could not end compression." << std::endl;
        opj_stream_destroy(stream);
        opj_destroy_codec(codec);
        opj_image_destroy(image);
        return nullptr;
    }

    outSize = ms->data.size();
    char* outData = new char[outSize];
    memcpy(outData, ms->data.data(), outSize);
    
    opj_stream_destroy(stream);
    opj_destroy_codec(codec);
    opj_image_destroy(image);

    delete ms;
    return outData;
}
Пример #14
0
int16_t* J2kConverter::decode(char* inData, size_t inSize, unsigned int& imageWidth, unsigned int& imageHeight , int16_t* outData) {

    opj_dparameters_t core;

    MemoryStream* ms = new MemoryStream;
    ms->data.resize(inSize, 0);
    memcpy(ms->data.data(), inData, inSize);

    opj_stream_t *stream = createOpjMemoryStream(OPJ_TRUE, ms);
    if (!stream) {
        std::cout << "Could not create in stream." << std::endl;
        delete ms;
        return nullptr;
    }

    opj_codec_t *codec = opj_create_decompress(OPJ_CODEC_J2K);
    opj_image_t *image = nullptr;
    
    opj_set_info_handler(codec, infoCallback, nullptr);
    opj_set_warning_handler(codec, warningCallback, nullptr);
    opj_set_error_handler(codec, errorCallback, nullptr);

    opj_set_default_decoder_parameters(&core);

    if ( !opj_setup_decoder(codec, &core) ){
        std::cout << "Could not set up decoder." << std::endl;
        opj_stream_destroy(stream);
        opj_destroy_codec(codec);
        delete ms;
        return nullptr;
    }

    if(! opj_read_header(stream, codec, &image)){
        std::cout << "Could not read header." << std::endl;
        opj_stream_destroy(stream);
        opj_destroy_codec(codec);
        opj_image_destroy(image);
        delete ms;
        return nullptr;
    }

    if (!(opj_decode(codec, stream, image))) {
        std::cout << "Could not decode image." << std::endl;
        opj_destroy_codec(codec);
        opj_stream_destroy(stream);
        opj_image_destroy(image);
        delete ms;
        return nullptr;
    }

    if (!opj_end_decompress(codec, stream)) {
        std::cout << "Could not end decompression." << std::endl;
        opj_destroy_codec(codec);
        opj_stream_destroy(stream);
        opj_image_destroy(image);
        delete ms;
        return nullptr;
    }


    imageWidth = image->x1 - image->x0;
    imageHeight = image->y1 - image->y0;
    unsigned int nPixels = imageWidth * imageHeight;
    
    if (outData == nullptr) {
        outData = new int16_t[nPixels];
    }

    for (unsigned int i = 0; i < nPixels; ++i) {
       outData[i] = image->comps[0].data[i];
    }
    
    opj_stream_destroy(stream);
    opj_destroy_codec(codec);
    opj_image_destroy(image);

    return outData; 
}
Пример #15
0
int main(int argc, char *argv[])
{
  const char * v = opj_version();

  const OPJ_COLOR_SPACE color_space = OPJ_CLRSPC_GRAY;
  unsigned int numcomps = 1;
  unsigned int i;
  unsigned int image_width = 256;
  unsigned int image_height = 256;

  opj_cparameters_t parameters;

  unsigned int subsampling_dx;
  unsigned int subsampling_dy;
  const char outputfile[] = "testempty2.j2k";

  opj_image_cmptparm_t cmptparm;
  opj_image_t *image;
  opj_codec_t* l_codec = 00;
  OPJ_BOOL bSuccess;
  opj_stream_t *l_stream = 00;
  (void)argc;
  (void)argv;

  opj_set_default_encoder_parameters(&parameters);
  parameters.cod_format = J2K_CFMT;
  puts(v);
  subsampling_dx = (unsigned int)parameters.subsampling_dx;
  subsampling_dy = (unsigned int)parameters.subsampling_dy;
  cmptparm.prec = 8;
  cmptparm.bpp = 8;
  cmptparm.sgnd = 0;
  cmptparm.dx = subsampling_dx;
  cmptparm.dy = subsampling_dy;
  cmptparm.w = image_width;
  cmptparm.h = image_height;
  strncpy(parameters.outfile, outputfile, sizeof(parameters.outfile)-1);

  image = opj_image_create(numcomps, &cmptparm, color_space);
  assert( image );

  for (i = 0; i < image_width * image_height; i++)
    {
    unsigned int compno;
    for(compno = 0; compno < numcomps; compno++)
      {
      image->comps[compno].data[i] = 0;
      }
    }

  /* catch events using our callbacks and give a local context */
  opj_set_info_handler(l_codec, info_callback,00);
  opj_set_warning_handler(l_codec, warning_callback,00);
  opj_set_error_handler(l_codec, error_callback,00);

  l_codec = opj_create_compress(OPJ_CODEC_J2K);
  opj_set_info_handler(l_codec, info_callback,00);
  opj_set_warning_handler(l_codec, warning_callback,00);
  opj_set_error_handler(l_codec, error_callback,00);

  opj_setup_encoder(l_codec, &parameters, image);

  l_stream = opj_stream_create_default_file_stream_v3(parameters.outfile,OPJ_FALSE);
  if( !l_stream )
    {
    fprintf( stderr, "Something went wrong during creation of stream\n" );
    opj_destroy_codec(l_codec);
    opj_image_destroy(image);
    opj_stream_destroy_v3(l_stream);
    return 1;
    }
  assert(l_stream);
  bSuccess = opj_start_compress(l_codec,image,l_stream);
  if( !bSuccess )
    {
    opj_stream_destroy_v3(l_stream);
    opj_destroy_codec(l_codec);
    opj_image_destroy(image);
    return 0;
    }

  assert( bSuccess );
  bSuccess = opj_encode(l_codec, l_stream);
  assert( bSuccess );
  bSuccess = opj_end_compress(l_codec, l_stream);
  assert( bSuccess );

  opj_stream_destroy_v3(l_stream);

  opj_destroy_codec(l_codec);
  opj_image_destroy(image);


  /* read back the generated file */
{
  opj_codec_t* d_codec = 00;
  opj_dparameters_t dparameters;

  d_codec = opj_create_decompress(OPJ_CODEC_J2K);
  opj_set_info_handler(d_codec, info_callback,00);
  opj_set_warning_handler(d_codec, warning_callback,00);
  opj_set_error_handler(d_codec, error_callback,00);

  bSuccess = opj_setup_decoder(d_codec, &dparameters);
  assert( bSuccess );

  l_stream = opj_stream_create_default_file_stream_v3(outputfile,1);
  assert( l_stream );

  bSuccess = opj_read_header(l_stream, d_codec, &image);
  assert( bSuccess );

  bSuccess = opj_decode(l_codec, l_stream, image);
  assert( bSuccess );

  bSuccess = opj_end_decompress(l_codec, l_stream);
  assert( bSuccess );

  opj_stream_destroy_v3(l_stream);

  opj_destroy_codec(d_codec);

  opj_image_destroy(image);
}

  puts( "end" );
  return 0;
}
Пример #16
0
/* -------------------------------------------------------------------------- */
int main(int argc, char *argv[])
{
    FILE *fout = NULL;

    opj_dparameters_t parameters;			/* Decompression parameters */
    opj_image_t* image = NULL;					/* Image structure */
    opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
    opj_stream_t *l_stream = NULL;				/* Stream */
    opj_codestream_info_v2_t* cstr_info = NULL;
    opj_codestream_index_t* cstr_index = NULL;

    int32_t num_images, imageno;
    img_fol_t img_fol;
    dircnt_t *dirptr = NULL;

#ifdef MSD
    bool l_go_on = true;
    uint32_t l_max_data_size = 1000;
    uint8_t * l_data = (uint8_t *) malloc(1000);
#endif

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

    /* Initialize img_fol */
    memset(&img_fol,0,sizeof(img_fol_t));
    img_fol.flag = OPJ_IMG_INFO | OPJ_J2K_MH_INFO | OPJ_J2K_MH_IND;

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

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

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

            if(!dirptr->filename_buf) {
                return EXIT_FAILURE;
            }

            for(it_image=0; it_image<num_images; it_image++) {
                dirptr->filename[it_image] = dirptr->filename_buf + it_image*OPJ_PATH_LEN;
            }
        }
        if(load_images(dirptr,img_fol.imgdirpath)==1) {
            return EXIT_FAILURE;
        }

        if (num_images==0) {
            fprintf(stdout,"Folder is empty\n");
            return EXIT_FAILURE;
        }
    } else {
        num_images=1;
    }

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

    /* Read the header of each image one by one */
    for(imageno = 0; imageno < num_images ; imageno++) {

        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 */
        /* ---------------------------------------- */

        l_stream = opj_stream_create_default_file_stream(parameters.infile,1);
        if (!l_stream) {
            fprintf(stderr, "ERROR -> failed to create the stream from the file %s\n",parameters.infile);
            return EXIT_FAILURE;
        }

        /* Read the JPEG2000 stream */
        /* ------------------------ */

        switch(parameters.decod_format) {
        case J2K_CFMT: {	/* JPEG-2000 codestream */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_J2K);
            break;
        }
        case JP2_CFMT: {	/* JPEG 2000 compressed image data */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JP2);
            break;
        }
        case JPT_CFMT: {	/* JPEG 2000, JPIP */
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JPT);
            break;
        }
        default:
            fprintf(stderr, "skipping file..\n");
            opj_stream_destroy(l_stream);
            continue;
        }

        /* catch events using our callbacks and give a local context */
        opj_set_info_handler(l_codec, info_callback,00);
        opj_set_warning_handler(l_codec, warning_callback,00);
        opj_set_error_handler(l_codec, error_callback,00);

        /* Setup the decoder decoding parameters using user parameters */
        if ( !opj_setup_decoder(l_codec, &parameters) ) {
            fprintf(stderr, "ERROR -> opj_dump: failed to setup the decoder\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            fclose(fout);
            return EXIT_FAILURE;
        }

        /* Read the main header of the codestream and if necessary the JP2 boxes*/
        if(! opj_read_header(l_stream, l_codec, &image)) {
            fprintf(stderr, "ERROR -> opj_dump: failed to read the header\n");
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            fclose(fout);
            return EXIT_FAILURE;
        }

        opj_dump_codec(l_codec, img_fol.flag, fout );

        cstr_info = opj_get_cstr_info(l_codec);

        cstr_index = opj_get_cstr_index(l_codec);

        /* close the byte stream */
        opj_stream_destroy(l_stream);

        /* free remaining structures */
        if (l_codec) {
            opj_destroy_codec(l_codec);
        }

        /* destroy the image header */
        opj_image_destroy(image);

        /* destroy the codestream index */
        opj_destroy_cstr_index(&cstr_index);

        /* destroy the codestream info */
        opj_destroy_cstr_info(&cstr_info);

    }

    /* Close the output file */
    fclose(fout);

    return EXIT_SUCCESS;
}
Пример #17
0
/* -------------------------------------------------------------------------- */
int jp2_decompress_main(char *infile, char *buf, int bufsize)
{
    int i;
    int *dataptr;

	opj_dparameters_t parameters;			/* decompression parameters */
	opj_image_t* image = NULL;
	opj_stream_t *l_stream = NULL;				/* Stream */
	opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
	opj_codestream_index_t* cstr_index = NULL;

	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	OPJ_INT32 num_images, imageno;
	img_fol_t img_fol;
	dircnt_t *dirptr = NULL;

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

	/* FIXME Initialize indexfilename and img_fol */
	*indexfilename = 0;

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

	/* parse input and get user encoding parameters */
	if (0 != parse_cmdline_decoder(&parameters,&img_fol, infile)) {
        return EXIT_FAILURE;
	}

    /* read the input file and put it in memory */
    /* ---------------------------------------- */

    l_stream = opj_stream_create_default_file_stream_v3(parameters.infile,1);
    if (!l_stream){
        return EXIT_FAILURE;
    }

    /* decode the JPEG2000 stream */
    /* ---------------------- */

    switch(parameters.decod_format) {
        case J2K_CFMT:	/* JPEG-2000 codestream */
        {
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_J2K);
            break;
        }
        case JP2_CFMT:	/* JPEG 2000 compressed image data */
        {
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JP2);
            break;
        }
        case JPT_CFMT:	/* JPEG 2000, JPIP */
        {
            /* Get a decoder handle */
            l_codec = opj_create_decompress(OPJ_CODEC_JPT);
            break;
        }
        default:
            fprintf(stderr, "skipping file..\n");
            opj_stream_destroy_v3(l_stream);
            return EXIT_FAILURE;
    }

    /* catch events using our callbacks and give a local context */
    opj_set_info_handler(l_codec, info_callback,00);
    opj_set_warning_handler(l_codec, warning_callback,00);
    opj_set_error_handler(l_codec, error_callback,00);

    /* Setup the decoder decoding parameters using user parameters */
    if ( !opj_setup_decoder(l_codec, &parameters) ){
        fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
        opj_stream_destroy_v3(l_stream);
        opj_destroy_codec(l_codec);
        return EXIT_FAILURE;
    }


    /* Read the main header of the codestream and if necessary the JP2 boxes*/
    if(! opj_read_header(l_stream, l_codec, &image)){
        fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
        opj_stream_destroy_v3(l_stream);
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        return EXIT_FAILURE;
    }

    if (!parameters.nb_tile_to_decode) {
        /* Optional if you want decode the entire image */
        if (!opj_set_decode_area(l_codec, image, parameters.DA_x0,
                parameters.DA_y0, parameters.DA_x1, parameters.DA_y1)){
            fprintf(stderr,	"ERROR -> opj_decompress: failed to set the decoded area\n");
            opj_stream_destroy_v3(l_stream);
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            return EXIT_FAILURE;
        }

        /* Get the decoded image */
        if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,	l_stream))) {
            fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
            opj_destroy_codec(l_codec);
            opj_stream_destroy_v3(l_stream);
            opj_image_destroy(image);
            return EXIT_FAILURE;
        }
    }
    else {

        /* It is just here to illustrate how to use the resolution after set parameters */
        /*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
            opj_destroy_codec(l_codec);
            opj_stream_destroy_v3(l_stream);
            opj_image_destroy(image);
            return EXIT_FAILURE;
        }*/

        if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
            fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
            opj_destroy_codec(l_codec);
            opj_stream_destroy_v3(l_stream);
            opj_image_destroy(image);
            return EXIT_FAILURE;
        }
        fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
    }

    /* Close the byte stream */
    opj_stream_destroy_v3(l_stream);

    if(image->color_space == OPJ_CLRSPC_SYCC){
        color_sycc_to_rgb(image); /* FIXME */
    }

    if( image->color_space != OPJ_CLRSPC_SYCC
        && image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
        && image->comps[1].dx != 1 )
        image->color_space = OPJ_CLRSPC_SYCC;
    else if (image->numcomps <= 2)
        image->color_space = OPJ_CLRSPC_GRAY;

    if(image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
        color_apply_icc_profile(image); /* FIXME */
#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 OPJ_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 /* OPJ_HAVE_LIBTIFF */
    case RAW_DFMT:			/* RAW */
        dataptr = &image->comps[0].data[0];
        char mask = 0xFF;
        for (i = 0; i < bufsize; i++) {
            *buf++ = *dataptr++ & mask;
        }
        /*
        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 RAWL_DFMT:			/* RAWL */
        if(imagetorawl(image, parameters.outfile)){
            fprintf(stdout,"Error generating rawl 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 OPJ_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 /* OPJ_HAVE_LIBPNG */
/* Can happen if output file is TIFF or PNG
* and OPJ_HAVE_LIBTIF or OPJ_HAVE_LIBPNG is undefined
*/
        default:
            fprintf(stderr,"Outfile %s not generated\n",parameters.outfile);
    }

    /* free remaining structures */
    if (l_codec) {
        opj_destroy_codec(l_codec);
    }


    /* free image data structure */
    opj_image_destroy(image);

    /* destroy the codestream index */
    opj_destroy_cstr_index(&cstr_index);

	return EXIT_SUCCESS;
}
Пример #18
0
bool ossim::opj_decode( std::ifstream* in,
                        const ossimIrect& rect,
                        ossim_uint32 resLevel,
                        ossim_int32 format, // OPJ_CODEC_FORMAT
                        std::streamoff fileOffset,
                        ossimImageData* tile)
{
   static const char MODULE[] = "ossimOpjDecoder::decode";

   bool status = false;

   if ( traceDebug() )
   {
      ossimNotify(ossimNotifyLevel_DEBUG)
         << MODULE << "entered...\nrect: " << rect
         << "\nresLevel: " << resLevel << std::endl;
   }
   
   // Need to check for NAN in rect
   if ( in && tile && !rect.hasNans())
   {
      in->seekg( fileOffset, std::ios_base::beg );

      opj_dparameters_t param;
      opj_codec_t*      codec = 0;
      opj_image_t*      image = 0;;
      opj_stream_t*     stream = 0;

      opj_user_istream* userStream = new opj_user_istream();
      userStream->m_str = in;
      userStream->m_offset = fileOffset;

      /* Set the length to avoid an assert */
      in->seekg(0, std::ios_base::end);

      // Fix: length must be passed in for nift blocks.
      userStream->m_length = in->tellg();

      // Set back to front:
      in->clear();
      in->seekg(fileOffset, std::ios_base::beg);
      
      stream = opj_stream_default_create(OPJ_TRUE);
      if (!stream)
      {
         opj_stream_destroy(stream);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_setup_decoder failed!";
         throw ossimException(errMsg);
      }
      
      opj_stream_set_read_function(stream, ossim_opj_istream_read);
      opj_stream_set_skip_function(stream, ossim_opj_istream_skip);
      opj_stream_set_seek_function(stream, ossim_opj_istream_seek);

      // Fix: length must be passed in for nift blocks.
      opj_stream_set_user_data_length(stream, userStream->m_length);
      
      opj_stream_set_user_data(stream, userStream,
                               ossim_opj_free_user_istream_data);

      opj_stream_set_user_data_length(stream, userStream->m_length);

      
      /* Set the default decoding parameters */
      opj_set_default_decoder_parameters(&param);

      param.decod_format = format;

      /** you may here add custom decoding parameters */
      /* do not use layer decoding limitations */
      param.cp_layer = 0;

      /* do not use resolutions reductions */
      param.cp_reduce = resLevel;

      codec = opj_create_decompress( (CODEC_FORMAT)format );

      // catch events using our callbacks and give a local context
      //opj_set_info_handler   (codec, ossim::opj_info_callback,   00);
      opj_set_info_handler   (codec, NULL,   00);
      opj_set_warning_handler(codec, ossim::opj_warning_callback,00);
      opj_set_error_handler  (codec, ossim::opj_error_callback,  00);

      // Setup the decoder decoding parameters using user parameters
      if ( opj_setup_decoder(codec, &param) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_setup_decoder failed!";
         throw ossimException(errMsg);
      }

      // Read the main header of the codestream and if necessary the JP2 boxes.
      if ( opj_read_header(stream, codec, &image) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);         
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_read_header failed!";
         throw ossimException(errMsg);
      }

      // tmp drb:
      // opj_stream_destroy(stream);
      // return;
      
      if ( opj_set_decoded_resolution_factor(codec, resLevel) == false)
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR:  opj_set_decoded_resolution_factor failed!";
         throw ossimException(errMsg);
      }

      //ossim_float32 res = resLevel;
      ossimIrect resRect = rect * (1 << resLevel);

      //std::cout << "resRect.ul(): " << resRect.ul()
      //          << "\nresRect.lr(): " << resRect.lr()
      //          << std::endl;

//      if ( opj_set_decode_area(codec, image, rect.ul().x, rect.ul().y,
//                               rect.lr().x+1, rect.lr().y+1) == false )
      if ( opj_set_decode_area(codec, image, resRect.ul().x, resRect.ul().y,
                               resRect.lr().x+1, resRect.lr().y+1) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_set_decode_area failed!";
         throw ossimException(errMsg);
      }

      // Get the decoded image:
      if ( opj_decode(codec, stream, image) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_decode failed!";
         throw ossimException(errMsg);
      }
      
      // ossim::print(std::cout, *image);
      if(image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
          color_apply_icc_profile(image); /* FIXME */
#endif
          free(image->icc_profile_buf);
          image->icc_profile_buf = NULL; image->icc_profile_len = 0;
      }

      status = ossim::copyOpjImage(image, tile);
      
#if 0
      ossim_uint32 tile_index      = 0;
      ossim_uint32 data_size       = 0;
      ossim_int32  current_tile_x0 = 0;
      ossim_int32  current_tile_y0 = 0;
      ossim_int32  current_tile_x1 = 0;
      ossim_int32  current_tile_y1 = 0;
      ossim_uint32 nb_comps        = 0;
      OPJ_BOOL go_on = 1;

      if ( opj_read_tile_header( codec,
                                 stream,
                                 &tile_index,
                                 &data_size,
                                 &current_tile_x0,
                                 &current_tile_y0,
                                 &current_tile_x1,
                                 &current_tile_y1,
                                 &nb_comps,
                                 &go_on) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_read_tile_header failed!";
         throw ossimException(errMsg);
      }
#endif

#if 0
      std::cout << "tile_index:      " << tile_index
                << "\ndata_size:       " << data_size
                << "\ncurrent_tile_x0: " << current_tile_x0
                << "\ncurrent_tile_y0: " << current_tile_y0
                << "\ncurrent_tile_x1: " << current_tile_x1
                << "\ncurrent_tile_y1: " << current_tile_y1
                << "\nnb_comps:        " << nb_comps
                << std::endl;
#endif

#if 0
      if ( opj_decode_tile_data(codec, tile_index,l_data,l_data_size,l_stream) == false)
      {
         opj_stream_destroy(l_stream);
         opj_destroy_codec(l_codec);
         opj_image_destroy(l_image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_read_tile_header failed!";
         throw ossimException(errMsg);
      }
#endif

#if 0
      
      if (opj_end_decompress(codec,stream) == false )
      {
         opj_stream_destroy(stream);
         opj_destroy_codec(codec);
         opj_image_destroy(image);
         std::string errMsg = MODULE;
         errMsg += " ERROR: opj_end_decompress failed!";
         throw ossimException(errMsg);
      } 

#endif
      
      /* Free memory */
      opj_stream_destroy(stream);
      opj_destroy_codec(codec);
      opj_image_destroy(image);

      // Tmp drb:
      if ( in->eof() )
      {
         in->clear();
      }
      in->seekg(fileOffset, std::ios_base::beg );
      
   } // Matches: if ( in && tile )

   return status;
   
} // End: ossim::opj_decode( ... )
Пример #19
0
static GstFlowReturn
gst_openjpeg_dec_handle_frame (GstVideoDecoder * decoder,
    GstVideoCodecFrame * frame)
{
  GstOpenJPEGDec *self = GST_OPENJPEG_DEC (decoder);
  GstFlowReturn ret = GST_FLOW_OK;
  gint64 deadline;
  GstMapInfo map;
#ifdef HAVE_OPENJPEG_1
  opj_dinfo_t *dec;
  opj_cio_t *io;
#else
  opj_codec_t *dec;
  opj_stream_t *stream;
  MemStream mstream;
#endif
  opj_image_t *image;
  GstVideoFrame vframe;
  opj_dparameters_t params;

  GST_DEBUG_OBJECT (self, "Handling frame");

  deadline = gst_video_decoder_get_max_decode_time (decoder, frame);
  if (deadline < 0) {
    GST_LOG_OBJECT (self, "Dropping too late frame: deadline %" G_GINT64_FORMAT,
        deadline);
    ret = gst_video_decoder_drop_frame (decoder, frame);
    return ret;
  }

  dec = opj_create_decompress (self->codec_format);
  if (!dec)
    goto initialization_error;

#ifdef HAVE_OPENJPEG_1
  if (G_UNLIKELY (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >=
          GST_LEVEL_TRACE)) {
    opj_event_mgr_t callbacks;

    callbacks.error_handler = gst_openjpeg_dec_opj_error;
    callbacks.warning_handler = gst_openjpeg_dec_opj_warning;
    callbacks.info_handler = gst_openjpeg_dec_opj_info;
    opj_set_event_mgr ((opj_common_ptr) dec, &callbacks, self);
  } else {
    opj_set_event_mgr ((opj_common_ptr) dec, NULL, NULL);
  }
#else
  if (G_UNLIKELY (gst_debug_category_get_threshold (GST_CAT_DEFAULT) >=
          GST_LEVEL_TRACE)) {
    opj_set_info_handler (dec, gst_openjpeg_dec_opj_info, self);
    opj_set_warning_handler (dec, gst_openjpeg_dec_opj_warning, self);
    opj_set_error_handler (dec, gst_openjpeg_dec_opj_error, self);
  } else {
    opj_set_info_handler (dec, NULL, NULL);
    opj_set_warning_handler (dec, NULL, NULL);
    opj_set_error_handler (dec, NULL, NULL);
  }
#endif

  params = self->params;
  if (self->ncomps)
    params.jpwl_exp_comps = self->ncomps;
  opj_setup_decoder (dec, &params);

  if (!gst_buffer_map (frame->input_buffer, &map, GST_MAP_READ))
    goto map_read_error;

#ifdef HAVE_OPENJPEG_1
  io = opj_cio_open ((opj_common_ptr) dec, map.data + (self->is_jp2c ? 8 : 0),
      map.size - (self->is_jp2c ? 8 : 0));
  if (!io)
    goto open_error;

  image = opj_decode (dec, io);
  if (!image)
    goto decode_error;
#else
  stream = opj_stream_create (4096, OPJ_TRUE);
  if (!stream)
    goto open_error;

  mstream.data = map.data + (self->is_jp2c ? 8 : 0);
  mstream.offset = 0;
  mstream.size = map.size - (self->is_jp2c ? 8 : 0);

  opj_stream_set_read_function (stream, read_fn);
  opj_stream_set_write_function (stream, write_fn);
  opj_stream_set_skip_function (stream, skip_fn);
  opj_stream_set_seek_function (stream, seek_fn);
  opj_stream_set_user_data (stream, &mstream);
  opj_stream_set_user_data_length (stream, mstream.size);

  image = NULL;
  if (!opj_read_header (stream, dec, &image))
    goto decode_error;

  if (!opj_decode (dec, stream, image))
    goto decode_error;
#endif

  gst_buffer_unmap (frame->input_buffer, &map);

  ret = gst_openjpeg_dec_negotiate (self, image);
  if (ret != GST_FLOW_OK)
    goto negotiate_error;

  ret = gst_video_decoder_allocate_output_frame (decoder, frame);
  if (ret != GST_FLOW_OK)
    goto allocate_error;

  if (!gst_video_frame_map (&vframe, &self->output_state->info,
          frame->output_buffer, GST_MAP_WRITE))
    goto map_write_error;

  self->fill_frame (&vframe, image);

  gst_video_frame_unmap (&vframe);

#ifdef HAVE_OPENJPEG_1
  opj_cio_close (io);
  opj_image_destroy (image);
  opj_destroy_decompress (dec);
#else
  opj_end_decompress (dec, stream);
  opj_stream_destroy (stream);
  opj_image_destroy (image);
  opj_destroy_codec (dec);
#endif

  ret = gst_video_decoder_finish_frame (decoder, frame);

  return ret;

initialization_error:
  {
    gst_video_codec_frame_unref (frame);
    GST_ELEMENT_ERROR (self, LIBRARY, INIT,
        ("Failed to initialize OpenJPEG decoder"), (NULL));
    return GST_FLOW_ERROR;
  }
map_read_error:
  {
#ifdef HAVE_OPENJPEG_1
    opj_destroy_decompress (dec);
#else
    opj_destroy_codec (dec);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to map input buffer"), (NULL));
    return GST_FLOW_ERROR;
  }
open_error:
  {
#ifdef HAVE_OPENJPEG_1
    opj_destroy_decompress (dec);
#else
    opj_destroy_codec (dec);
#endif
    gst_buffer_unmap (frame->input_buffer, &map);
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, LIBRARY, INIT,
        ("Failed to open OpenJPEG stream"), (NULL));
    return GST_FLOW_ERROR;
  }
decode_error:
  {
    if (image)
      opj_image_destroy (image);
#ifdef HAVE_OPENJPEG_1
    opj_cio_close (io);
    opj_destroy_decompress (dec);
#else
    opj_stream_destroy (stream);
    opj_destroy_codec (dec);
#endif
    gst_buffer_unmap (frame->input_buffer, &map);
    gst_video_codec_frame_unref (frame);

    GST_VIDEO_DECODER_ERROR (self, 1, STREAM, DECODE,
        ("Failed to decode OpenJPEG stream"), (NULL), ret);
    return ret;
  }
negotiate_error:
  {
    opj_image_destroy (image);
#ifdef HAVE_OPENJPEG_1
    opj_cio_close (io);
    opj_destroy_decompress (dec);
#else
    opj_stream_destroy (stream);
    opj_destroy_codec (dec);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, CORE, NEGOTIATION,
        ("Failed to negotiate"), (NULL));
    return ret;
  }
allocate_error:
  {
    opj_image_destroy (image);
#ifdef HAVE_OPENJPEG_1
    opj_cio_close (io);
    opj_destroy_decompress (dec);
#else
    opj_stream_destroy (stream);
    opj_destroy_codec (dec);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to allocate output buffer"), (NULL));
    return ret;
  }
map_write_error:
  {
    opj_image_destroy (image);
#ifdef HAVE_OPENJPEG_1
    opj_cio_close (io);
    opj_destroy_decompress (dec);
#else
    opj_stream_destroy (stream);
    opj_destroy_codec (dec);
#endif
    gst_video_codec_frame_unref (frame);

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to map output buffer"), (NULL));
    return GST_FLOW_ERROR;
  }
}
Пример #20
0
static BOOL DLL_CALLCONV
Save(FreeImageIO *io, FIBITMAP *dib, fi_handle handle, int page, int flags, void *data) {
	J2KFIO_t *fio = (J2KFIO_t*)data;
	if (dib && handle && fio) {
		BOOL bSuccess;
		opj_codec_t *c_codec = NULL;	// handle to a compressor
		opj_cparameters_t parameters;	// compression parameters
		opj_image_t *image = NULL;		// image to encode

		// get the OpenJPEG stream
		opj_stream_t *c_stream = fio->stream;

		// set encoding parameters to default values
		opj_set_default_encoder_parameters(&parameters);

		try {
			parameters.tcp_numlayers = 0;
			// if no rate entered, apply a 16:1 rate by default
			if(flags == J2K_DEFAULT) {
				parameters.tcp_rates[0] = (float)16;
			} else {
				// for now, the flags parameter is only used to specify the rate
				parameters.tcp_rates[0] = (float)(flags & 0x3FF);
			}
			parameters.tcp_numlayers++;
			parameters.cp_disto_alloc = 1;

			// convert the dib to a OpenJPEG image
			image = FIBITMAPToJ2KImage(s_format_id, dib, &parameters);
			if(!image) {
				return FALSE;
			}

			// decide if MCT should be used
			parameters.tcp_mct = (image->numcomps == 3) ? 1 : 0;

			// encode the destination image

			// get a J2K compressor handle
			c_codec = opj_create_compress(OPJ_CODEC_J2K);

			// configure the event callbacks
			// catch events using our callbacks (no local context needed here)
			opj_set_info_handler(c_codec, NULL, NULL);
			opj_set_warning_handler(c_codec, j2k_warning_callback, NULL);
			opj_set_error_handler(c_codec, j2k_error_callback, NULL);

			// setup the encoder parameters using the current image and using user parameters
			opj_setup_encoder(c_codec, &parameters, image);

			// encode the image
			bSuccess = opj_start_compress(c_codec, image, c_stream);
			if(bSuccess) {
				bSuccess = bSuccess && opj_encode(c_codec, c_stream);
				if(bSuccess) {
					bSuccess = bSuccess && opj_end_compress(c_codec, c_stream);
				}
			}
			if (!bSuccess) {
				throw "Failed to encode image";
			}

			// free remaining compression structures
			opj_destroy_codec(c_codec);
			
			// free image data
			opj_image_destroy(image);

			return TRUE;

		} catch (const char *text) {
			if(c_codec) opj_destroy_codec(c_codec);
			if(image) opj_image_destroy(image);
			FreeImage_OutputMessageProc(s_format_id, text);
			return FALSE;
		}
	}

	return FALSE;
}
Пример #21
0
static ImBuf *imb_load_jp2_stream(opj_stream_t *stream,
                                  const OPJ_CODEC_FORMAT format,
                                  int flags,
                                  char colorspace[IM_MAX_SPACE])
{
  if (format == OPJ_CODEC_UNKNOWN) {
    return NULL;
  }

  struct ImBuf *ibuf = NULL;
  bool use_float = false; /* for precision higher then 8 use float */
  bool use_alpha = false;

  long signed_offsets[4] = {0, 0, 0, 0};
  int float_divs[4] = {1, 1, 1, 1};

  unsigned int i, i_next, w, h, planes;
  unsigned int y;
  int *r, *g, *b, *a; /* matching 'opj_image_comp.data' type */

  opj_dparameters_t parameters; /* decompression parameters */

  opj_image_t *image = NULL;
  opj_codec_t *codec = NULL; /* handle to a decompressor */

  /* both 8, 12 and 16 bit JP2Ks are default to standard byte colorspace */
  colorspace_set_default_role(colorspace, IM_MAX_SPACE, COLOR_ROLE_DEFAULT_BYTE);

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

  /* JPEG 2000 compressed image data */

  /* get a decoder handle */
  codec = opj_create_decompress(format);

  /* configure the event callbacks (not required) */
  opj_set_error_handler(codec, error_callback, stderr);
  opj_set_warning_handler(codec, warning_callback, stderr);
#ifdef DEBUG /* too noisy */
  opj_set_info_handler(codec, info_callback, stderr);
#endif

  /* setup the decoder decoding parameters using the current image and user parameters */
  if (opj_setup_decoder(codec, &parameters) == false) {
    goto finally;
  }

  if (opj_read_header(stream, codec, &image) == false) {
    printf("OpenJPEG error: failed to read the header\n");
    goto finally;
  }

  /* decode the stream and fill the image structure */
  if (opj_decode(codec, stream, image) == false) {
    fprintf(stderr, "ERROR -> j2k_to_image: failed to decode image!\n");
    goto finally;
  }

  if ((image->numcomps * image->x1 * image->y1) == 0) {
    fprintf(stderr, "\nError: invalid raw image parameters\n");
    goto finally;
  }

  w = image->comps[0].w;
  h = image->comps[0].h;

  switch (image->numcomps) {
    case 1: /* Grayscale */
    case 3: /* Color */
      planes = 24;
      use_alpha = false;
      break;
    default:       /* 2 or 4 - Grayscale or Color + alpha */
      planes = 32; /* grayscale + alpha */
      use_alpha = true;
      break;
  }

  i = image->numcomps;
  if (i > 4) {
    i = 4;
  }

  while (i) {
    i--;

    if (image->comps[i].prec > 8) {
      use_float = true;
    }

    if (image->comps[i].sgnd) {
      signed_offsets[i] = 1 << (image->comps[i].prec - 1);
    }

    /* only needed for float images but dosnt hurt to calc this */
    float_divs[i] = (1 << image->comps[i].prec) - 1;
  }

  ibuf = IMB_allocImBuf(w, h, planes, use_float ? IB_rectfloat : IB_rect);

  if (ibuf == NULL) {
    goto finally;
  }

  ibuf->ftype = IMB_FTYPE_JP2;
  if (1 /* is_jp2 */) {
    ibuf->foptions.flag |= JP2_JP2;
  }
  else {
    ibuf->foptions.flag |= JP2_J2K;
  }

  if (use_float) {
    float *rect_float = ibuf->rect_float;

    if (image->numcomps < 3) {
      r = image->comps[0].data;
      a = (use_alpha) ? image->comps[1].data : NULL;

      /* grayscale 12bits+ */
      if (use_alpha) {
        a = image->comps[1].data;
        PIXEL_LOOPER_BEGIN (rect_float) {
          rect_float[0] = rect_float[1] = rect_float[2] = (float)(r[i] + signed_offsets[0]) /
                                                          float_divs[0];
          rect_float[3] = (a[i] + signed_offsets[1]) / float_divs[1];
        }
        PIXEL_LOOPER_END;
      }
      else {
        PIXEL_LOOPER_BEGIN (rect_float) {
          rect_float[0] = rect_float[1] = rect_float[2] = (float)(r[i] + signed_offsets[0]) /
                                                          float_divs[0];
          rect_float[3] = 1.0f;
        }
        PIXEL_LOOPER_END;
      }
    }
Пример #22
0
int main (int argc, char *argv[])
{
	opj_dparameters_t l_param;
	opj_codec_t * l_codec;
	opj_image_t * l_image;
	FILE * l_file;
	opj_stream_t * l_stream;
	OPJ_UINT32 l_data_size;
	OPJ_UINT32 l_max_data_size = 1000;
	OPJ_UINT32 l_tile_index;
	OPJ_BYTE * l_data = (OPJ_BYTE *) malloc(1000);
	opj_bool l_go_on = OPJ_TRUE;
	OPJ_INT32 l_tile_x0,l_tile_y0;
	OPJ_UINT32 l_tile_width,l_tile_height,l_nb_tiles_x,l_nb_tiles_y,l_nb_comps;
	OPJ_INT32 l_current_tile_x0,l_current_tile_y0,l_current_tile_x1,l_current_tile_y1;

  int da_x0=0;
  int da_y0=0;
  int da_x1=1000;
  int da_y1=1000;
  char input_file[64];
	
  /* should be test_tile_decoder 0 0 1000 1000 tte1.j2k */
  if( argc == 6 )
    {
    da_x0=atoi(argv[1]);
    da_y0=atoi(argv[2]);
    da_x1=atoi(argv[3]);
    da_y1=atoi(argv[4]);
    strcpy(input_file,argv[5]);
    }
  else
    {
    da_x0=0;
    da_y0=0;
    da_x1=1000;
    da_y1=1000;
    strcpy(input_file,"test.j2k");
    }

	if
		(! l_data)
	{
		return 1;
	}
	opj_set_default_decoder_parameters(&l_param);

	/** you may here add custom decoding parameters */
	/* do not use layer decoding limitations */
	l_param.cp_layer = 0;

	/* do not use resolutions reductions */
	l_param.cp_reduce = 0;

	/* to decode only a part of the image data */
	//opj_restrict_decoding(&l_param,0,0,1000,1000);
	
	l_codec = opj_create_decompress_v2(CODEC_J2K);
	if
		(! l_codec)
	{
		free(l_data);
		return 1;
	}

	/* catch events using our callbacks and give a local context */		
	opj_set_info_handler(l_codec, info_callback,00);
	opj_set_warning_handler(l_codec, warning_callback,00);
	opj_set_error_handler(l_codec, error_callback,00);
	
	if
		(! opj_setup_decoder_v2(l_codec,&l_param))
	{
		free(l_data);
		opj_destroy_codec(l_codec);
		return 1;
	}
	
	l_file = fopen(input_file,"rb");
	if
		(! l_file)
	{
		fprintf(stdout, "Error opening input file\n");
		free(l_data);
		opj_destroy_codec(l_codec);
		return 1;
	}

	l_stream = opj_stream_create_default_file_stream(l_file,OPJ_TRUE);

	if
		(! opj_read_header(l_stream, l_codec, &l_image))
	{
		free(l_data);
		opj_stream_destroy(l_stream);
		fclose(l_file);
		opj_destroy_codec(l_codec);
		return 1;
	}
	printf("Setting decoding area to %d,%d,%d,%d\n", da_x0, da_y0, da_x1, da_y1);
	opj_set_decode_area(l_codec, l_image, da_x0, da_y0, da_x1, da_y1);
	while
		(l_go_on)
	{
		if
			(! opj_read_tile_header(
						l_codec,
            l_stream,
						&l_tile_index,
						&l_data_size,
						&l_current_tile_x0,
						&l_current_tile_y0,
						&l_current_tile_x1,
						&l_current_tile_y1,
						&l_nb_comps,
						&l_go_on))
		{
			free(l_data);
			opj_stream_destroy(l_stream);
			fclose(l_file);
			opj_destroy_codec(l_codec);
			opj_image_destroy(l_image);
			return 1;
		}
		if
			(l_go_on)
		{
			if
				(l_data_size > l_max_data_size)
			{
				l_data = (OPJ_BYTE *) realloc(l_data,l_data_size);
				if
					(! l_data)
				{
					opj_stream_destroy(l_stream);
					fclose(l_file);
					opj_destroy_codec(l_codec);
					opj_image_destroy(l_image);
					return 1;
				}
				l_max_data_size = l_data_size;
			}

			if
				(! opj_decode_tile_data(l_codec,l_tile_index,l_data,l_data_size,l_stream))
			{
				free(l_data);
				opj_stream_destroy(l_stream);
				fclose(l_file);
				opj_destroy_codec(l_codec);
				opj_image_destroy(l_image);
				return 1;
			}
			/** now should inspect image to know the reduction factor and then how to behave with data */
		}
	}
	if
		(! opj_end_decompress(l_codec,l_stream))
	{
		free(l_data);
		opj_stream_destroy(l_stream);
		fclose(l_file);
		opj_destroy_codec(l_codec);
		opj_image_destroy(l_image);
		return 1;
	}
	free(l_data);
	opj_stream_destroy(l_stream);
	fclose(l_file);
	opj_destroy_codec(l_codec);
	opj_image_destroy(l_image);

	// Print profiling
	//PROFPRINT();

	return 0;
}
Пример #23
0
void* OPJSupport::decompressJPEG2KWithBuffer(void* inputBuffer,
                                             void* jp2Data,
                                             long jp2DataSize,
                                             long *decompressedBufferSize,
                                             int *colorModel)
{
    //decoderMutex.lock();
    
    opj_dparameters_t parameters;
    int i;
    int width, height;
    OPJ_BOOL hasAlpha, fails = OPJ_FALSE;
    OPJ_CODEC_FORMAT codec_format;
    unsigned char rc, gc, bc, ac;
    
    if (jp2DataSize<12)
    {
        //decoderMutex.unlock();
        
        return 0;
    }
    
    /*-----------------------------------------------*/
    
    decode_info_t decodeInfo;
    memset(&decodeInfo, 0, sizeof(decode_info_t));
    
    opj_set_default_decoder_parameters(&parameters);
    parameters.decod_format = buffer_format(jp2Data);
    
    // Create the stream
    opj_buffer_info_t bufferInfo;
    bufferInfo.cur = bufferInfo.buf = (OPJ_BYTE *)jp2Data;
    bufferInfo.len = (OPJ_SIZE_T) jp2DataSize;
    // Create the stream
    decodeInfo.stream = opj_stream_create_buffer_stream(&bufferInfo , OPJ_STREAM_READ);
    
    
    //GROK
    //decodeInfo.stream = opj_stream_create_buffer_stream((OPJ_BYTE *)jp2Data, (OPJ_SIZE_T) jp2DataSize , OPJ_STREAM_READ);
    
    
    if (!decodeInfo.stream)
    {
        fprintf(stderr,"%s:%d:\n\tNO decodeInfo.stream\n",__FILE__,__LINE__);
        
        //decoderMutex.unlock();
        
        return NULL;
    }
    
    /*-----------------------------------------------*/
    
    switch (parameters.decod_format)
    {
        case J2K_CFMT:                      /* JPEG-2000 codestream */
            codec_format = OPJ_CODEC_J2K;
            break;
            
        case JP2_CFMT:                      /* JPEG 2000 compressed image data */
            codec_format = OPJ_CODEC_JP2;
            break;
            
        case JPT_CFMT:                      /* JPEG 2000, JPIP */
            codec_format = OPJ_CODEC_JPT;
            break;
            
        case -1:
            
        default:
            
            release(&decodeInfo);
            
            fprintf(stderr,"%s:%d: decode format missing\n",__FILE__,__LINE__);
            
             //decoderMutex.unlock();
            
            return NULL;
    }
    
    /*-----------------------------------------------*/
    
    while(1)
    {
        int user_changed_tile=0, user_changed_reduction=0;
        int max_tiles=0, max_reduction=0;
        fails = OPJ_TRUE;
        
        decodeInfo.codec = opj_create_decompress(codec_format);
        if (decodeInfo.codec == NULL)
        {
            fprintf(stderr,"%s:%d:\n\tNO codec\n",__FILE__,__LINE__);
            break;
        }
        
#ifdef OPJ_VERBOSE
        opj_set_info_handler(decodeInfo.codec, info_callback, this);
        opj_set_warning_handler(decodeInfo.codec, warning_callback, this);
#endif
        opj_set_error_handler(decodeInfo.codec, error_callback, this);
        
        // Setup the decoder decoding parameters
        if ( !opj_setup_decoder(decodeInfo.codec, &parameters))
        {
            fprintf(stderr,"%s:%d:\n\topj_setup_decoder failed\n",__FILE__,__LINE__);
            break;
        }
        
        if (user_changed_tile && user_changed_reduction)
        {
            int reduction=0;
            opj_set_decoded_resolution_factor(decodeInfo.codec, reduction);
        }
        
        /* Read the main header of the codestream and if necessary the JP2 boxes
         * see openjpeg.c
         * For OPJ_CODEC_JP2 it will call 'opj_jp2_read_header()' in jp2.c:2276
         * then call 'opj_j2k_read_header()'
         */
        if( !opj_read_header(decodeInfo.stream, decodeInfo.codec, &(decodeInfo.image)))
        {
            fprintf(stderr,"%s:%d:\n\topj_read_header failed\n",__FILE__,__LINE__);
            break;
        }
        
        if ( !(user_changed_tile && user_changed_reduction)
            || (max_tiles <= 0) || (max_reduction <= 0) )
        {
            decodeInfo.cstr_info = opj_get_cstr_info(decodeInfo.codec);
            
            max_reduction = decodeInfo.cstr_info->m_default_tile_info.tccp_info->numresolutions;
            max_tiles = decodeInfo.cstr_info->tw * decodeInfo.cstr_info->th;
            
            decodeInfo.cstr_index = opj_get_cstr_index(decodeInfo.codec);
        }
        
        if (!parameters.nb_tile_to_decode)
        {
            int user_changed_area=0;
            
            if(user_changed_area)
            {
                
            }
            
            /* Optional if you want decode the entire image */
            if (!opj_set_decode_area(decodeInfo.codec, decodeInfo.image,
                                     (OPJ_INT32)parameters.DA_x0,
                                     (OPJ_INT32)parameters.DA_y0,
                                     (OPJ_INT32)parameters.DA_x1,
                                     (OPJ_INT32)parameters.DA_y1)) {
                fprintf(stderr,"%s:%d:\n\topj_set_decode_area failed\n",__FILE__,__LINE__);
                break;
            }
            
            /* Get the decoded image */
            if (!opj_decode(decodeInfo.codec, decodeInfo.stream, decodeInfo.image)) {
                fprintf(stderr,"%s:%d:\n\topj_decode failed\n",__FILE__,__LINE__);
                
                //decoderMutex.unlock();
                
                return NULL;
            }
            
            if (!opj_end_decompress(decodeInfo.codec, decodeInfo.stream)) {
                fprintf(stderr,"%s:%d:\n\topj_end_decompress failed\n",__FILE__,__LINE__);
                break;
            }
            
        }
        else
        {
            if (!opj_get_decoded_tile(decodeInfo.codec, decodeInfo.stream, decodeInfo.image, parameters.tile_index))
            {
                fprintf(stderr,"%s:%d:\n\topj_get_decoded_tile failed\n",__FILE__,__LINE__);
                break;
            }
        }
        
        fails = OPJ_FALSE;
        break;
    } // while
    
    decodeInfo.deleteImage = fails;
    
    if (fails)
    {
        //decoderMutex.unlock();
        
        return NULL;
    }
    
    decodeInfo.deleteImage = OPJ_TRUE;
    
    if(decodeInfo.image->color_space == OPJ_CLRSPC_SYCC)
    {
        //disable for now
        //color_sycc_to_rgb(decodeInfo.image);
    }
    
    if (decodeInfo.image->color_space != OPJ_CLRSPC_SYCC
        && decodeInfo.image->numcomps == 3
        && decodeInfo.image->comps[0].dx == decodeInfo.image->comps[0].dy
        && decodeInfo.image->comps[1].dx != 1)
    {
        decodeInfo.image->color_space = OPJ_CLRSPC_SYCC;
    }
    else if(decodeInfo.image->numcomps <= 2)
    {
        decodeInfo.image->color_space = OPJ_CLRSPC_GRAY;
    }
    
    if (decodeInfo.image->icc_profile_buf)
    {
#if defined(HAVE_LIBLCMS1) || defined(HAVE_LIBLCMS2)
        color_apply_icc_profile(decodeInfo.image);
#endif
        free(decodeInfo.image->icc_profile_buf);
        decodeInfo.image->icc_profile_buf = NULL;
        decodeInfo.image->icc_profile_len = 0;
    }
    
    //---
    
    width = decodeInfo.image->comps[0].w;
    height = decodeInfo.image->comps[0].h;
    
    long depth = (decodeInfo.image->comps[0].prec + 7)/8;
    long decompressSize = width * height * decodeInfo.image->numcomps * depth;
    if (decompressedBufferSize)
        *decompressedBufferSize = decompressSize;;
    
    if (!inputBuffer )
    {
        inputBuffer =  malloc(decompressSize);
    }
    
    if (colorModel)
        *colorModel = 0;
    
    if ((decodeInfo.image->numcomps >= 3
         && decodeInfo.image->comps[0].dx == decodeInfo.image->comps[1].dx
         && decodeInfo.image->comps[1].dx == decodeInfo.image->comps[2].dx
         && decodeInfo.image->comps[0].dy == decodeInfo.image->comps[1].dy
         && decodeInfo.image->comps[1].dy == decodeInfo.image->comps[2].dy
         && decodeInfo.image->comps[0].prec == decodeInfo.image->comps[1].prec
         && decodeInfo.image->comps[1].prec == decodeInfo.image->comps[2].prec
         )/* RGB[A] */
        ||
        (decodeInfo.image->numcomps == 2
         && decodeInfo.image->comps[0].dx == decodeInfo.image->comps[1].dx
         && decodeInfo.image->comps[0].dy == decodeInfo.image->comps[1].dy
         && decodeInfo.image->comps[0].prec == decodeInfo.image->comps[1].prec
         )
        ) /* GA */
    {
        int  has_alpha4, has_alpha2, has_rgb;
        int *red, *green, *blue, *alpha;
        
        if (colorModel)
            *colorModel = 1;
        
        alpha = NULL;
        
        has_rgb = (decodeInfo.image->numcomps == 3);
        has_alpha4 = (decodeInfo.image->numcomps == 4);
        has_alpha2 = (decodeInfo.image->numcomps == 2);
        hasAlpha = (has_alpha4 || has_alpha2);
        
        if(has_rgb)
        {
            red = decodeInfo.image->comps[0].data;
            green = decodeInfo.image->comps[1].data;
            blue = decodeInfo.image->comps[2].data;
            
            if(has_alpha4)
            {
                alpha = decodeInfo.image->comps[3].data;
            }
            
        }	/* if(has_rgb) */
        else
        {
            red = green = blue = decodeInfo.image->comps[0].data;
            if(has_alpha2)
            {
                alpha = decodeInfo.image->comps[1].data;
            }
        }	/* if(has_rgb) */
        
        ac = 255;/* 255: FULLY_OPAQUE; 0: FULLY_TRANSPARENT */
        
        unsigned char* ptrIBody = (unsigned char*)inputBuffer;
        for(i = 0; i < width*height; i++)
        {
            rc = (unsigned char)*red++;
            gc = (unsigned char)*green++;
            bc = (unsigned char)*blue++;
            if(hasAlpha)
            {
                ac = (unsigned char)*alpha++;;
            }
            
            /*                         A        R          G       B
             */
            //*ptrIBody++ = (int)((ac<<24) | (rc<<16) | (gc<<8) | bc);
            *ptrIBody = rc;
            ptrIBody++;
            *ptrIBody = gc;
            ptrIBody++;
            *ptrIBody = bc;
            ptrIBody++;
            if (hasAlpha)
            {
                *ptrIBody = ac;
                ptrIBody++;
            }
        }	/* for(i) */
    }/* if (decodeInfo.image->numcomps >= 3  */
    else if(decodeInfo.image->numcomps == 1) /* Grey */
    {
        /* 1 component 8 or 16 bpp decodeInfo.image
         */
        int *grey = decodeInfo.image->comps[0].data;
        if(decodeInfo.image->comps[0].prec <= 8)
        {
            char* ptrBBody = (char*)inputBuffer;
            for(i=0; i<width*height; i++)
            {
                *ptrBBody++ = *grey++;
            }
            /* Replace image8 buffer:
             */
        }
        else /* prec[9:16] */
        {
            int *grey = decodeInfo.image->comps[0].data;
            //int ushift = 0, dshift = 0, force16 = 0;
            
            short* ptrSBody = (short*)inputBuffer;
            
            for(i=0; i<width*height; i++)
            {
                //disable shift up for signed data: don't know why we are doing this
                *ptrSBody++ = *grey++;
            }
            /* Replace image16 buffer:
             */
        }
    }
    else
    {
        int *grey;
        
        fprintf(stderr,"%s:%d:Can show only first component of decodeInfo.image\n"
                "  components(%d) prec(%d) color_space[%d](%s)\n"
                "  RECT(%d,%d,%d,%d)\n",__FILE__,__LINE__,decodeInfo.image->numcomps,
                decodeInfo.image->comps[0].prec,
                decodeInfo.image->color_space,clr_space(decodeInfo.image->color_space),
                decodeInfo.image->x0,decodeInfo.image->y0,decodeInfo.image->x1,decodeInfo.image->y1 );
        
        for(i = 0; i < decodeInfo.image->numcomps; ++i)
        {
            fprintf(stderr,"[%d]dx(%d) dy(%d) w(%d) h(%d) signed(%u)\n",i,
                    decodeInfo.image->comps[i].dx ,decodeInfo.image->comps[i].dy,
                    decodeInfo.image->comps[i].w,decodeInfo.image->comps[i].h,
                    decodeInfo.image->comps[i].sgnd);
        }
        
        /* 1 component 8 or 16 bpp decodeInfo.image
         */
        grey = decodeInfo.image->comps[0].data;
        if(decodeInfo.image->comps[0].prec <= 8)
        {
            char* ptrBBody = (char*)inputBuffer;
            for(i=0; i<width*height; i++)
            {
                *ptrBBody++ = *grey++;
            }
            /* Replace image8 buffer:
             */
        }
        else /* prec[9:16] */
        {
            int *grey;
            //int ushift = 0, dshift = 0, force16 = 0;
            
            grey = decodeInfo.image->comps[0].data;
            
            short* ptrSBody = (short*)inputBuffer;
            
            for(i=0; i<width*height; i++)
            {
                *ptrSBody++ = *grey++;
            }
            /* Replace image16 buffer:
             */
        }
    }
    
    release(&decodeInfo);
    opj_destroy_cstr_index(&(decodeInfo.cstr_index));
    
    //decoderMutex.unlock();
    
    return inputBuffer;
}
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
	FILE *fsrc = NULL;

	opj_dparameters_t parameters;			/* decompression parameters */
	opj_image_t* image = NULL;
	opj_stream_t *l_stream = NULL;				/* Stream */
	opj_codec_t* l_codec = NULL;				/* Handle to a decompressor */
	opj_codestream_index_t* cstr_index = NULL;

	char indexfilename[OPJ_PATH_LEN];	/* index file name */

	OPJ_INT32 num_images, imageno;
	img_fol_t img_fol;
	dircnt_t *dirptr = NULL;
  int failed = 0;

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

	/* FIXME Initialize indexfilename and img_fol */
	*indexfilename = 0;

	/* Initialize img_fol */
	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 EXIT_FAILURE;
	}

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

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

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

	/*Decoding image one by one*/
	for(imageno = 0; imageno < num_images ; imageno++)	{

		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 EXIT_FAILURE;
		}

		l_stream = opj_stream_create_default_file_stream(fsrc,1);
		if (!l_stream){
			fclose(fsrc);
			fprintf(stderr, "ERROR -> failed to create the stream from the file\n");
			return EXIT_FAILURE;
		}

		/* decode the JPEG2000 stream */
		/* ---------------------- */

		switch(parameters.decod_format) {
			case J2K_CFMT:	/* JPEG-2000 codestream */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_J2K);
				break;
			}
			case JP2_CFMT:	/* JPEG 2000 compressed image data */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JP2);
				break;
			}
			case JPT_CFMT:	/* JPEG 2000, JPIP */
			{
				/* Get a decoder handle */
				l_codec = opj_create_decompress(OPJ_CODEC_JPT);
				break;
			}
			default:
				fprintf(stderr, "skipping file..\n");
				opj_stream_destroy(l_stream);
				continue;
		}

		/* catch events using our callbacks and give a local context */		
		opj_set_info_handler(l_codec, info_callback,00);
		opj_set_warning_handler(l_codec, warning_callback,00);
		opj_set_error_handler(l_codec, error_callback,00);

		/* Setup the decoder decoding parameters using user parameters */
		if ( !opj_setup_decoder(l_codec, &parameters) ){
			fprintf(stderr, "ERROR -> opj_compress: failed to setup the decoder\n");
			opj_stream_destroy(l_stream);
			fclose(fsrc);
			opj_destroy_codec(l_codec);
			return EXIT_FAILURE;
		}


		/* Read the main header of the codestream and if necessary the JP2 boxes*/
		if(! opj_read_header(l_stream, l_codec, &image)){
			fprintf(stderr, "ERROR -> opj_decompress: failed to read the header\n");
			opj_stream_destroy(l_stream);
			fclose(fsrc);
			opj_destroy_codec(l_codec);
			opj_image_destroy(image);
			return EXIT_FAILURE;
		}

		if (!parameters.nb_tile_to_decode) {
			/* Optional if you want decode the entire image */
			if (!opj_set_decode_area(l_codec, image, (OPJ_INT32)parameters.DA_x0,
					(OPJ_INT32)parameters.DA_y0, (OPJ_INT32)parameters.DA_x1, (OPJ_INT32)parameters.DA_y1)){
				fprintf(stderr,	"ERROR -> opj_decompress: failed to set the decoded area\n");
				opj_stream_destroy(l_stream);
				opj_destroy_codec(l_codec);
				opj_image_destroy(image);
				fclose(fsrc);
				return EXIT_FAILURE;
			}

			/* Get the decoded image */
			if (!(opj_decode(l_codec, l_stream, image) && opj_end_decompress(l_codec,	l_stream))) {
				fprintf(stderr,"ERROR -> opj_decompress: failed to decode image!\n");
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				fclose(fsrc);
				return EXIT_FAILURE;
			}
		}
		else {

			/* It is just here to illustrate how to use the resolution after set parameters */
			/*if (!opj_set_decoded_resolution_factor(l_codec, 5)) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to set the resolution factor tile!\n");
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				fclose(fsrc);
				return EXIT_FAILURE;
			}*/

			if (!opj_get_decoded_tile(l_codec, l_stream, image, parameters.tile_index)) {
				fprintf(stderr, "ERROR -> opj_decompress: failed to decode tile!\n");
				opj_destroy_codec(l_codec);
				opj_stream_destroy(l_stream);
				opj_image_destroy(image);
				fclose(fsrc);
				return EXIT_FAILURE;
			}
			fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
		}

		/* Close the byte stream */
		opj_stream_destroy(l_stream);
		fclose(fsrc);

		if(image->color_space == OPJ_CLRSPC_SYCC){
			color_sycc_to_rgb(image); /* FIXME */
		}
		
		if( image->color_space != OPJ_CLRSPC_SYCC 
			&& image->numcomps == 3 && image->comps[0].dx == image->comps[0].dy
			&& image->comps[1].dx != 1 )
			image->color_space = OPJ_CLRSPC_SYCC;
		else if (image->numcomps <= 2)
			image->color_space = OPJ_CLRSPC_GRAY;

		if(image->icc_profile_buf) {
#if defined(OPJ_HAVE_LIBLCMS1) || defined(OPJ_HAVE_LIBLCMS2)
			color_apply_icc_profile(image); /* FIXME */
#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(stderr,"Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
				fprintf(stdout,"Generated Outfile %s\n",parameters.outfile);
			}
			break;

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

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

		case RAWL_DFMT:			/* RAWL */
			if(imagetorawl(image, parameters.outfile)){
				fprintf(stderr,"Error generating rawl file. Outfile %s not generated\n",parameters.outfile);
        failed = 1;
			}
			else {
				fprintf(stdout,"Successfully generated Outfile %s\n",parameters.outfile);
			}
			break;

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

		/* free remaining structures */
		if (l_codec) {
			opj_destroy_codec(l_codec);
		}


		/* free image data structure */
		opj_image_destroy(image);

		/* destroy the codestream index */
		opj_destroy_cstr_index(&cstr_index);

	}
	return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Пример #25
0
unsigned char *
OPJSupport::compressJPEG2K(void *data,
                           int samplesPerPixel,
                           int rows,
                           int columns,
                           int bitsstored, //precision,
                           unsigned char bitsAllocated,
                           bool sign,
                           int rate,
                           long *compressedDataSize)
{
    //enconderMutex.lock();
    
    opj_cparameters_t parameters;
    
    opj_stream_t *l_stream = 00;
    opj_codec_t* l_codec = 00;
    opj_image_t *image = NULL;
    
    OPJ_BOOL bSuccess;
    OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
    OPJ_UINT32 l_nb_tiles = 4;
    
    OPJ_BOOL fails = OPJ_FALSE;
    OPJ_CODEC_FORMAT codec_format;
    
    memset(&parameters, 0, sizeof(parameters));
    opj_set_default_encoder_parameters(&parameters);
    parameters.outfile[0] = '\0';
    parameters.tcp_numlayers = 1;
    parameters.cp_disto_alloc = 1;
    parameters.tcp_rates[0] = rate;
    parameters.cod_format = JP2_CFMT; //JP2_CFMT; //J2K_CFMT;
    OPJ_BOOL forceJ2K = (parameters.cod_format == J2K_CFMT ? OPJ_FALSE:(((OPJ_TRUE /*force here*/))));
    
#ifdef WITH_OPJ_FILE_STREAM
    tmpnam(parameters.outfile);
#endif
    
    image = rawtoimage( (char*) data,
                       &parameters,
                       static_cast<int>( columns*rows*samplesPerPixel*bitsAllocated/8), // [data length], fragment_size
                       columns, rows,
                       samplesPerPixel,
                       bitsAllocated,
                       bitsstored,
                       sign,
                       /*quality,*/ 0);
    
    if (image == NULL)
    {
        /* close and free the byte stream */
        if (l_stream) opj_stream_destroy(l_stream);
        
        /* free remaining compression structures */
        if (l_codec) opj_destroy_codec(l_codec);
        
        /* free image data */
        if (image) opj_image_destroy(image);
        
        *compressedDataSize = 0;
        
        //enconderMutex.unlock();
        
        return NULL;
    }
    
    /*-----------------------------------------------*/
    
    switch (parameters.cod_format)
    {
        case J2K_CFMT:                      /* JPEG-2000 codestream */
            codec_format = OPJ_CODEC_J2K;
            break;
            
        case JP2_CFMT:                      /* JPEG 2000 compressed image data */
            codec_format = OPJ_CODEC_JP2;
            break;
            
        case JPT_CFMT:                      /* JPEG 2000, JPIP */
            codec_format = OPJ_CODEC_JPT;
            break;
            
        case -1:
        default:
            fprintf(stderr,"%s:%d: encode format missing\n",__FILE__,__LINE__);
            
            /* close and free the byte stream */
            if (l_stream) opj_stream_destroy(l_stream);
            
            /* free remaining compression structures */
            if (l_codec) opj_destroy_codec(l_codec);
            
            /* free image data */
            if (image) opj_image_destroy(image);
            
            *compressedDataSize = 0;
            
            //enconderMutex.unlock();
            
            return NULL;
    }
    
    /* see test_tile_encoder.c:232 and opj_compress.c:1746 */
    l_codec = opj_create_compress(codec_format);
    if (!l_codec)
    {
        fprintf(stderr,"%s:%d:\n\tNO codec\n",__FILE__,__LINE__);
        
        /* close and free the byte stream */
        if (l_stream) opj_stream_destroy(l_stream);
        
        /* free remaining compression structures */
        if (l_codec) opj_destroy_codec(l_codec);
        
        /* free image data */
        if (image) opj_image_destroy(image);
        
        *compressedDataSize = 0;
        
        //enconderMutex.unlock();
        
        return NULL;
    }
    
    
#ifdef OPJ_VERBOSE
    opj_set_info_handler(l_codec, info_callback, this);
    opj_set_warning_handler(l_codec, warning_callback, this);
#endif
    
    opj_set_error_handler(l_codec, error_callback, this);
    
    if ( !opj_setup_encoder(l_codec, &parameters, image))
    {
        fprintf(stderr,"%s:%d:\n\topj_setup_encoder failed\n",__FILE__,__LINE__);
        
        /* close and free the byte stream */
        if (l_stream) opj_stream_destroy(l_stream);
        
        /* free remaining compression structures */
        if (l_codec) opj_destroy_codec(l_codec);
        
        /* free image data */
        if (image) opj_image_destroy(image);
        
        *compressedDataSize = 0;
        
        //enconderMutex.unlock();
        
        return NULL;
    }
    
    
    // Create the stream
#ifdef WITH_OPJ_BUFFER_STREAM
    opj_buffer_info_t bufferInfo;
    bufferInfo.cur = bufferInfo.buf = (OPJ_BYTE *)data;
    bufferInfo.len = (OPJ_SIZE_T) rows * columns;
    l_stream = opj_stream_create_buffer_stream(&bufferInfo, OPJ_STREAM_WRITE);
    
    //printf("%p\n",bufferInfo.buf);
    //printf("%lu\n",bufferInfo.len);
#endif
    
    
#ifdef WITH_OPJ_FILE_STREAM
    l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_STREAM_WRITE);
#endif
    
    
    if (!l_stream)
    {
        fprintf(stderr,"%s:%d:\n\tstream creation failed\n",__FILE__,__LINE__);
        
        /* close and free the byte stream */
        if (l_stream) opj_stream_destroy(l_stream);
        
        /* free remaining compression structures */
        if (l_codec) opj_destroy_codec(l_codec);
        
        /* free image data */
        if (image) opj_image_destroy(image);
        
        *compressedDataSize = 0;
        
        //enconderMutex.unlock();
        
        return NULL;
    }
    
    
    while(1)
    {
        //        int tile_index=-1, user_changed_tile=0, user_changed_reduction=0;
        //        int max_tiles=0, max_reduction=0;
        fails = OPJ_TRUE;
        
        /* encode the image */
        bSuccess = opj_start_compress(l_codec, image, l_stream);
        
        if (!bSuccess)
        {
            fprintf(stderr,"%s:%d:\n\topj_start_compress failed\n",__FILE__,__LINE__);
            break;
        }
        
        if ( bSuccess && bUseTiles )
        {
            OPJ_BYTE *l_data = NULL;
            OPJ_UINT32 l_data_size = 512*512*3; //FIXME
            l_data = (OPJ_BYTE*) malloc(l_data_size * sizeof(OPJ_BYTE));
            memset(l_data, 0, l_data_size * sizeof(OPJ_BYTE));
            
            //assert( l_data );
            if (!l_data)
            {
                /* close and free the byte stream */
                if (l_stream) opj_stream_destroy(l_stream);
                
                /* free remaining compression structures */
                if (l_codec) opj_destroy_codec(l_codec);
                
                /* free image data */
                if (image) opj_image_destroy(image);
                
                *compressedDataSize = 0;
                
                //enconderMutex.unlock();
                
                return NULL;
            }
            
            for (int i=0;i<l_nb_tiles;++i)
            {
                if (! opj_write_tile(l_codec,i,l_data,l_data_size,l_stream))
                {
                    fprintf(stderr, "\nERROR -> test_tile_encoder: failed to write the tile %d!\n",i);
                    /* close and free the byte stream */
                    if (l_stream) opj_stream_destroy(l_stream);
                    
                    /* free remaining compression structures */
                    if (l_codec) opj_destroy_codec(l_codec);
                    
                    /* free image data */
                    if (image) opj_image_destroy(image);
                    
                    free(l_data);
                    
                    *compressedDataSize = 0;
                    
                    //enconderMutex.unlock();
                    
                    return NULL;
                }
            }
            
            free(l_data);
        }
        else
        {
            if (!opj_encode(l_codec, l_stream))
            {
                fprintf(stderr,"%s:%d:\n\topj_encode failed\n",__FILE__,__LINE__);
                break;
            }
        }
        
        if (!opj_end_compress(l_codec, l_stream))
        {
            fprintf(stderr,"%s:%d:\n\topj_end_compress failed\n",__FILE__,__LINE__);
            break;
        }
        
        fails = OPJ_FALSE;
        break;
        
    } // while
    
    *compressedDataSize = 0;
    unsigned char *to = NULL;
    
    /* close and free the byte stream */
    if (l_stream) opj_stream_destroy(l_stream);
    
    /* free remaining compression structures */
    if (l_codec) opj_destroy_codec(l_codec);
    
    /* free image data */
    if (image) opj_image_destroy(image);
    
    if (fails)
    {
#ifdef WITH_OPJ_FILE_STREAM
        if (parameters.outfile[0] != '\0')
            remove(parameters.outfile);
#endif
    }
    else
    {
#ifdef WITH_OPJ_BUFFER_STREAM
        //printf("%p\n",bufferInfo.buf);
        //printf("%lu\n",bufferInfo.len);
        //to=(unsigned char *) malloc(bufferInfo.len);
        //memcpy(to,l_stream,bufferInfo.len);
#endif
        
#ifdef WITH_OPJ_FILE_STREAM
        // Open the temp file and get the encoded data into 'to'
        // and the length into 'length'
        FILE *f = NULL;
        if (parameters.outfile[0] != '\0')
        {
            f = fopen(parameters.outfile, "rb");
        }
        
        long length = 0;
        
        if (f != NULL)
        {
            fseek(f, 0, SEEK_END);
            length = ftell(f);
            fseek(f, 0, SEEK_SET);
            if (forceJ2K)
            {
                length -= 85;
                fseek(f, 85, SEEK_SET);
            }
            
            if (length % 2)
            {
                length++; // ensure even length
                //fprintf(stdout,"Padded to %li\n", length);
            }
            
            to = (unsigned char *) malloc(length);
            
            fread(to, length, 1, f);
            
            //printf("%s %lu\n",parameters.outfile,length);;
            
            fclose(f);
        }
        
        *compressedDataSize = length;
        
        if (parameters.outfile[0] != '\0')
        {
            remove(parameters.outfile);
        }
#endif
    }
    
    //enconderMutex.unlock();
    
    return to;
}
Пример #26
0
int main (int argc, char *argv[])
{
	opj_cparameters_t l_param;
	opj_codec_t * l_codec;
	opj_image_t * l_image;
	opj_image_cmptparm_t l_params [NUM_COMPS_MAX];
	opj_stream_t * l_stream;
	OPJ_UINT32 l_nb_tiles;
	OPJ_UINT32 l_data_size;
	unsigned char len;

#ifdef USING_MCT
	const OPJ_FLOAT32 l_mct [] =
	{
		1 , 0 , 0 ,
		0 , 1 , 0 ,
		0 , 0 , 1
	};

	const OPJ_INT32 l_offsets [] =
	{
		128 , 128 , 128
	};
#endif

	opj_image_cmptparm_t * l_current_param_ptr;
	OPJ_UINT32 i;
	OPJ_BYTE *l_data;

  OPJ_UINT32 num_comps;
  int image_width;
  int image_height;
  int tile_width;
  int tile_height;
  int comp_prec;
  int irreversible;
  char output_file[64];

  /* should be test_tile_encoder 3 2000 2000 1000 1000 8 tte1.j2k */
  if( argc == 9 )
    {
    num_comps = (OPJ_UINT32)atoi( argv[1] );
    image_width = atoi( argv[2] );
    image_height = atoi( argv[3] );
    tile_width = atoi( argv[4] );
    tile_height = atoi( argv[5] );
    comp_prec = atoi( argv[6] );
    irreversible = atoi( argv[7] );
    strcpy(output_file, argv[8] );
    }
  else
    {
    num_comps = 3;
    image_width = 2000;
    image_height = 2000;
    tile_width = 1000;
    tile_height = 1000;
    comp_prec = 8;
    irreversible = 1;
    strcpy(output_file, "test.j2k" );
    }
  if( num_comps > NUM_COMPS_MAX )
    {
    return 1;
    }
	l_nb_tiles = (OPJ_UINT32)(image_width/tile_width) * (OPJ_UINT32)(image_height/tile_height);
	l_data_size = (OPJ_UINT32)tile_width * (OPJ_UINT32)tile_height * (OPJ_UINT32)num_comps * (OPJ_UINT32)(comp_prec/8);

	l_data = (OPJ_BYTE*) malloc(l_data_size * sizeof(OPJ_BYTE));

	fprintf(stdout, "Encoding random values -> keep in mind that this is very hard to compress\n");
	for (i=0;i<l_data_size;++i)	{
		l_data[i] = (OPJ_BYTE)i; /*rand();*/
	}

	opj_set_default_encoder_parameters(&l_param);
	/** you may here add custom encoding parameters */
	/* rate specifications */
	/** number of quality layers in the stream */
	l_param.tcp_numlayers = 1;
	l_param.cp_fixed_quality = 1;
	l_param.tcp_distoratio[0] = 20;
	/* is using others way of calculation */
	/* l_param.cp_disto_alloc = 1 or l_param.cp_fixed_alloc = 1 */
	/* l_param.tcp_rates[0] = ... */


	/* tile definitions parameters */
	/* position of the tile grid aligned with the image */
	l_param.cp_tx0 = 0;
	l_param.cp_ty0 = 0;
	/* tile size, we are using tile based encoding */
	l_param.tile_size_on = OPJ_TRUE;
	l_param.cp_tdx = tile_width;
	l_param.cp_tdy = tile_height;

	/* use irreversible encoding ?*/
	l_param.irreversible = irreversible;

	/* do not bother with mct, the rsiz is set when calling opj_set_MCT*/
	/*l_param.cp_rsiz = OPJ_STD_RSIZ;*/

	/* no cinema */
	/*l_param.cp_cinema = 0;*/

	/* no not bother using SOP or EPH markers, do not use custom size precinct */
	/* number of precincts to specify */
	/* l_param.csty = 0;*/
	/* l_param.res_spec = ... */
	/* l_param.prch_init[i] = .. */
	/* l_param.prcw_init[i] = .. */


	/* do not use progression order changes */
	/*l_param.numpocs = 0;*/
	/* l_param.POC[i].... */

	/* do not restrain the size for a component.*/
	/* l_param.max_comp_size = 0; */

	/** block encoding style for each component, do not use at the moment */
	/** J2K_CCP_CBLKSTY_TERMALL, J2K_CCP_CBLKSTY_LAZY, J2K_CCP_CBLKSTY_VSC, J2K_CCP_CBLKSTY_SEGSYM, J2K_CCP_CBLKSTY_RESET */
	/* l_param.mode = 0;*/

	/** number of resolutions */
	l_param.numresolution = 6;

	/** progression order to use*/
	/** OPJ_LRCP, OPJ_RLCP, OPJ_RPCL, PCRL, CPRL */
	l_param.prog_order = OPJ_LRCP;

	/** no "region" of interest, more precisally component */
	/* l_param.roi_compno = -1; */
	/* l_param.roi_shift = 0; */

	/* we are not using multiple tile parts for a tile. */
	/* l_param.tp_on = 0; */
	/* l_param.tp_flag = 0; */

	/* if we are using mct */
#ifdef USING_MCT
	opj_set_MCT(&l_param,l_mct,l_offsets,NUM_COMPS);
#endif


	/* image definition */
	l_current_param_ptr = l_params;
	for (i=0;i<num_comps;++i) {
		/* do not bother bpp useless */
		/*l_current_param_ptr->bpp = COMP_PREC;*/
		l_current_param_ptr->dx = 1;
		l_current_param_ptr->dy = 1;

		l_current_param_ptr->h = (OPJ_UINT32)image_height;
		l_current_param_ptr->w = (OPJ_UINT32)image_width;

		l_current_param_ptr->sgnd = 0;
		l_current_param_ptr->prec = (OPJ_UINT32)comp_prec;

		l_current_param_ptr->x0 = 0;
		l_current_param_ptr->y0 = 0;

		++l_current_param_ptr;
	}

  /* should we do j2k or jp2 ?*/
  len = (unsigned char)strlen( output_file );
  if( strcmp( output_file + len - 4, ".jp2" ) == 0 )
    {
    l_codec = opj_create_compress(OPJ_CODEC_JP2);
    }
  else
    {
    l_codec = opj_create_compress(OPJ_CODEC_J2K);
    }
	if (!l_codec) {
		return 1;
	}

	/* catch events using our callbacks and give a local context */
	opj_set_info_handler(l_codec, info_callback,00);
	opj_set_warning_handler(l_codec, warning_callback,00);
	opj_set_error_handler(l_codec, error_callback,00);

	l_image = opj_image_tile_create(num_comps,l_params,OPJ_CLRSPC_SRGB);
	if (! l_image) {
		opj_destroy_codec(l_codec);
		return 1;
	}

	l_image->x0 = 0;
	l_image->y0 = 0;
	l_image->x1 = (OPJ_UINT32)image_width;
	l_image->y1 = (OPJ_UINT32)image_height;
	l_image->color_space = OPJ_CLRSPC_SRGB;

	if (! opj_setup_encoder(l_codec,&l_param,l_image)) {
		fprintf(stderr, "ERROR -> test_tile_encoder: failed to setup the codec!\n");
		opj_destroy_codec(l_codec);
		opj_image_destroy(l_image);
		return 1;
	}

	l_stream = opj_stream_create_default_file_stream_v3(output_file, OPJ_FALSE);
    if (! l_stream) {
		fprintf(stderr, "ERROR -> test_tile_encoder: failed to create the stream from the output file %s !\n",output_file );
		opj_destroy_codec(l_codec);
		opj_image_destroy(l_image);
		return 1;
	}

	if (! opj_start_compress(l_codec,l_image,l_stream)) {
		fprintf(stderr, "ERROR -> test_tile_encoder: failed to start compress!\n");
		opj_stream_destroy_v3(l_stream);
		opj_destroy_codec(l_codec);
		opj_image_destroy(l_image);
		return 1;
	}

	for (i=0;i<l_nb_tiles;++i) {
		if (! opj_write_tile(l_codec,i,l_data,l_data_size,l_stream)) {
			fprintf(stderr, "ERROR -> test_tile_encoder: failed to write the tile %d!\n",i);
			opj_stream_destroy_v3(l_stream);
			opj_destroy_codec(l_codec);
			opj_image_destroy(l_image);
			return 1;
		}
	}

	if (! opj_end_compress(l_codec,l_stream)) {
		fprintf(stderr, "ERROR -> test_tile_encoder: failed to end compress!\n");
		opj_stream_destroy_v3(l_stream);
		opj_destroy_codec(l_codec);
		opj_image_destroy(l_image);
		return 1;
	}

	opj_stream_destroy_v3(l_stream);
	opj_destroy_codec(l_codec);
	opj_image_destroy(l_image);

	free(l_data);

	/* Print profiling*/
	/*PROFPRINT();*/

	return 0;
}
Пример #27
0
/*!
 *  pixReadStreamJp2k()
 *
 *      Input:  stream
 *              reduction (scaling factor: 1, 2, 4, 8)
 *              box  (<optional> for extracting a subregion), can be null
 *              hint (a bitwise OR of L_JP2K_* values; 0 for default)
 *              debug (output callback messages, etc)
 *      Return: pix (8 or 32 bpp), or null on error
 *
 *  Notes:
 *      (1) See pixReadJp2k() for usage.
 */
PIX *
pixReadStreamJp2k(FILE     *fp,
                  l_uint32  reduction,
                  BOX      *box,
                  l_int32   hint,
                  l_int32   debug)
{
const char        *opjVersion;
l_int32            i, j, index, bx, by, bw, bh, val, rval, gval, bval, aval;
l_int32            w, h, wpl, bps, spp, xres, yres, reduce, prec, colorspace;
l_uint32           pixel;
l_uint32          *data, *line;
opj_dparameters_t  parameters;   /* decompression parameters */
opj_image_t       *image = NULL;
opj_codec_t       *l_codec = NULL;  /* handle to decompressor */
opj_stream_t      *l_stream = NULL;  /* opj stream */
PIX               *pix = NULL;

    PROCNAME("pixReadStreamJp2k");

    if (!fp)
        return (PIX *)ERROR_PTR("fp not defined", procName, NULL);

    opjVersion = opj_version();
    if (opjVersion[0] != '2') {
        L_ERROR("version is %s; must be 2.0 or higher\n", procName, opjVersion);
        return NULL;
    }
    if ((opjVersion[2] - 0x30) != OPJ_VERSION_MINOR) {
        L_ERROR("version %s: differs from minor = %d\n",
                procName, opjVersion, OPJ_VERSION_MINOR);
         return NULL;
     }

        /* Get the resolution and the bits/sample */
    rewind(fp);
    fgetJp2kResolution(fp, &xres, &yres);
    freadHeaderJp2k(fp, NULL, NULL, &bps, NULL);
    rewind(fp);

    if (bps > 8) {
        L_ERROR("found %d bps; can only handle 8 bps\n", procName, bps);
        return NULL;
    }

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

        /* Find and set the reduce parameter, which is log2(reduction).
         * Valid reductions are powers of 2, and are determined when the
         * compressed string is made.  A request for an invalid reduction
         * will cause an error in opj_read_header(), and no image will
         * be returned. */
    for (reduce = 0; (1L << reduce) < reduction; reduce++) { }
    if ((1L << reduce) != reduction) {
        L_ERROR("invalid reduction %d; not power of 2\n", procName, reduction);
        return NULL;
    }
    parameters.cp_reduce = reduce;

        /* Open decompression 'stream'.  In 2.0, we could call this:
         *    opj_stream_create_default_file_stream(fp, 1)
         * but the file stream interface was removed in 2.1. */
    if ((l_stream = opjCreateStream(fp, 1)) == NULL) {
        L_ERROR("failed to open the stream\n", procName);
        return NULL;
    }

    if ((l_codec = opj_create_decompress(OPJ_CODEC_JP2)) == NULL) {
        L_ERROR("failed to make the codec\n", procName);
        opj_stream_destroy(l_stream);
        return NULL;
    }

        /* Catch and report events using callbacks */
    if (debug) {
        opj_set_info_handler(l_codec, info_callback, NULL);
        opj_set_warning_handler(l_codec, warning_callback, NULL);
        opj_set_error_handler(l_codec, error_callback, NULL);
    }

        /* Setup the decoding parameters using user parameters */
    if (!opj_setup_decoder(l_codec, &parameters)){
        L_ERROR("failed to set up decoder\n", procName);
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        return NULL;
    }

        /* Read the main header of the codestream and, if necessary,
         * the JP2 boxes */
    if(!opj_read_header(l_stream, l_codec, &image)){
        L_ERROR("failed to read the header\n", procName);
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        opj_image_destroy(image);
        return NULL;
    }

        /* Set up to decode a rectangular region */
    if (box) {
        boxGetGeometry(box, &bx, &by, &bw, &bh);
        if (!opj_set_decode_area(l_codec, image, bx, by,
                                 bx + bw, by + bh)) {
            L_ERROR("failed to set the region for decoding\n", procName);
            opj_stream_destroy(l_stream);
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            return NULL;
        }
    }

        /* Get the decoded image */
    if (!(opj_decode(l_codec, l_stream, image) &&
          opj_end_decompress(l_codec, l_stream))) {
        L_ERROR("failed to decode the image\n", procName);
        opj_destroy_codec(l_codec);
        opj_stream_destroy(l_stream);
        opj_image_destroy(image);
        return NULL;
    }

        /* Close the byte stream */
    opj_stream_destroy(l_stream);

        /* Get the image parameters */
    spp = image->numcomps;
    w = image->comps[0].w;
    h = image->comps[0].h;
    prec = image->comps[0].prec;
    if (prec != bps)
        L_WARNING("precision %d != bps %d!\n", procName, prec, bps);
    if (debug) {
        L_INFO("w = %d, h = %d, bps = %d, spp = %d\n",
               procName, w, h, bps, spp);
        colorspace = image->color_space;
        if (colorspace == OPJ_CLRSPC_SRGB)
            L_INFO("colorspace is sRGB\n", procName);
        else if (colorspace == OPJ_CLRSPC_GRAY)
            L_INFO("colorspace is grayscale\n", procName);
        else if (colorspace == OPJ_CLRSPC_SYCC)
            L_INFO("colorspace is YUV\n", procName);
    }

        /* Free the codec structure */
    if (l_codec)
        opj_destroy_codec(l_codec);

        /* Convert the image to a pix */
    if (spp == 1)
        pix = pixCreate(w, h, 8);
    else
        pix = pixCreate(w, h, 32);
    pixSetResolution(pix, xres, yres);
    data = pixGetData(pix);
    wpl = pixGetWpl(pix);
    index = 0;
    if (spp == 1) {
        for (i = 0; i < h; i++) {
            line = data + i * wpl;
            for (j = 0; j < w; j++) {
                val = image->comps[0].data[index];
                SET_DATA_BYTE(line, j, val);
                index++;
            }
        }
    } else if (spp == 2) {  /* convert to RGBA */
        for (i = 0; i < h; i++) {
            line = data + i * wpl;
            for (j = 0; j < w; j++) {
                val = image->comps[0].data[index];
                aval = image->comps[1].data[index];
                composeRGBAPixel(val, val, val, aval, &pixel);
                line[j] = pixel;
                index++;
            }
        }
    } else if (spp >= 3) {
        for (i = 0; i < h; i++) {
            line = data + i * wpl;
            for (j = 0; j < w; j++) {
                rval = image->comps[0].data[index];
                gval = image->comps[1].data[index];
                bval = image->comps[2].data[index];
                if (spp == 3) {
                    composeRGBPixel(rval, gval, bval, &pixel);
                } else {  /* spp == 4 */
                    aval = image->comps[3].data[index];
                    composeRGBAPixel(rval, gval, bval, aval, &pixel);
                }
                line[j] = pixel;
                index++;
            }
        }
    }

        /* Free the opj image data structure */
    opj_image_destroy(image);

    return pix;
}