Пример #1
0
static void ReadJP2KImage( GenericImage<P>& img, jas_stream_t* jp2Stream, jas_image_t* jp2Image )
{
   int width = jas_image_cmptwidth( jp2Image, 0 );
   int height = jas_image_cmptheight( jp2Image, 0 );
   int numberOfChannels = jas_image_numcmpts( jp2Image );

   jas_matrix_t* pixels = nullptr;

   try
   {
      pixels = jas_matrix_create( 1, width );
      if ( pixels == nullptr )
         throw Error( "Memory allocation error reading JPEG2000 image" );

      // Allocate pixel data
      img.AllocateData( width, height, numberOfChannels,
                        (jas_clrspc_fam( jas_image_clrspc( jp2Image ) ) == JAS_CLRSPC_FAM_GRAY) ?
                              ColorSpace::Gray : ColorSpace::RGB );

      for ( int c = 0; c < numberOfChannels; ++c )
      {
         int n = jas_image_cmptprec( jp2Image, c );
         bool s = jas_image_cmptsgnd( jp2Image, c ) != 0;

         for ( int y = 0; y < height; ++y )
         {
            jas_image_readcmpt( jp2Image, c, 0, y, width, 1, pixels );

            typename P::sample* f = img.ScanLine( y, c );

            if ( n == 8 )
            {
               if ( s )
                  for ( int x = 0; x < width; ++x )
                     *f++ = P::ToSample( int8( jas_matrix_get( pixels, 0, x ) ) );
               else
                  for ( int x = 0; x < width; ++x )
                     *f++ = P::ToSample( uint8( jas_matrix_get( pixels, 0, x ) ) );
            }
            else
            {
               if ( s )
                  for ( int x = 0; x < width; ++x )
                     *f++ = P::ToSample( int16( jas_matrix_get( pixels, 0, x ) ) );
               else
                  for ( int x = 0; x < width; ++x )
                     *f++ = P::ToSample( uint16( jas_matrix_get( pixels, 0, x ) ) );
            }
         }
      }

      jas_matrix_destroy( pixels ), pixels = nullptr;
   }
   catch ( ... )
   {
      if ( pixels != nullptr )
         jas_matrix_destroy( pixels );
      throw;
   }
}
Пример #2
0
static void jpg_put_pixel_rows(j_decompress_ptr cinfo, jpg_dest_t *dinfo,
  JDIMENSION rows_supplied)
{
    JSAMPLE *bufptr;
    int cmptno;
    JDIMENSION x;
    uint_fast32_t width;

    if (dinfo->error) {
        return;
    }

    assert(cinfo->output_components == jas_image_numcmpts(dinfo->image));

    for (cmptno = 0; cmptno < cinfo->output_components; ++cmptno) {
        width = jas_image_cmptwidth(dinfo->image, cmptno);
        bufptr = (dinfo->buffer[0]) + cmptno;
        for (x = 0; x < width; ++x) {
            jas_matrix_set(dinfo->data, 0, x, GETJSAMPLE(*bufptr));
            bufptr += cinfo->output_components;
        }
        if (jas_image_writecmpt(dinfo->image, cmptno, 0, dinfo->row, width, 1,
          dinfo->data)) {
            dinfo->error = 1;
        }
    }
    dinfo->row += rows_supplied;
}
Пример #3
0
jas_image_t *converttosrgb(jas_image_t *inimage)
{
	jas_image_t *outimage;
	jas_cmpixmap_t inpixmap;
	jas_cmpixmap_t outpixmap;
	jas_cmcmptfmt_t incmptfmts[16];
	jas_cmcmptfmt_t outcmptfmts[16];

	outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB);
	assert(outprof);
	xform = jas_cmxform_create(jas_image_cmprof(inimage), outprof, 0, JAS_CMXFORM_FWD, JAS_CMXFORM_INTENT_PER, 0);
	assert(xform);

	inpixmap.numcmpts = jas_image_numcmpts(oldimage);
	outpixmap.numcmpts = 3;
	for (i = 0; i < inpixmap.numcmpts; ++i) {
		inpixmap.cmptfmts[i] = &incmptfmts[i];
	}
	for (i = 0; i < outpixmap.numcmpts; ++i)
		outpixmap.cmptfmts[i] = &outcmptfmts[i];
	if (jas_cmxform_apply(xform, &inpixmap, &outpixmap))
		abort();

	jas_xform_destroy(xform);
	jas_cmprof_destroy(outprof);
	return 0;
}
Пример #4
0
fz_error
fz_processjpxd(fz_filter *filter, fz_buffer *in, fz_buffer *out)
{
	fz_jpxd *d = (fz_jpxd*)filter;
	int n, bpc, w, h;
	int i, x, y;

	switch (d->stage)
	{
	case 0: goto input;
	case 1: goto decode;
	case 2: goto output;
	}

input:
	while (in->rp < in->wp)
	{
		n = jas_stream_write(d->stream, in->rp, in->wp - in->rp);
		in->rp += n;
	}

	if (!in->eof)
		return fz_ioneedin;

	d->stage = 1;

decode:
	jas_stream_seek(d->stream, 0, SEEK_SET);

	d->image = jas_image_decode(d->stream, -1, nil);
	if (!d->image)
		return fz_throw("jasper error: jas_image_decode()");

	d->stage = 2;

output:
	w = jas_image_width(d->image);
	h = jas_image_height(d->image);
	n = jas_image_numcmpts(d->image);
	bpc = jas_image_cmptprec(d->image, 0);	/* use precision of first component for all... */

	while (d->offset < w * h)
	{
		y = d->offset / w;
		x = d->offset - y * w;

		/* FIXME bpc != 8 */

		if (out->wp + n >= out->ep)
			return fz_ioneedout;

		for (i = 0; i < n; i++)
			*out->wp++ = jas_image_readcmptsample(d->image, i, x, y);

		d->offset ++;
	}

	return fz_iodone;
}
Пример #5
0
static unsigned int
maxJasperComponentPrecision(jas_image_t * const jasperP) {

    int cmptNo;
    unsigned int max;
    
    max = 1;

    for (cmptNo = 0; cmptNo < jas_image_numcmpts(jasperP); ++cmptNo)
        max = MAX(max, jas_image_cmptprec(jasperP, cmptNo));

    return max;
}
Пример #6
0
static void prevcmpt()
{
	if (gs.monomode) {
		if (!gs.cmptno) {
			gs.monomode = 0;
		} else {
			--gs.cmptno;
		}
	} else {
		gs.monomode = 1;
		gs.cmptno = jas_image_numcmpts(gs.image) - 1;
	}
	gs.dirty = 1;
	glutPostRedisplay();
}
Пример #7
0
/* dump information from a jasper image struct for debugging */
static int
dump_jas_image(jas_image_t *image)
{
    int i, numcmpts = jas_image_numcmpts(image);
    int clrspc = jas_image_clrspc(image);
    const char *csname = "unrecognized vendor space";

    if (image == NULL) return 1;

    if_debug2('w', "[w]JPX image is %d x %d\n",
        (int)jas_image_width(image), (int)jas_image_height(image));

    /* sort the colorspace */
    if jas_clrspc_isunknown(clrspc) csname = "unknown";
    else switch (clrspc) {
Пример #8
0
bool  GrFmtJpeg2000Reader::ReadHeader()
{
    bool result = false;

    Close();

    m_stream = jas_stream_fopen( m_filename, "rb" );
    if( m_stream )
    {
        m_image = jas_image_decode( m_stream, -1, 0 );
        if( m_image ) {
            m_width = jas_image_width( m_image );
            m_height = jas_image_height( m_image );

            int cntcmpts = 0; // count the known components
            int numcmpts = jas_image_numcmpts( m_image );
            for( int i = 0; i < numcmpts; i++ )
            {
                int depth = jas_image_cmptprec( m_image, i );
                if( depth > m_bit_depth )
                    m_bit_depth = depth;
                if( m_bit_depth > 8 )
                    m_bit_depth = 16;

                if( jas_image_cmpttype( m_image, i ) > 2 )
                    continue;
                cntcmpts++;
            }

            if( cntcmpts )
            {
                m_iscolor = (cntcmpts > 1);

                result = true;
            }
        }
    }

    if( !result )
        Close();

    return result;
}
Пример #9
0
static void nextcmpt()
{
	if (gs.monomode) {
		if (gs.cmptno == jas_image_numcmpts(gs.image) - 1) {
			if (gs.altimage) {
				gs.monomode = 0;
			} else {
				gs.cmptno = 0;
			}
		} else {
			++gs.cmptno;
		}
	} else {
		gs.monomode = 1;
		gs.cmptno = 0;
	}
	gs.dirty = 1;
	glutPostRedisplay();
}
Пример #10
0
static void
validateComponentsAlike(jas_image_t * const jasperP) {
/*----------------------------------------------------------------------------
   JPC allows each component to have its own width and height.  But
   PAM requires all planes to the same shape.  So we validate now that
   all the channels are the same, and abort the program if not.
-----------------------------------------------------------------------------*/
    int cmptNo;
    
    for (cmptNo = 0; cmptNo < jas_image_numcmpts(jasperP); ++cmptNo) {
        if (jas_image_cmptwidth(jasperP, cmptNo) != 
            jas_image_cmptwidth(jasperP, 0))
            pm_message("Input image does not have components all the same "
                       "width.");
        if (jas_image_cmptheight(jasperP, cmptNo) != 
            jas_image_cmptheight(jasperP, 0))
            pm_message("Input image does not have components all the same "
                       "height.");
    }
}
Пример #11
0
int jp2_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
{
	jp2_box_t *box;
	jp2_ftyp_t *ftyp;
	jp2_ihdr_t *ihdr;
	jas_stream_t *tmpstream;
	int allcmptssame;
	jp2_bpcc_t *bpcc;
	long len;
	uint_fast16_t cmptno;
	jp2_colr_t *colr;
	char buf[4096];
	uint_fast32_t overhead;
	jp2_cdefchan_t *cdefchanent;
	jp2_cdef_t *cdef;
	int i;
	uint_fast32_t typeasoc;

	box = 0;
	tmpstream = 0;

	/* Output the signature box. */

	if (!(box = jp2_box_create(JP2_BOX_JP))) {
		goto error;
	}
	box->data.jp.magic = JP2_JP_MAGIC;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Output the file type box. */

	if (!(box = jp2_box_create(JP2_BOX_FTYP))) {
		goto error;
	}
	ftyp = &box->data.ftyp;
	ftyp->majver = JP2_FTYP_MAJVER;
	ftyp->minver = JP2_FTYP_MINVER;
	ftyp->numcompatcodes = 1;
	ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/*
	 * Generate the data portion of the JP2 header box.
	 * We cannot simply output the header for this box
	 * since we do not yet know the correct value for the length
	 * field.
	 */

	if (!(tmpstream = jas_stream_memopen(0, 0))) {
		goto error;
	}

	/* Generate image header box. */

	if (!(box = jp2_box_create(JP2_BOX_IHDR))) {
		goto error;
	}
	ihdr = &box->data.ihdr;
	ihdr->width = jas_image_width(image);
	ihdr->height = jas_image_height(image);
	ihdr->numcmpts = jas_image_numcmpts(image);
	allcmptssame = 0;
	ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0),
	  jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL;
	ihdr->comptype = JP2_IHDR_COMPTYPE;
	ihdr->csunk = 0;
	ihdr->ipr = 0;
	if (jp2_box_put(box, tmpstream)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Generate bits per component box. */

	if (!allcmptssame) {
		if (!(box = jp2_box_create(JP2_BOX_BPCC))) {
			goto error;
		}
		bpcc = &box->data.bpcc;
		bpcc->numcmpts = jas_image_numcmpts(image);
		if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts *
		  sizeof(uint_fast8_t)))) {
			goto error;
		}
		for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) {
			bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image,
			  cmptno), jas_image_cmptprec(image, cmptno));
		}
		if (jp2_box_put(box, tmpstream)) {
			goto error;
		}
		jp2_box_destroy(box);
		box = 0;
	}

	/* Generate color specification box. */

	if (!(box = jp2_box_create(JP2_BOX_COLR))) {
		goto error;
	}
	colr = &box->data.colr;
	colr->method = JP2_COLR_ENUM;
	colr->pri = JP2_COLR_PRI;
	colr->approx = 0;
	colr->csid = (jas_image_colorspace(image) == JAS_IMAGE_CS_RGB) ? JP2_COLR_SRGB :
	  JP2_COLR_SGRAY;
	if (jp2_box_put(box, tmpstream)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	if (!(jas_image_colorspace(image) == JAS_IMAGE_CS_RGB &&
	  jas_image_numcmpts(image) == 3 &&
	  jas_image_getcmptbytype(image, 0) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_R) &&
	  jas_image_getcmptbytype(image, 1) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_G) &&
	  jas_image_getcmptbytype(image, 2) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_RGB_B)) &&
	  !(jas_image_colorspace(image) == JAS_IMAGE_CS_YCBCR &&
	  jas_image_numcmpts(image) != 3 &&
	  jas_image_getcmptbytype(image, 0) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_Y) &&
	  jas_image_getcmptbytype(image, 1) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_CB) &&
	  jas_image_getcmptbytype(image, 2) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_YCBCR_CR)) &&
	  !(jas_image_colorspace(image) == JAS_IMAGE_CS_GRAY &&
	  jas_image_numcmpts(image) == 1 &&
	  jas_image_getcmptbytype(image, 0) ==
	  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))) {

		if (!(box = jp2_box_create(JP2_BOX_CDEF))) {
			goto error;
		}
		cdef = &box->data.cdef;
		cdef->numchans = jas_image_numcmpts(image);
		cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t));
		for (i = 0; i < jas_image_numcmpts(image); ++i) {
			cdefchanent = &cdef->ents[i];
			cdefchanent->channo = i;
			typeasoc = jp2_gettypeasoc(jas_image_colorspace(image), jas_image_cmpttype(image, i));
			cdefchanent->type = typeasoc >> 16;
			cdefchanent->assoc = typeasoc & 0x7fff;
		}
		jp2_box_destroy(box);
		box = 0;
	}

	/* Determine the total length of the JP2 header box. */

	len = jas_stream_tell(tmpstream);
	jas_stream_rewind(tmpstream);

	/*
	 * Output the JP2 header box and all of the boxes which it contains.
	 */

	if (!(box = jp2_box_create(JP2_BOX_JP2H))) {
		goto error;
	}
	box->len = len + JP2_BOX_HDRLEN;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	if (jas_stream_copy(out, tmpstream, len)) {
		goto error;
	}

	jas_stream_close(tmpstream);
	tmpstream = 0;

	/*
	 * Output the contiguous code stream box.
	 */

	if (!(box = jp2_box_create(JP2_BOX_JP2C))) {
		goto error;
	}
	box->len = 0;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Output the JPEG-2000 code stream. */

	overhead = jas_stream_getrwcount(out);
	sprintf(buf, "%s\n_jp2overhead=%lu\n", (optstr ? optstr : ""),
	  (unsigned long) overhead);

	if (jpc_encode(image, out, buf)) {
		goto error;
	}

	return 0;
	abort();

error:

	if (box) {
		jp2_box_destroy(box);
	}
	if (tmpstream) {
		jas_stream_close(tmpstream);
	}
	return -1;
}
Пример #12
0
int main(int argc, char **argv)
{
	char *origpath;
	char *reconpath;
	int verbose;
	char *metricname;
	int metric;

	int id;
	jas_image_t *origimage;
	jas_image_t *reconimage;
	jas_matrix_t *origdata;
	jas_matrix_t *recondata;
	jas_image_t *diffimage;
	jas_stream_t *diffstream;
	int width;
	int height;
	int depth;
	int numcomps;
	double d;
	double maxdist;
	double mindist;
	int compno;
	jas_stream_t *origstream;
	jas_stream_t *reconstream;
	char *diffpath;
	int maxonly;
	int minonly;
	int fmtid;

	verbose = 0;
	origpath = 0;
	reconpath = 0;
	metricname = 0;
	metric = metricid_none;
	diffpath = 0;
	maxonly = 0;
	minonly = 0;

	if (jas_init()) {
		errprint(0, "error: cannot initialize jasper library\n");
		abort();
	}

	/* set our error callback */
	jas_set_error_cb(errprint);

	cmdname = argv[0];

	/* Parse the command line options. */
	while ((id = jas_getopt(argc, argv, opts)) >= 0) {
		switch (id) {
		case OPT_MAXONLY:
			maxonly = 1;
			break;
		case OPT_MINONLY:
			minonly = 1;
			break;
		case OPT_METRIC:
			metricname = jas_optarg;
			break;
		case OPT_ORIG:
			origpath = jas_optarg;
			break;
		case OPT_RECON:
			reconpath = jas_optarg;
			break;
		case OPT_VERBOSE:
			verbose = 1;
			break;
		case OPT_DIFFIMAGE:
			diffpath = jas_optarg;
			break;
		case OPT_VERSION:
			printf("%s\n", JAS_VERSION);
			exit(EXIT_SUCCESS);
			break;
		case OPT_HELP:
		default:
			usage();
			break;
		}
	}

	if (verbose) {
		cmdinfo();
	}

	/* Ensure that files are given for both the original and reconstructed
	  images. */
	if (!origpath || !reconpath) {
		usage();
	}

	/* If a metric was specified, process it. */
	if (metricname) {
		if ((metric = (jas_taginfo_nonull(jas_taginfos_lookup(metrictab,
		  metricname))->id)) < 0) {
			usage();
		}
	}

	/* Open the original image file. */
	if (!(origstream = jas_stream_fopen(origpath, "rb"))) {
		jas_eprintf("cannot open %s\n", origpath);
		return EXIT_FAILURE;
	}

	/* Open the reconstructed image file. */
	if (!(reconstream = jas_stream_fopen(reconpath, "rb"))) {
		jas_eprintf("cannot open %s\n", reconpath);
		return EXIT_FAILURE;
	}

	/* Decode the original image. */
	if (!(origimage = jas_image_decode(origstream, -1, 0))) {
		jas_eprintf("cannot load original image\n");
		return EXIT_FAILURE;
	}

	/* Decoder the reconstructed image. */
	if (!(reconimage = jas_image_decode(reconstream, -1, 0))) {
		jas_eprintf("cannot load reconstructed image\n");
		return EXIT_FAILURE;
	}

	/* Close the original image file. */
	jas_stream_close(origstream);

	/* Close the reconstructed image file. */
	jas_stream_close(reconstream);

	/* Ensure that both images have the same number of components. */
	numcomps = jas_image_numcmpts(origimage);
	if (jas_image_numcmpts(reconimage) != numcomps) {
		jas_eprintf("number of components differ\n");
		return EXIT_FAILURE;
	}

	/* Compute the difference for each component. */
	maxdist = 0;
	mindist = FLT_MAX;
	for (compno = 0; compno < numcomps; ++compno) {
		width = jas_image_cmptwidth(origimage, compno);
		height = jas_image_cmptheight(origimage, compno);
		depth = jas_image_cmptprec(origimage, compno);
		if (jas_image_cmptwidth(reconimage, compno) != width ||
		 jas_image_cmptheight(reconimage, compno) != height) {
			jas_eprintf("image dimensions differ\n");
			return EXIT_FAILURE;
		}
		if (jas_image_cmptprec(reconimage, compno) != depth) {
			jas_eprintf("precisions differ\n");
			return EXIT_FAILURE;
		}

		if (!(origdata = jas_matrix_create(height, width))) {
			jas_eprintf("internal error\n");
			return EXIT_FAILURE;
		}
		if (!(recondata = jas_matrix_create(height, width))) {
			jas_eprintf("internal error\n");
			return EXIT_FAILURE;
		}
		if (jas_image_readcmpt(origimage, compno, 0, 0, width, height,
		  origdata)) {
			jas_eprintf("cannot read component data\n");
			return EXIT_FAILURE;
		}
		if (jas_image_readcmpt(reconimage, compno, 0, 0, width, height,
		  recondata)) {
			jas_eprintf("cannot read component data\n");
			return EXIT_FAILURE;
		}

		if (diffpath) {
			if (!(diffstream = jas_stream_fopen(diffpath, "rwb"))) {
				jas_eprintf("cannot open diff stream\n");
				return EXIT_FAILURE;
			}
			if (!(diffimage = makediffimage(origdata, recondata))) {
				jas_eprintf("cannot make diff image\n");
				return EXIT_FAILURE;
			}
			fmtid = jas_image_strtofmt("pnm");
			if (jas_image_encode(diffimage, diffstream, fmtid, 0)) {
				jas_eprintf("cannot save\n");
				return EXIT_FAILURE;
			}
			jas_stream_close(diffstream);
			jas_image_destroy(diffimage);
		}

		if (metric != metricid_none) {
			d = getdistortion(origdata, recondata, depth, metric);
			if (d > maxdist) {
				maxdist = d;
			}
			if (d < mindist) {
				mindist = d;
			}
			if (!maxonly && !minonly) {
				if (metric == metricid_pae || metric == metricid_equal) {
					printf("%ld\n", (long) ceil(d));
				} else {
					printf("%f\n", d);
				}
			}
		}
		jas_matrix_destroy(origdata);
		jas_matrix_destroy(recondata);
	}

	if (metric != metricid_none && (maxonly || minonly)) {
		if (maxonly) {
			d = maxdist;
		} else if (minonly) {
			d = mindist;
		} else {
			abort();
		}
		
		if (metric == metricid_pae || metric == metricid_equal) {
			jas_eprintf("%ld\n", (long) ceil(d));
		} else {
			jas_eprintf("%f\n", d);
		}
	}

	jas_image_destroy(origimage);
	jas_image_destroy(reconimage);
	jas_image_clearfmts();

	return EXIT_SUCCESS;
}
Пример #13
0
static GstFlowReturn
gst_jasper_dec_negotiate (GstJasperDec * dec, jas_image_t * image)
{
  GstFlowReturn flow_ret = GST_FLOW_OK;
  gint width, height, channels;
  gint i, j;
  gboolean negotiate = FALSE;
  jas_clrspc_t clrspc;
  GstCaps *allowed_caps, *caps;

  width = jas_image_width (image);
  height = jas_image_height (image);
  channels = jas_image_numcmpts (image);

  GST_LOG_OBJECT (dec, "%d x %d, %d components", width, height, channels);

  /* jp2c bitstream has no real colour space info (kept in container),
   * so decoder may only pretend to know, where it really does not */
  if (!jas_clrspc_isunknown (dec->clrspc)) {
    clrspc = dec->clrspc;
    GST_DEBUG_OBJECT (dec, "forcing container supplied colour space %d",
        clrspc);
    jas_image_setclrspc (image, clrspc);
  } else
    clrspc = jas_image_clrspc (image);

  if (!width || !height || !channels || jas_clrspc_isunknown (clrspc))
    goto fail_image;

  if (dec->width != width || dec->height != height ||
      dec->channels != channels || dec->clrspc != clrspc)
    negotiate = TRUE;

  if (channels != 3)
    goto not_supported;

  for (i = 0; i < channels; i++) {
    gint cheight, cwidth, depth, sgnd;

    cheight = jas_image_cmptheight (image, i);
    cwidth = jas_image_cmptwidth (image, i);
    depth = jas_image_cmptprec (image, i);
    sgnd = jas_image_cmptsgnd (image, i);

    GST_LOG_OBJECT (dec, "image component %d, %dx%d, depth %d, sgnd %d", i,
        cwidth, cheight, depth, sgnd);

    if (depth != 8 || sgnd)
      goto not_supported;

    if (dec->cheight[i] != cheight || dec->cwidth[i] != cwidth) {
      dec->cheight[i] = cheight;
      dec->cwidth[i] = cwidth;
      negotiate = TRUE;
    }
  }

  if (!negotiate && dec->format != GST_VIDEO_FORMAT_UNKNOWN)
    goto done;

  /* clear and refresh to new state */
  flow_ret = GST_FLOW_NOT_NEGOTIATED;
  dec->format = GST_VIDEO_FORMAT_UNKNOWN;
  dec->width = width;
  dec->height = height;
  dec->channels = channels;

  /* retrieve allowed caps, and find the first one that reasonably maps
   * to the parameters of the colourspace */
  caps = gst_pad_get_allowed_caps (dec->srcpad);
  if (!caps) {
    GST_DEBUG_OBJECT (dec, "... but no peer, using template caps");
    /* need to copy because get_allowed_caps returns a ref,
       and get_pad_template_caps doesn't */
    caps = gst_caps_copy (gst_pad_get_pad_template_caps (dec->srcpad));
  }
  /* avoid lists of fourcc, etc */
  allowed_caps = gst_caps_normalize (caps);
  caps = NULL;
  GST_LOG_OBJECT (dec, "allowed source caps %" GST_PTR_FORMAT, allowed_caps);

  for (i = 0; i < gst_caps_get_size (allowed_caps); i++) {
    GstVideoFormat format;
    gboolean ok;

    if (caps)
      gst_caps_unref (caps);
    caps = gst_caps_copy_nth (allowed_caps, i);
    /* sigh, ds and _parse_caps need fixed caps for parsing, fixate */
    gst_pad_fixate_caps (dec->srcpad, caps);
    GST_LOG_OBJECT (dec, "checking caps %" GST_PTR_FORMAT, caps);
    if (!gst_video_format_parse_caps (caps, &format, NULL, NULL))
      continue;
    if (gst_video_format_is_rgb (format) &&
        jas_clrspc_fam (clrspc) == JAS_CLRSPC_FAM_RGB) {
      GST_DEBUG_OBJECT (dec, "trying RGB");
      if ((dec->cmpt[0] = jas_image_getcmptbytype (image,
                  JAS_IMAGE_CT_COLOR (JAS_CLRSPC_CHANIND_RGB_R))) < 0 ||
          (dec->cmpt[1] = jas_image_getcmptbytype (image,
                  JAS_IMAGE_CT_COLOR (JAS_CLRSPC_CHANIND_RGB_G))) < 0 ||
          (dec->cmpt[2] = jas_image_getcmptbytype (image,
                  JAS_IMAGE_CT_COLOR (JAS_CLRSPC_CHANIND_RGB_B))) < 0) {
        GST_DEBUG_OBJECT (dec, "missing RGB color component");
        continue;
      }
    } else if (gst_video_format_is_yuv (format) &&
        jas_clrspc_fam (clrspc) == JAS_CLRSPC_FAM_YCBCR) {
      GST_DEBUG_OBJECT (dec, "trying YUV");
      if ((dec->cmpt[0] = jas_image_getcmptbytype (image,
                  JAS_IMAGE_CT_COLOR (JAS_CLRSPC_CHANIND_YCBCR_Y))) < 0 ||
          (dec->cmpt[1] = jas_image_getcmptbytype (image,
                  JAS_IMAGE_CT_COLOR (JAS_CLRSPC_CHANIND_YCBCR_CB))) < 0 ||
          (dec->cmpt[2] = jas_image_getcmptbytype (image,
                  JAS_IMAGE_CT_COLOR (JAS_CLRSPC_CHANIND_YCBCR_CR))) < 0) {
        GST_DEBUG_OBJECT (dec, "missing YUV color component");
        continue;
      }
    } else
      continue;
    /* match format with validity checks */
    ok = TRUE;
    for (j = 0; j < channels; j++) {
      gint cmpt;

      cmpt = dec->cmpt[j];
      if (dec->cwidth[cmpt] != gst_video_format_get_component_width (format, j,
              width) ||
          dec->cheight[cmpt] != gst_video_format_get_component_height (format,
              j, height))
        ok = FALSE;
    }
    /* commit to this format */
    if (ok) {
      dec->format = format;
      break;
    }
  }

  if (caps)
    gst_caps_unref (caps);
  gst_caps_unref (allowed_caps);

  if (dec->format != GST_VIDEO_FORMAT_UNKNOWN) {
    /* cache some video format properties */
    for (j = 0; j < channels; ++j) {
      dec->offset[j] = gst_video_format_get_component_offset (dec->format, j,
          dec->width, dec->height);
      dec->inc[j] = gst_video_format_get_pixel_stride (dec->format, j);
      dec->stride[j] = gst_video_format_get_row_stride (dec->format, j,
          dec->width);
    }
    dec->image_size = gst_video_format_get_size (dec->format, width, height);
    dec->alpha = gst_video_format_has_alpha (dec->format);

    if (dec->buf)
      g_free (dec->buf);
    dec->buf = g_new0 (glong, dec->width);

    caps = gst_video_format_new_caps (dec->format, dec->width, dec->height,
        dec->framerate_numerator, dec->framerate_denominator, 1, 1);

    GST_DEBUG_OBJECT (dec, "Set format to %d, size to %dx%d", dec->format,
        dec->width, dec->height);

    if (!gst_pad_set_caps (dec->srcpad, caps))
      flow_ret = GST_FLOW_NOT_NEGOTIATED;
    else
      flow_ret = GST_FLOW_OK;

    gst_caps_unref (caps);
  }

done:
  return flow_ret;

  /* ERRORS */
fail_image:
  {
    GST_DEBUG_OBJECT (dec, "Failed to process decoded image.");
    flow_ret = GST_FLOW_NOT_NEGOTIATED;
    goto done;
  }
not_supported:
  {
    GST_DEBUG_OBJECT (dec, "Decoded image has unsupported colour space.");
    GST_ELEMENT_ERROR (dec, STREAM, DECODE, (NULL), ("Unsupported colorspace"));
    flow_ret = GST_FLOW_ERROR;
    goto done;
  }
}
Пример #14
0
static int loadimage()
{
	int reshapeflag;
	jas_stream_t *in;
	int scrnwidth;
	int scrnheight;
	int vh;
	int vw;
	char *pathname;
	jas_cmprof_t *outprof;

	assert(!gs.image);
	assert(!gs.altimage);

	gs.image = 0;
	gs.altimage = 0;

	pathname = cmdopts.filenames[gs.filenum];

	if (pathname && pathname[0] != '\0') {
#if 1
	jas_eprintf("opening %s\n", pathname);
#endif
		/* The input image is to be read from a file. */
		if (!(in = jas_stream_fopen(pathname, "rb"))) {
			jas_eprintf("error: cannot open file %s\n", pathname);
			goto error;
		}
	} else {
		/* The input image is to be read from standard input. */
		in = streamin;
	}

	/* Get the input image data. */
	if (!(gs.image = jas_image_decode(in, -1, 0))) {
		jas_eprintf("error: cannot load image data\n");
		goto error;
	}

	/* Close the input stream. */
	if (in != streamin) {
		jas_stream_close(in);
	}

	if (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)))
		goto error;
	if (!(gs.altimage = jas_image_chclrspc(gs.image, outprof, JAS_CMXFORM_INTENT_PER)))
		goto error;

	if ((scrnwidth = glutGet(GLUT_SCREEN_WIDTH)) < 0) {
		scrnwidth = 256;
	}
	if ((scrnheight = glutGet(GLUT_SCREEN_HEIGHT)) < 0) {
		scrnheight = 256;
	}

	vw = min(jas_image_width(gs.image), 0.95 * scrnwidth);
	vh = min(jas_image_height(gs.image), 0.95 * scrnheight);

	gs.vcx = (jas_image_tlx(gs.image) + jas_image_brx(gs.image)) / 2.0;
	gs.vcy = (jas_image_tly(gs.image) + jas_image_bry(gs.image)) / 2.0;
	gs.sx = 1.0;
	gs.sy = 1.0;
	if (gs.altimage) {
		gs.monomode = 0;
	} else {
		gs.monomode = 1;
		gs.cmptno = 0;
	}

#if 1
	jas_eprintf("num of components %d\n", jas_image_numcmpts(gs.image));
#endif

	if (vw < jas_image_width(gs.image)) {
		gs.sx = jas_image_width(gs.image) / ((float) vw);
	}
	if (vh < jas_image_height(gs.image)) {
		gs.sy = jas_image_height(gs.image) / ((float) vh);
	}
	if (gs.sx > gs.sy) {
		gs.sy = gs.sx;
	} else if (gs.sx < gs.sy) {
		gs.sx = gs.sy;
	}
	vw = jas_image_width(gs.image) / gs.sx;
	vh = jas_image_height(gs.image) / gs.sy;
	gs.dirty = 1;

	reshapeflag = 0;
	if (vw != glutGet(GLUT_WINDOW_WIDTH) ||
	  vh != glutGet(GLUT_WINDOW_HEIGHT)) {
		glutReshapeWindow(vw, vh);
		reshapeflag = 1;
	}
	if (cmdopts.title) {
		glutSetWindowTitle(cmdopts.title);
	} else {
		glutSetWindowTitle((pathname && pathname[0] != '\0') ? pathname :
		  "stdin");
	}
	/* If we reshaped the window, GLUT will automatically invoke both
	  the reshape and display callback (in this order).  Therefore, we
	  only need to explicitly force the display callback to be invoked
	  if the window was not reshaped. */
	if (!reshapeflag) {
		glutPostRedisplay();
	}

	if (cmdopts.tmout != 0) {
		glutTimerFunc(cmdopts.tmout, timer, gs.nexttmid);
		gs.activetmid = gs.nexttmid;
		++gs.nexttmid;
	}

	return 0;

error:
	unloadimage();
	return -1;
}
Пример #15
0
int main(int argc, char **argv)
{
	jas_image_t *image;
	cmdopts_t *cmdopts;
	jas_stream_t *in;
	jas_stream_t *out;
	clock_t startclk;
	clock_t endclk;
	long dectime;
	long enctime;
	int_fast16_t numcmpts;
	int i;

	/* Determine the base name of this command. */
	if ((cmdname = strrchr(argv[0], '/'))) {
		++cmdname;
	} else {
		cmdname = argv[0];
	}

	if (jas_init()) {
		errprint(0, "error: cannot initialize jasper library\n");
		abort();
	}

	/* set our error callback */
	jas_set_error_cb(errprint);

	/* Parse the command line options. */
	if (!(cmdopts = cmdopts_parse(argc, argv))) {
		jas_eprintf("error: cannot parse command line\n");
		exit(EXIT_FAILURE);
	}

	if (cmdopts->version) {
		jas_eprintf("%s\n", JAS_VERSION);
		jas_eprintf("libjasper %s\n", jas_getversion());
		exit(EXIT_SUCCESS);
	}

	jas_setdbglevel(cmdopts->debug);

	if (cmdopts->verbose) {
		cmdinfo();
	}

	/* Open the input image file. */
	if (cmdopts->infile) {
		/* The input image is to be read from a file. */
		if (!(in = jas_stream_fopen(cmdopts->infile, "rb"))) {
			jas_eprintf("error: cannot open input image file %s\n",
			  cmdopts->infile);
			exit(EXIT_FAILURE);
		}
	} else {
		/* The input image is to be read from standard input. */
		if (!(in = jas_stream_fdopen(0, "rb"))) {
			jas_eprintf("error: cannot open standard input\n");
			exit(EXIT_FAILURE);
		}
	}

	/* Open the output image file. */
	if (cmdopts->outfile) {
		/* The output image is to be written to a file. */
		if (!(out = jas_stream_fopen(cmdopts->outfile, "w+b"))) {
			jas_eprintf("error: cannot open output image file %s\n",
			  cmdopts->outfile);
			exit(EXIT_FAILURE);
		}
	} else {
		/* The output image is to be written to standard output. */
		if (!(out = jas_stream_fdopen(1, "w+b"))) {
			jas_eprintf("error: cannot open standard output\n");
			exit(EXIT_FAILURE);
		}
	}

	if (cmdopts->infmt < 0) {
		if ((cmdopts->infmt = jas_image_getfmt(in)) < 0) {
			jas_eprintf("error: input image has unknown format\n");
			exit(EXIT_FAILURE);
		}
	}

	/* Get the input image data. */
	startclk = clock();
	if (!(image = jas_image_decode(in, cmdopts->infmt, cmdopts->inopts))) {
		jas_eprintf("error: cannot load image data\n");
		exit(EXIT_FAILURE);
	}
	endclk = clock();
	dectime = endclk - startclk;

	/* If requested, throw away all of the components except one.
	  Why might this be desirable?  It is a hack, really.
	  None of the image formats other than the JPEG-2000 ones support
	  images with two, four, five, or more components.  This hack
	  allows such images to be decoded with the non-JPEG-2000 decoders,
	  one component at a time. */
	numcmpts = jas_image_numcmpts(image);
	if (cmdopts->cmptno >= 0 && cmdopts->cmptno < numcmpts) {
		for (i = numcmpts - 1; i >= 0; --i) {
			if (i != cmdopts->cmptno) {
				jas_image_delcmpt(image, i);
			}
		}
	}

	if (cmdopts->srgb) {
		jas_image_t *newimage;
		jas_cmprof_t *outprof;
		jas_eprintf("forcing conversion to sRGB\n");
		if (!(outprof = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) {
			jas_eprintf("cannot create sRGB profile\n");
			exit(EXIT_FAILURE);
		}
		if (!(newimage = jas_image_chclrspc(image, outprof, JAS_CMXFORM_INTENT_PER))) {
			jas_eprintf("cannot convert to sRGB\n");
			exit(EXIT_FAILURE);
		}
		jas_image_destroy(image);
		jas_cmprof_destroy(outprof);
		image = newimage;
	}

	/* Generate the output image data. */
	startclk = clock();
	if (jas_image_encode(image, out, cmdopts->outfmt, cmdopts->outopts)) {
		jas_eprintf("error: cannot encode image\n");
		exit(EXIT_FAILURE);
	}
	jas_stream_flush(out);
	endclk = clock();
	enctime = endclk - startclk;

	if (cmdopts->verbose) {
		jas_eprintf("decoding time = %f\n", dectime / (double)
		  CLOCKS_PER_SEC);
		jas_eprintf("encoding time = %f\n", enctime / (double)
		  CLOCKS_PER_SEC);
	}

	/* If this fails, we don't care. */
	(void) jas_stream_close(in);

	/* Close the output image stream. */
	if (jas_stream_close(out)) {
		jas_eprintf("error: cannot close output image file\n");
		exit(EXIT_FAILURE);
	}

	cmdopts_destroy(cmdopts);
	jas_image_destroy(image);
	jas_image_clearfmts();

	/* Success at last! :-) */
	return EXIT_SUCCESS;
}
Пример #16
0
DEFINE_LOADER_PLUGIN_LOAD(p, st, vw
#if !defined(IDENTIFY_BEFORE_LOAD)
__attribute__((unused))
#endif
, c
#if !defined(IDENTIFY_BEFORE_LOAD)
__attribute__((unused))
#endif
, priv
#if !defined(IDENTIFY_BEFORE_LOAD)
__attribute__((unused))
#endif
)
{
  jas_image_t *ji;
  jas_stream_t *js;
  unsigned char *d;
  char *buf = NULL;
  int k, cmp[3];
  unsigned int i, j;
  int tlx, tly;
  int vs, hs;

  //debug_message("JasPer: load() called\n");

#ifdef IDENTIFY_BEFORE_LOAD
  {
    LoaderStatus status;

    if ((status = identify(p, st, vw, c, priv)) != LOAD_OK)
      return status;
    stream_rewind(st);
  }
#endif

  /* Read whole stream into buffer... */
  {
    char *tmp;
    int size = 0, len;
    int bufsize = 65536;

    for (;;) {
      if ((tmp = realloc(buf, bufsize)) == NULL) {
	free(buf);
	return LOAD_ERROR;
      }
      buf = tmp;
      len = stream_read(st, (unsigned char *)(buf + size), bufsize - size);
      size += len;
      if (len < bufsize - size)
	break;
      bufsize += 65536;
    }
    if ((js = jas_stream_memopen(buf, size)) == NULL) {
      free(buf);
      return LOAD_ERROR;
    }
  }

  /* loading... */
  if ((ji = jas_image_decode(js, -1, 0)) == NULL) {
    err_message_fnc("jas_image_decode() failed.\n");
    goto error_clear;
  }

  /* colorspace conversion */
  {
    jas_cmprof_t *jc;
    jas_image_t *new_ji;
    if ((jc = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB)) == NULL)
      goto error_destroy_free;
    if ((new_ji = jas_image_chclrspc(ji, jc, JAS_CMXFORM_INTENT_PER)) == NULL)
      goto error_destroy_free;
    jas_image_destroy(ji);
    ji = new_ji;
  }

  jas_stream_close(js);
  free(buf);
  debug_message("JasPer: jas_image_decode() OK: (%ld,%ld)\n", jas_image_cmptwidth(ji, 0), jas_image_cmptheight(ji, 0));

  /* convert to enfle format */

  p->bits_per_pixel = 24;
  p->type = _RGB24;
  p->depth = 24;
  cmp[0] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
  cmp[1] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
  cmp[2] = jas_image_getcmptbytype(ji, JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
  /* dimension */
  image_width(p)  = jas_image_cmptwidth(ji, cmp[0]);
  image_height(p) = jas_image_cmptheight(ji, cmp[0]);
  image_left(p) = 0;
  image_top(p) = 0;
  image_bpl(p) = image_width(p) * 3;
  tlx = jas_image_cmpttlx(ji, cmp[0]);
  tly = jas_image_cmpttly(ji, cmp[0]);
  vs = jas_image_cmptvstep(ji, cmp[0]);
  hs = jas_image_cmpthstep(ji, cmp[0]);
  debug_message("JasPer: tlx %d tly %d vs %d hs %d ncomponents %d\n", tlx, tly, vs, hs, jas_image_numcmpts(ji));
  /* memory allocation */
  if ((d = memory_alloc(image_image(p), image_bpl(p) * image_height(p))) == NULL) {
    err_message("No enough memory (%d bytes)\n", image_bpl(p) * image_height(p));
    goto error_destroy_free;
  }

  for (i = 0; i < image_height(p); i++) {
    for (j = 0; j < image_width(p); j++) {
      for (k = 0; k < 3; k++)
	*d++ = jas_image_readcmptsample(ji, cmp[k], j, i);
    }
  }

  jas_image_destroy(ji);

  return LOAD_OK;

 error_destroy_free:
  jas_image_destroy(ji);
 error_clear:

  return LOAD_ERROR;
}
Пример #17
0
static void
computeOutputParm(jas_image_t * const jasperP,
                  struct pam *  const outpamP,
                  int **        const jasperCmptNoP) {

    int * jasperCmptNo;
       /* Malloc'ed array.  jaspercmptNo[P] is the component number for use
          with the Jasper library that corresponds to Plane P of the PAM.
       */

	switch (jas_clrspc_fam(jas_image_clrspc(jasperP))) {
	case JAS_CLRSPC_FAM_GRAY:
        outpamP->depth = 1;
        MALLOCARRAY_NOFAIL(jasperCmptNo, 1);
        getGrayComponent(&jasperCmptNo[0], jasperP);
        if (jas_image_cmptprec(jasperP, jasperCmptNo[0]) == 1) {
            outpamP->format = RPBM_FORMAT;
            strcpy(outpamP->tuple_type, PAM_PBM_TUPLETYPE);
        } else {
            outpamP->format = RPGM_FORMAT;
            strcpy(outpamP->tuple_type, PAM_PGM_TUPLETYPE);
        }
        break;
	case JAS_CLRSPC_FAM_RGB:
        outpamP->depth = 3;
        MALLOCARRAY_NOFAIL(jasperCmptNo, 3);
        getRgbComponents(jasperCmptNo, jasperP);
        outpamP->format = RPPM_FORMAT;
        strcpy(outpamP->tuple_type, PAM_PPM_TUPLETYPE);
        break;
    default:
        outpamP->format = PAM_FORMAT;
        outpamP->depth = jas_image_numcmpts(jasperP);
        {
            unsigned int plane;

            MALLOCARRAY_NOFAIL(jasperCmptNo, outpamP->depth);
            for (plane = 0; plane < outpamP->depth; ++plane)
                jasperCmptNo[plane] = plane;
        }
        strcpy(outpamP->tuple_type, "");
        if (jas_image_cmptsgnd(jasperP, 0)) 
            pm_message("Warning: Input image has signed sample values.  "
                       "They will be represented in the PAM output in "
                       "two's complement.");
    }
    outpamP->plainformat = FALSE;

	outpamP->width = jas_image_cmptwidth(jasperP, 0);
	outpamP->height = jas_image_cmptheight(jasperP, 0);

    validateComponentsAlike(jasperP);

    {
        unsigned int const maxPrecision = maxJasperComponentPrecision(jasperP);

        outpamP->maxval = pm_bitstomaxval(maxPrecision);
        
        outpamP->bytes_per_sample = (maxPrecision + 7)/8;
    }
    *jasperCmptNoP = jasperCmptNo;
}
Пример #18
0
int JPEG2000Dataset::DecodeImage()
{
    if (bAlreadyDecoded)
        return psImage != NULL;
        
    bAlreadyDecoded = TRUE;    
    if ( !( psImage = jas_image_decode(psStream, iFormat, 0) ) )
    {
        CPLDebug( "JPEG2000", "Unable to decode image. Format: %s, %d",
                  jas_image_fmttostr( iFormat ), iFormat );
        return FALSE;
    }
    
    /* Case of a JP2 image : check that the properties given by */
    /* the JP2 boxes match the ones of the code stream */
    if (nBands != 0)
    {
        if (nBands != jas_image_numcmpts( psImage ))
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "The number of components indicated in the IHDR box (%d) mismatch "
                     "the value specified in the code stream (%d)",
                     nBands, jas_image_numcmpts( psImage ));
            jas_image_destroy( psImage );
            psImage = NULL;
            return FALSE;
        }
        
        if (nRasterXSize != jas_image_cmptwidth( psImage, 0 ) ||
            nRasterYSize != jas_image_cmptheight( psImage, 0 ) )
        {
            CPLError(CE_Failure, CPLE_AppDefined,
                     "The dimensions indicated in the IHDR box (%d x %d) mismatch "
                     "the value specified in the code stream (%d x %d)",
                     nRasterXSize, nRasterYSize,
                     jas_image_cmptwidth( psImage, 0 ),
                     jas_image_cmptheight( psImage, 0 ));
            jas_image_destroy( psImage );
            psImage = NULL;
            return FALSE;
        }
        
        int iBand;
        for ( iBand = 0; iBand < nBands; iBand++ )
        {
            JPEG2000RasterBand* poBand = (JPEG2000RasterBand*) GetRasterBand(iBand+1);
            if (poBand->iDepth != jas_image_cmptprec( psImage, iBand ) ||
                poBand->bSignedness != jas_image_cmptsgnd( psImage, iBand ))
            {
                CPLError(CE_Failure, CPLE_AppDefined,
                         "The bit depth of band %d indicated in the IHDR box (%d) mismatch "
                         "the value specified in the code stream (%d)",
                         iBand + 1, poBand->iDepth, jas_image_cmptprec( psImage, iBand ));
                jas_image_destroy( psImage );
                psImage = NULL;
                return FALSE;
            }
        }
    }
    
    /* Ask for YCbCr -> RGB translation */
    if ( jas_clrspc_fam( jas_image_clrspc( psImage ) ) == 
              JAS_CLRSPC_FAM_YCBCR )
    {
        jas_image_t *psRGBImage;
        jas_cmprof_t *psRGBProf;
        CPLDebug( "JPEG2000", "forcing conversion to sRGB");
        if (!(psRGBProf = jas_cmprof_createfromclrspc(JAS_CLRSPC_SRGB))) {
            CPLDebug( "JPEG2000", "cannot create sRGB profile");
            return TRUE;
        }
        if (!(psRGBImage = jas_image_chclrspc(psImage, psRGBProf, JAS_CMXFORM_INTENT_PER))) {
            CPLDebug( "JPEG2000", "cannot convert to sRGB");
            jas_cmprof_destroy(psRGBProf);
            return TRUE;
        }
        jas_image_destroy(psImage);
        jas_cmprof_destroy(psRGBProf);
        psImage = psRGBImage;
    }
    
    return TRUE;
}
Пример #19
0
static gboolean
query_jp2 (const gchar   *path,
           gint          *width,
           gint          *height,
           gint          *depth,
           jas_image_t  **jas_image)
{
  gboolean ret;
  jas_stream_t *in;
  int image_fmt;
  jas_image_t *image;
  jas_cmprof_t *output_profile;
  jas_image_t *cimage;
  int numcmpts;
  int i;
  gboolean b;

  in = NULL;
  cimage = image = NULL;
  output_profile = NULL;
  ret = FALSE;

  do
    {
      in = jas_stream_fopen (path, "rb");
      if (!in)
	{
	  g_warning ("Unable to open image file '%s'", path);
	  break;
	}

      image_fmt = jas_image_getfmt (in);
      if (image_fmt < 0)
	{
	  g_warning (_("Unknown JPEG-2000 image format in '%s'"), path);
          break;
	}

      image = jas_image_decode (in, image_fmt, NULL);
      if (!image)
	{
	  g_warning (_("Unable to open JPEG-2000 image in '%s'"), path);
	  break;
	}

      output_profile = jas_cmprof_createfromclrspc (JAS_CLRSPC_SRGB);
      if (!output_profile)
        {
	  g_warning (_("Unable to create output color profile for '%s'"), path);
	  break;
        }

      cimage = jas_image_chclrspc (image, output_profile,
                                   JAS_CMXFORM_INTENT_PER);
      if (!cimage)
        {
	  g_warning (_("Unable to convert image to sRGB color space "
                       "when processing '%s'"), path);
	  break;
        }

      numcmpts = jas_image_numcmpts (cimage);
      if (numcmpts != 3)
	{
	  g_warning (_("Unsupported non-RGB JPEG-2000 file with "
                       "%d components in '%s'"), numcmpts, path);
	  break;
	}

      *width = jas_image_cmptwidth (cimage, 0);
      *height = jas_image_cmptheight (cimage, 0);
      *depth = jas_image_cmptprec (cimage, 0);

      if ((*depth != 8) && (*depth != 16))
	{
	  g_warning (_("Unsupported JPEG-2000 file with depth %d in '%s'"),
                     *depth, path);
	  break;
	}

      b = FALSE;

      for (i = 1; i < 3; i++)
        {
          if ((jas_image_cmptprec (cimage, i) != *depth) ||
              (jas_image_cmptwidth (cimage, i) != *width) ||
              (jas_image_cmptheight (cimage, i) != *height))
            {
              g_warning (_("Components of input image '%s' don't match"),
                         path);
              b = TRUE;
              break;
            }
        }

      if (b)
        break;

      ret = TRUE;
    }
  while (FALSE); /* structured goto */

  if (jas_image)
    *jas_image = cimage;
  else if (cimage)
    jas_image_destroy (cimage);

  if (image)
    jas_image_destroy (image);

  if (output_profile)
    jas_cmprof_destroy (output_profile);

  if (in)
    jas_stream_close (in);

  return ret;
}
Пример #20
0
int img_dat_generate(IMG_DAT **oimg_dat, jas_image_t *image)
{
   IMG_DAT *img_dat;
   int i;
   int cmptscnt;
   int rwcnt;
   int max_hor, max_vrt;

   /* Allocate memory for image data structure. */
   img_dat = (IMG_DAT *)calloc(1, sizeof(IMG_DAT));
   if(img_dat == NULL){
      fprintf(stderr, "ERROR : img_dat_generate : "
              "calloc : img_dat (%lu bytes)\n", (unsigned long)sizeof(IMG_DAT));
      return(-2);
   }

   /* Get component count. */
   cmptscnt = jas_image_numcmpts(image);

   /* Initialize img_dat info */
   img_dat->max_width = jas_image_brx(image);
   img_dat->max_height = jas_image_bry(image);
   img_dat->ppi = -1;
   img_dat->intrlv = 0;
   img_dat->n_cmpnts = cmptscnt;
   img_dat->cmpnt_depth = jas_image_cmptprec(image, 0);

   max_hor = -1;
   max_vrt = -1;
   img_dat->pix_depth = 0;

   for(i = 0; i < cmptscnt; i++){
      int cdepth;

      img_dat->hor_sampfctr[i] = 1;
      img_dat->vrt_sampfctr[i] = 1;
      cdepth = jas_image_cmptprec(image, i);
      img_dat->pix_depth += cdepth;
      if (cdepth != img_dat->cmpnt_depth) {
         fprintf(stderr, "WARNING : img_dat_generate: "
                 "unequal component depths, 0: %d and %d: %d\n",
                 i, cdepth, jas_image_cmptprec(image, i));
      }

      if(max_hor < img_dat->hor_sampfctr[i])
         max_hor = img_dat->hor_sampfctr[i];
      if(max_vrt < img_dat->vrt_sampfctr[i])
         max_vrt = img_dat->vrt_sampfctr[i];
   }

   for(i = 0; i < img_dat->n_cmpnts; i++){
      img_dat->samp_width[i] = (int)ceil(img_dat->max_width *
                   (img_dat->hor_sampfctr[i]/(double)max_hor));
      img_dat->samp_height[i] = (int)ceil(img_dat->max_height *
                   (img_dat->vrt_sampfctr[i]/(double)max_vrt));
   }

   /* Put the image raw pixels to image data sturcture component plains. */
   cmptscnt = jas_image_numcmpts(image);
   for (i = 0; i < cmptscnt; i++){
      jas_stream_rewind(image->cmpts_[i]->stream_);
      rwcnt = jas_stream_getrwcount(image->cmpts_[i]->stream_) - 1;
      img_dat->image[i]  = (unsigned char *)malloc(rwcnt * sizeof(unsigned char));
      if(img_dat->image[i] == NULL){
         fprintf(stderr, "ERROR : get_raw_image: "
                 "calloc : img_dat->image[%d] (%lu bytes)\n",
                 i, (unsigned long)(rwcnt * sizeof(unsigned char)));
         return(-3);
      }
      jas_stream_read(image->cmpts_[i]->stream_, img_dat->image[i], rwcnt);
   }

   *oimg_dat = img_dat;

   return(0);
}
Пример #21
0
static int pnm_getdata(jas_stream_t *in, pnm_hdr_t *hdr, jas_image_t *image)
{
    int ret;
#if 0
    int numcmpts;
#endif
    int cmptno;
    int fmt;
    jas_matrix_t *data[3];
    int x;
    int y;
    int_fast64_t v;
    int depth;
    int type;
    int c;
    int n;

    ret = -1;

#if 0
    numcmpts = jas_image_numcmpts(image);
#endif
    fmt = pnm_fmt(hdr->magic);
    type = pnm_type(hdr->magic);
    depth = pnm_maxvaltodepth(hdr->maxval);

    data[0] = 0;
    data[1] = 0;
    data[2] = 0;
    for (cmptno = 0; cmptno < hdr->numcmpts; ++cmptno) {
        if (!(data[cmptno] = jas_matrix_create(1, hdr->width))) {
            goto done;
        }
    }

    for (y = 0; y < hdr->height; ++y) {
        if (type == PNM_TYPE_PBM) {
            if (fmt == PNM_FMT_BIN) {
                for (x = 0; x < hdr->width;) {
                    if ((c = jas_stream_getc(in)) == EOF) {
                        goto done;
                    }
                    n = 8;
                    while (n > 0 && x < hdr->width) {
                        jas_matrix_set(data[0], 0, x, 1 - ((c >> 7) & 1));
                        c <<= 1;
                        --n;
                        ++x;
                    }
                }
            } else {
                for (x = 0; x < hdr->width; ++x) {
                    int uv;
                    if (pnm_getbitstr(in, &uv)) {
                        goto done;
                    }
                    jas_matrix_set(data[0], 0, x, 1 - uv);
                }
            }
        } else {
            for (x = 0; x < hdr->width; ++x) {
static DFBResult
IDirectFBImageProvider_JPEG2000_RenderTo( IDirectFBImageProvider *thiz,
                                          IDirectFBSurface       *destination,
                                          const DFBRectangle     *dest_rect )
{
     IDirectFBSurface_data  *dst_data;
     CoreSurface            *dst_surface;
     CoreSurfaceBufferLock   lock;
     DFBRectangle            rect;
     DFBRegion               clip;
     DIRenderCallbackResult  cb_result = DIRCR_OK;
     DFBResult               ret       = DFB_OK;
     
     DIRECT_INTERFACE_GET_DATA( IDirectFBImageProvider_JPEG2000 )
     
     if (!destination)
          return DFB_INVARG;
          
     dst_data = destination->priv;
     if (!dst_data || !dst_data->surface)
          return DFB_DESTROYED;
          
     dst_surface = dst_data->surface;
     
     if (dest_rect) {
          if (dest_rect->w < 1 || dest_rect->h < 1)
               return DFB_INVARG;
          rect = *dest_rect;
          rect.x += dst_data->area.wanted.x;
          rect.y += dst_data->area.wanted.y;
     }
     else {
          rect = dst_data->area.wanted;
     }
     
     dfb_region_from_rectangle( &clip, &dst_data->area.current );
     if (!dfb_rectangle_region_intersects( &rect, &clip ))
          return DFB_OK;

     ret = dfb_surface_lock_buffer( dst_surface, CSBR_BACK, CSAID_CPU, CSAF_WRITE, &lock );
     if (ret)
          return ret;
     
     if (!data->buf) {
          int  cmptlut[3];
          int  width, height;
          int  tlx, tly;
          int  hs, vs;
          int  i, j;
          bool direct, mono;
     
          if (jas_image_numcmpts(data->image) > 1) {
               cmptlut[0] = jas_image_getcmptbytype(data->image,
                              JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R));
               cmptlut[1] = jas_image_getcmptbytype(data->image,
                              JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G));
               cmptlut[2] = jas_image_getcmptbytype(data->image,
                              JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B));
               if (cmptlut[0] < 0 || cmptlut[1] < 0 || cmptlut[2] < 0) {
                    dfb_surface_unlock_buffer( dst_surface, &lock );
                    return DFB_UNSUPPORTED;
               }
               mono = false;
          }
          else {
               cmptlut[0] = cmptlut[1] = cmptlut[2] = 0;
               mono = true;
          }
     
          width = jas_image_width(data->image);
          height = jas_image_height(data->image);
          tlx = jas_image_cmpttlx(data->image, 0);
          tly = jas_image_cmpttly(data->image, 0);
          hs = jas_image_cmpthstep(data->image, 0);
          vs = jas_image_cmptvstep(data->image, 0);
          
          data->buf = D_MALLOC( width*height*4 );
          if (!data->buf) {
               dfb_surface_unlock_buffer( dst_surface, &lock );
               return D_OOM();
          }
          
          direct = (rect.w == width && rect.h == height && data->render_callback);
          
#define GET_SAMPLE( n, x, y ) ({ \
     int _s; \
     _s = jas_image_readcmptsample(data->image, cmptlut[n], x, y); \
     _s >>= jas_image_cmptprec(data->image, cmptlut[n]) - 8; \
     if (_s > 255) \
          _s = 255; \
     else if (_s < 0) \
          _s = 0; \
     _s; \
})
            
          for (i = 0; i < height; i++) {
               u32 *dst = data->buf + i * width;
               int  x, y;
               
               y = (i - tly) / vs;
               if (y >= 0 && y < height) {     
                    for (j = 0; j < width; j++) {
                         x = (j - tlx) / hs;
                         if (x >= 0 && x < width) {
                              unsigned int r, g, b;
                              if (mono) {
                                   r = g = b = GET_SAMPLE(0, x, y);
                              }
                              else {
                                   r = GET_SAMPLE(0, x, y);
                                   g = GET_SAMPLE(1, x, y);
                                   b = GET_SAMPLE(2, x, y);
                              }
                              *dst++ = 0xff000000 | (r << 16) | (g << 8) | b;
                         }
                         else {
                              *dst++ = 0;
                         }
                    }
               }
               else {
                    memset( dst, 0, width*4 );
               }
               
               if (direct) {
                    DFBRectangle r = { rect.x, rect.y+i, width, 1 };
                    
                    dfb_copy_buffer_32( data->buf + i*width,
                                        lock.addr, lock.pitch, &r, dst_surface, &clip );
                    
                    if (data->render_callback) {                    
                         r = (DFBRectangle) { 0, i, width, 1 };
                         cb_result = data->render_callback( &r, data->render_callback_ctx );
                         if (cb_result != DIRCR_OK)
                              break;
                    }
               }
          }
          
          if (!direct) {
               dfb_scale_linear_32( data->buf, width, height,
                                    lock.addr, lock.pitch, &rect, dst_surface, &clip );

               if (data->render_callback) {
                    DFBRectangle r = { 0, 0, width, height };
                    data->render_callback( &r, data->render_callback_ctx );
               }
          }
          
          if (cb_result != DIRCR_OK) {
               D_FREE( data->buf );
               data->buf = NULL;
               ret = DFB_INTERRUPTED;
          }
     }
     else {
          int width  = jas_image_width(data->image);
          int height = jas_image_height(data->image);
          
          dfb_scale_linear_32( data->buf, width, height,
                               lock.addr, lock.pitch, &rect, dst_surface, &clip );
          
          if (data->render_callback) {
               DFBRectangle r = {0, 0, width, height};
               data->render_callback( &r, data->render_callback_ctx );
          }
     }
     
     dfb_surface_unlock_buffer( dst_surface, &lock );
     
     return ret;
}
Пример #23
0
jas_image_t *jp2_decode(jas_stream_t *in, char *optstr)
{
	jp2_box_t *box;
	int found;
	jas_image_t *image;
	jp2_dec_t *dec;
	bool samedtype;
	int dtype;
	unsigned int i;
	jp2_cmap_t *cmapd;
	jp2_pclr_t *pclrd;
	jp2_cdef_t *cdefd;
	unsigned int channo;
	int newcmptno;
	int_fast32_t *lutents;
#if 0
	jp2_cdefchan_t *cdefent;
	int cmptno;
#endif
	jp2_cmapent_t *cmapent;
	jas_icchdr_t icchdr;
	jas_iccprof_t *iccprof;

	dec = 0;
	box = 0;
	image = 0;

	if (!(dec = jp2_dec_create())) {
		goto error;
	}

	/* Get the first box.  This should be a JP box. */
	if (!(box = jp2_box_get(in))) {
		jas_eprintf("error: cannot get box\n");
		goto error;
	}
	if (box->type != JP2_BOX_JP) {
		jas_eprintf("error: expecting signature box\n");
		goto error;
	}
	if (box->data.jp.magic != JP2_JP_MAGIC) {
		jas_eprintf("incorrect magic number\n");
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Get the second box.  This should be a FTYP box. */
	if (!(box = jp2_box_get(in))) {
		goto error;
	}
	if (box->type != JP2_BOX_FTYP) {
		jas_eprintf("expecting file type box\n");
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Get more boxes... */
	found = 0;
	while ((box = jp2_box_get(in))) {
		if (jas_getdbglevel() >= 1) {
			jas_eprintf("box type %s\n", box->info->name);
		}
		switch (box->type) {
		case JP2_BOX_JP2C:
			found = 1;
			break;
		case JP2_BOX_IHDR:
			if (!dec->ihdr) {
				dec->ihdr = box;
				box = 0;
			}
			break;
		case JP2_BOX_BPCC:
			if (!dec->bpcc) {
				dec->bpcc = box;
				box = 0;
			}
			break;
		case JP2_BOX_CDEF:
			if (!dec->cdef) {
				dec->cdef = box;
				box = 0;
			}
			break;
		case JP2_BOX_PCLR:
			if (!dec->pclr) {
				dec->pclr = box;
				box = 0;
			}
			break;
		case JP2_BOX_CMAP:
			if (!dec->cmap) {
				dec->cmap = box;
				box = 0;
			}
			break;
		case JP2_BOX_COLR:
			if (!dec->colr) {
				dec->colr = box;
				box = 0;
			}
			break;
		}
		if (box) {
			jp2_box_destroy(box);
			box = 0;
		}
		if (found) {
			break;
		}
	}

	if (!found) {
		jas_eprintf("error: no code stream found\n");
		goto error;
	}

	if (!(dec->image = jpc_decode(in, optstr))) {
		jas_eprintf("error: cannot decode code stream\n");
		goto error;
	}

	/* An IHDR box must be present. */
	if (!dec->ihdr) {
		jas_eprintf("error: missing IHDR box\n");
		goto error;
	}

	/* Does the number of components indicated in the IHDR box match
	  the value specified in the code stream? */
	if (dec->ihdr->data.ihdr.numcmpts != JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
		jas_eprintf("warning: number of components mismatch\n");
	}

	/* At least one component must be present. */
	if (!jas_image_numcmpts(dec->image)) {
		jas_eprintf("error: no components\n");
		goto error;
	}

	/* Determine if all components have the same data type. */
	samedtype = true;
	dtype = jas_image_cmptdtype(dec->image, 0);
	for (i = 1; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
		if (jas_image_cmptdtype(dec->image, i) != dtype) {
			samedtype = false;
			break;
		}
	}

	/* Is the component data type indicated in the IHDR box consistent
	  with the data in the code stream? */
	if ((samedtype && dec->ihdr->data.ihdr.bpc != JP2_DTYPETOBPC(dtype)) ||
	  (!samedtype && dec->ihdr->data.ihdr.bpc != JP2_IHDR_BPCNULL)) {
		jas_eprintf("warning: component data type mismatch\n");
	}

	/* Is the compression type supported? */
	if (dec->ihdr->data.ihdr.comptype != JP2_IHDR_COMPTYPE) {
		jas_eprintf("error: unsupported compression type\n");
		goto error;
	}

	if (dec->bpcc) {
		/* Is the number of components indicated in the BPCC box
		  consistent with the code stream data? */
		if (dec->bpcc->data.bpcc.numcmpts != JAS_CAST(uint, jas_image_numcmpts(
		  dec->image))) {
			jas_eprintf("warning: number of components mismatch\n");
		}
		/* Is the component data type information indicated in the BPCC
		  box consistent with the code stream data? */
		if (!samedtype) {
			for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
				if (jas_image_cmptdtype(dec->image, i) != JP2_BPCTODTYPE(dec->bpcc->data.bpcc.bpcs[i])) {
					jas_eprintf("warning: component data type mismatch\n");
				}
			}
		} else {
			jas_eprintf("warning: superfluous BPCC box\n");
		}
	}

	/* A COLR box must be present. */
	if (!dec->colr) {
		jas_eprintf("error: no COLR box\n");
		goto error;
	}

	switch (dec->colr->data.colr.method) {
	case JP2_COLR_ENUM:
		jas_image_setclrspc(dec->image, jp2_getcs(&dec->colr->data.colr));
		break;
	case JP2_COLR_ICC:
		iccprof = jas_iccprof_createfrombuf(dec->colr->data.colr.iccp,
		  dec->colr->data.colr.iccplen);
		assert(iccprof);
		jas_iccprof_gethdr(iccprof, &icchdr);
		jas_eprintf("ICC Profile CS %08x\n", icchdr.colorspc);
		jas_image_setclrspc(dec->image, fromiccpcs(icchdr.colorspc));
		dec->image->cmprof_ = jas_cmprof_createfromiccprof(iccprof);
		assert(dec->image->cmprof_);
		jas_iccprof_destroy(iccprof);
		break;
	}

	/* If a CMAP box is present, a PCLR box must also be present. */
	if (dec->cmap && !dec->pclr) {
		jas_eprintf("warning: missing PCLR box or superfluous CMAP box\n");
		jp2_box_destroy(dec->cmap);
		dec->cmap = 0;
	}

	/* If a CMAP box is not present, a PCLR box must not be present. */
	if (!dec->cmap && dec->pclr) {
		jas_eprintf("warning: missing CMAP box or superfluous PCLR box\n");
		jp2_box_destroy(dec->pclr);
		dec->pclr = 0;
	}

	/* Determine the number of channels (which is essentially the number
	  of components after any palette mappings have been applied). */
	dec->numchans = dec->cmap ? dec->cmap->data.cmap.numchans : JAS_CAST(uint, jas_image_numcmpts(dec->image));

	/* Perform a basic sanity check on the CMAP box if present. */
	if (dec->cmap) {
		for (i = 0; i < dec->numchans; ++i) {
			/* Is the component number reasonable? */
			if (dec->cmap->data.cmap.ents[i].cmptno >= JAS_CAST(uint, jas_image_numcmpts(dec->image))) {
				jas_eprintf("error: invalid component number in CMAP box\n");
				goto error;
			}
			/* Is the LUT index reasonable? */
			if (dec->cmap->data.cmap.ents[i].pcol >= dec->pclr->data.pclr.numchans) {
				jas_eprintf("error: invalid CMAP LUT index\n");
				goto error;
			}
		}
	}

	/* Allocate space for the channel-number to component-number LUT. */
	if (!(dec->chantocmptlut = jas_malloc(dec->numchans * sizeof(uint_fast16_t)))) {
		jas_eprintf("error: no memory\n");
		goto error;
	}

	if (!dec->cmap) {
		for (i = 0; i < dec->numchans; ++i) {
			dec->chantocmptlut[i] = i;
		}
	} else {
		cmapd = &dec->cmap->data.cmap;
		pclrd = &dec->pclr->data.pclr;
		cdefd = &dec->cdef->data.cdef;
		for (channo = 0; channo < cmapd->numchans; ++channo) {
			cmapent = &cmapd->ents[channo];
			if (cmapent->map == JP2_CMAP_DIRECT) {
				dec->chantocmptlut[channo] = channo;
			} else if (cmapent->map == JP2_CMAP_PALETTE) {
				lutents = jas_malloc(pclrd->numlutents * sizeof(int_fast32_t));
				for (i = 0; i < pclrd->numlutents; ++i) {
					lutents[i] = pclrd->lutdata[cmapent->pcol + i * pclrd->numchans];
				}
				newcmptno = jas_image_numcmpts(dec->image);
				jas_image_depalettize(dec->image, cmapent->cmptno, pclrd->numlutents, lutents, JP2_BPCTODTYPE(pclrd->bpc[cmapent->pcol]), newcmptno);
				dec->chantocmptlut[channo] = newcmptno;
				jas_free(lutents);
#if 0
				if (dec->cdef) {
					cdefent = jp2_cdef_lookup(cdefd, channo);
					if (!cdefent) {
						abort();
					}
				jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), cdefent->type, cdefent->assoc));
				} else {
				jas_image_setcmpttype(dec->image, newcmptno, jp2_getct(jas_image_clrspc(dec->image), 0, channo + 1));
				}
#endif
			}
		}
	}

	/* Mark all components as being of unknown type. */

	for (i = 0; i < JAS_CAST(uint, jas_image_numcmpts(dec->image)); ++i) {
		jas_image_setcmpttype(dec->image, i, JAS_IMAGE_CT_UNKNOWN);
	}

	/* Determine the type of each component. */
	if (dec->cdef) {
		for (i = 0; i < dec->numchans; ++i) {
			jas_image_setcmpttype(dec->image,
			  dec->chantocmptlut[dec->cdef->data.cdef.ents[i].channo],
			  jp2_getct(jas_image_clrspc(dec->image),
			  dec->cdef->data.cdef.ents[i].type, dec->cdef->data.cdef.ents[i].assoc));
		}
	} else {
		for (i = 0; i < dec->numchans; ++i) {
			jas_image_setcmpttype(dec->image, dec->chantocmptlut[i],
			  jp2_getct(jas_image_clrspc(dec->image), 0, i + 1));
		}
	}

	/* Delete any components that are not of interest. */
	for (i = jas_image_numcmpts(dec->image); i > 0; --i) {
		if (jas_image_cmpttype(dec->image, i - 1) == JAS_IMAGE_CT_UNKNOWN) {
			jas_image_delcmpt(dec->image, i - 1);
		}
	}

	/* Ensure that some components survived. */
	if (!jas_image_numcmpts(dec->image)) {
		jas_eprintf("error: no components\n");
		goto error;
	}
#if 0
jas_eprintf("no of components is %d\n", jas_image_numcmpts(dec->image));
#endif

	/* Prevent the image from being destroyed later. */
	image = dec->image;
	dec->image = 0;

	jp2_dec_destroy(dec);

	return image;

error:
	if (box) {
		jp2_box_destroy(box);
	}
	if (dec) {
		jp2_dec_destroy(dec);
	}
	return 0;
}
$NetBSD: patch-src_libjasper_jp2_jp2__enc.c,v 1.1 2016/05/16 14:03:40 he Exp $

Fix CVE-2008-3520, patches from
https://bugs.gentoo.org/show_bug.cgi?id=222819

--- src/libjasper/jp2/jp2_enc.c.orig	2007-01-19 21:43:05.000000000 +0000
+++ src/libjasper/jp2/jp2_enc.c
@@ -191,7 +191,7 @@ int sgnd;
 		}
 		bpcc = &box->data.bpcc;
 		bpcc->numcmpts = jas_image_numcmpts(image);
-		if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts *
+		if (!(bpcc->bpcs = jas_alloc2(bpcc->numcmpts,
 		  sizeof(uint_fast8_t)))) {
 			goto error;
 		}
@@ -285,7 +285,7 @@ int sgnd;
 		}
 		cdef = &box->data.cdef;
 		cdef->numchans = jas_image_numcmpts(image);
-		cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t));
+		cdef->ents = jas_alloc2(cdef->numchans, sizeof(jp2_cdefchan_t));
 		for (i = 0; i < jas_image_numcmpts(image); ++i) {
 			cdefchanent = &cdef->ents[i];
 			cdefchanent->channo = i;
@@ -343,7 +343,8 @@ int sgnd;
 	/* Output the JPEG-2000 code stream. */
 
 	overhead = jas_stream_getrwcount(out);
-	sprintf(buf, "%s\n_jp2overhead=%lu\n", (optstr ? optstr : ""),
+	snprintf(buf, sizeof buf, "%s\n_jp2overhead=%lu\n", 
Пример #25
0
// Internal function used to load the Jpeg2000 stream.
ILboolean iLoadJp2Internal(jas_stream_t	*Stream, ILimage *Image)
{
	jas_image_t		*Jp2Image = NULL;
	jas_matrix_t	*origdata;
	ILuint			x, y, c, Error;
	ILimage			*TempImage;

	// Decode image
	Jp2Image = jas_image_decode(Stream, -1, 0);
	if (!Jp2Image)
	{
		ilSetError(IL_ILLEGAL_FILE_VALUE);
		jas_stream_close(Stream);
		return IL_FALSE;
	}

	// JasPer likes to buffer a lot, so it may try buffering past the end
	//  of the file.  iread naturally sets IL_FILE_READ_ERROR if it tries
	//  reading past the end of the file, but this actually is not an error.
	Error = ilGetError();
	// Put the error back if it is not IL_FILE_READ_ERROR.
	if (Error != IL_FILE_READ_ERROR)
		ilSetError(Error);


	// We're not supporting anything other than 8 bits/component yet.
	if (jas_image_cmptprec(Jp2Image, 0) != 8)
	{
		jas_image_destroy(Jp2Image);
		ilSetError(IL_ILLEGAL_FILE_VALUE);
		return IL_FALSE;
	}

	switch (jas_image_numcmpts(Jp2Image))
	{
		//@TODO: Can we do alpha data?  jas_image_cmpttype always returns 0 for this case.
		case 1:  // Assuming this is luminance data.
			if (Image == NULL) {
				ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 1, IL_LUMINANCE, IL_UNSIGNED_BYTE, NULL);
				TempImage = iCurImage;
			}
			else {
				ifree(Image->Data);  // @TODO: Not really the most efficient way to do this...
				ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 1, IL_LUMINANCE, IL_UNSIGNED_BYTE, NULL);
				TempImage = Image;
			}
			break;

		case 2:  // Assuming this is luminance-alpha data.
			if (Image == NULL) {
				ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 2, IL_LUMINANCE_ALPHA, IL_UNSIGNED_BYTE, NULL);
				TempImage = iCurImage;
			}
			else {
				ifree(Image->Data);  // @TODO: Not really the most efficient way to do this...
				ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 2, IL_LUMINANCE_ALPHA, IL_UNSIGNED_BYTE, NULL);
				TempImage = Image;
			}
			break;

		case 3:
			if (Image == NULL) {
				ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL);
				TempImage = iCurImage;
			}
			else {
				ifree(Image->Data);  // @TODO: Not really the most efficient way to do this...
				ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL);
				TempImage = Image;
			}
			break;
		case 4:
			if (Image == NULL) {
				ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL);
				TempImage = iCurImage;
			}
			else {
				ifree(Image->Data);  // @TODO: Not really the most efficient way to do this...
				ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL);
				TempImage = Image;
			}
			break;
		default:
			jas_image_destroy(Jp2Image);
			ilSetError(IL_ILLEGAL_FILE_VALUE);
			return IL_FALSE;
	}
	TempImage->Origin = IL_ORIGIN_UPPER_LEFT;

	// JasPer stores the data channels separately.
	//  I am assuming RGBA format.  Is it possible for other formats to be included?
	for (c = 0; c < TempImage->Bpp; c++)
	{
		origdata = jas_matrix_create(TempImage->Height, TempImage->Width);
		if (!origdata)
		{
			ilSetError(IL_LIB_JP2_ERROR);
			return IL_FALSE;  // @TODO: Error
		}
		// Have to convert data into an intermediate matrix format.
		if (jas_image_readcmpt(Jp2Image, c, 0, 0, TempImage->Width, TempImage->Height, origdata))
		{
			return IL_FALSE;
		}

		for (y = 0; y < TempImage->Height; y++)
		{
			for (x = 0; x < TempImage->Width; x++)
			{
				TempImage->Data[y * TempImage->Width * TempImage->Bpp + x * TempImage->Bpp + c] = origdata->data_[y * origdata->numcols_ + x];
			}
		}

		jas_matrix_destroy(origdata);
	}

	jas_image_destroy(Jp2Image);

	return ilFixImage();
}
Пример #26
0
int pgx_encode(jas_image_t *image, jas_stream_t *out, char *optstr)
{
	pgx_hdr_t hdr;
	uint_fast32_t width;
	uint_fast32_t height;
	jas_bool sgnd;
	int prec;
	pgx_enc_t encbuf;
	pgx_enc_t *enc = &encbuf;

	/* Avoid compiler warnings about unused parameters. */
	optstr = 0;

	switch (jas_clrspc_fam(jas_image_clrspc(image))) {
	case JAS_CLRSPC_FAM_GRAY:
		if ((enc->cmpt = jas_image_getcmptbytype(image,
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_GRAY_Y))) < 0) {
			jas_eprintf("error: missing color component\n");
			return -1;
		}
		break;
	default:
		jas_eprintf("error: BMP format does not support color space\n");
		return -1;
		break;
	}

	width = jas_image_cmptwidth(image, enc->cmpt);
	height = jas_image_cmptheight(image, enc->cmpt);
	prec = jas_image_cmptprec(image, enc->cmpt);
	sgnd = jas_image_cmptsgnd(image, enc->cmpt);

	/* The PGX format is quite limited in the set of image geometries
	  that it can handle.  Here, we check to ensure that the image to
	  be saved can actually be represented reasonably accurately using the
	  PGX format. */
	/* There must be exactly one component. */
	if (jas_image_numcmpts(image) > 1 || prec > 16) {
		jas_eprintf("The PNM format cannot be used to represent an image with this geometry.\n");
		return -1;
	}

	hdr.magic = PGX_MAGIC;
	hdr.bigendian = jas_true;
	hdr.sgnd = sgnd;
	hdr.prec = prec;
	hdr.width = width;
	hdr.height = height;

#ifdef PGX_DEBUG
	pgx_dumphdr(&hdr);
#endif

	if (pgx_puthdr(out, &hdr)) {
		return -1;
	}

	if (pgx_putdata(out, &hdr, image, enc->cmpt)) {
		return -1;
	}

	return 0;
}
Пример #27
0
// Internal function used to load the Jpeg2000 stream.
ILboolean iLoadJp2Internal(jas_stream_t	*Stream, ILimage *Image)
{
	jas_image_t		*Jp2Image = NULL;
	jas_matrix_t	*origdata;
	ILuint			x, y, c;
	ILimage			*TempImage;

	// Decode image
	Jp2Image = jas_image_decode(Stream, -1, 0);
	if (!Jp2Image)
	{
		ilSetError(IL_ILLEGAL_FILE_VALUE);
		jas_stream_close(Stream);
		return IL_FALSE;
	}

	// We're not supporting anything other than 8 bits/component yet.
	if (jas_image_cmptprec(Jp2Image, 0) != 8)
	{
		jas_image_destroy(Jp2Image);
		ilSetError(IL_ILLEGAL_FILE_VALUE);
		return IL_FALSE;
	}

	switch (jas_image_numcmpts(Jp2Image))
	{
		case 3:
			if (Image == NULL) {
				ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL);
				TempImage = iCurImage;
			}
			else {
				ifree(Image->Data);  // @TODO: Not really the most efficient way to do this...
				ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 3, IL_RGB, IL_UNSIGNED_BYTE, NULL);
				TempImage = Image;
			}
			break;
		case 4:
			if (Image == NULL) {
				ilTexImage(jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL);
				TempImage = iCurImage;
			}
			else {
				ifree(Image->Data);  // @TODO: Not really the most efficient way to do this...
				ilInitImage(Image, jas_image_width(Jp2Image), jas_image_height(Jp2Image), 1, 4, IL_RGBA, IL_UNSIGNED_BYTE, NULL);
				TempImage = Image;
			}
			break;
		default:
			jas_image_destroy(Jp2Image);
			ilSetError(IL_ILLEGAL_FILE_VALUE);
			return IL_FALSE;
	}
	TempImage->Origin = IL_ORIGIN_UPPER_LEFT;

	// JasPer stores the data channels separately.
	//  I am assuming RGBA format.  Is it possible for other formats to be included?
	for (c = 0; c < TempImage->Bpp; c++)
	{
		origdata = jas_matrix_create(TempImage->Height, TempImage->Width);
		if (!origdata)
		{
			ilSetError(IL_LIB_JP2_ERROR);
			return IL_FALSE;  // @TODO: Error
		}
		// Have to convert data into an intermediate matrix format.
		if (jas_image_readcmpt(Jp2Image, c, 0, 0, TempImage->Width, TempImage->Height, origdata))
		{
			return IL_FALSE;
		}

		for (y = 0; y < TempImage->Height; y++)
		{
			for (x = 0; x < TempImage->Width; x++)
			{
				TempImage->Data[y * TempImage->Width * TempImage->Bpp + x * TempImage->Bpp + c] = origdata->data_[y * origdata->numcols_ + x];
			}
		}

		jas_matrix_destroy(origdata);
	}

	jas_image_destroy(Jp2Image);

	ilFixImage();

	return IL_TRUE;
}
Пример #28
0
int jp2_write_header(jas_image_t *image, jas_stream_t *out)
{
	jp2_box_t *box;
	jp2_ftyp_t *ftyp;
	jp2_ihdr_t *ihdr;
	jas_stream_t *tmpstream;
	int allcmptssame;
	jp2_bpcc_t *bpcc;
	long len;
	uint_fast16_t cmptno;
	jp2_colr_t *colr;
	jp2_cdefchan_t *cdefchanent;
	jp2_cdef_t *cdef;
	int i;
	uint_fast32_t typeasoc;
jas_iccprof_t *iccprof;
jas_stream_t *iccstream;
int pos;
int needcdef;
int prec;
int sgnd;

	box = 0;
	tmpstream = 0;

	allcmptssame = 1;
	sgnd = jas_image_cmptsgnd(image, 0);
	prec = jas_image_cmptprec(image, 0);
	for (i = 1; i < jas_image_numcmpts(image); ++i) {
		if (jas_image_cmptsgnd(image, i) != sgnd ||
		  jas_image_cmptprec(image, i) != prec) {
			allcmptssame = 0;
			break;
		}
	}

	/* Output the signature box. */

	if (!(box = jp2_box_create(JP2_BOX_JP))) {
		goto error;
	}
	box->data.jp.magic = JP2_JP_MAGIC;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Output the file type box. */

	if (!(box = jp2_box_create(JP2_BOX_FTYP))) {
		goto error;
	}
	ftyp = &box->data.ftyp;
	ftyp->majver = JP2_FTYP_MAJVER;
	ftyp->minver = JP2_FTYP_MINVER;
	ftyp->numcompatcodes = 1;
	ftyp->compatcodes[0] = JP2_FTYP_COMPATCODE;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/*
	 * Generate the data portion of the JP2 header box.
	 * We cannot simply output the header for this box
	 * since we do not yet know the correct value for the length
	 * field.
	 */

	if (!(tmpstream = jas_stream_memopen(0, 0))) {
		goto error;
	}

	/* Generate image header box. */

	if (!(box = jp2_box_create(JP2_BOX_IHDR))) {
		goto error;
	}
	ihdr = &box->data.ihdr;
	ihdr->width = jas_image_width(image);
	ihdr->height = jas_image_height(image);
	ihdr->numcmpts = jas_image_numcmpts(image);
	ihdr->bpc = allcmptssame ? JP2_SPTOBPC(jas_image_cmptsgnd(image, 0),
	  jas_image_cmptprec(image, 0)) : JP2_IHDR_BPCNULL;
	ihdr->comptype = JP2_IHDR_COMPTYPE;
	ihdr->csunk = 0;
	ihdr->ipr = 0;
	if (jp2_box_put(box, tmpstream)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	/* Generate bits per component box. */

	if (!allcmptssame) {
		if (!(box = jp2_box_create(JP2_BOX_BPCC))) {
			goto error;
		}
		bpcc = &box->data.bpcc;
		bpcc->numcmpts = jas_image_numcmpts(image);
		if (!(bpcc->bpcs = jas_malloc(bpcc->numcmpts *
		  sizeof(uint_fast8_t)))) {
			goto error;
		}
		for (cmptno = 0; cmptno < bpcc->numcmpts; ++cmptno) {
			bpcc->bpcs[cmptno] = JP2_SPTOBPC(jas_image_cmptsgnd(image,
			  cmptno), jas_image_cmptprec(image, cmptno));
		}
		if (jp2_box_put(box, tmpstream)) {
			goto error;
		}
		jp2_box_destroy(box);
		box = 0;
	}

	/* Generate color specification box. */

	if (!(box = jp2_box_create(JP2_BOX_COLR))) {
		goto error;
	}
	colr = &box->data.colr;
	switch (jas_image_clrspc(image)) {
	case JAS_CLRSPC_SRGB:
	case JAS_CLRSPC_SYCBCR:
	case JAS_CLRSPC_SGRAY:
		colr->method = JP2_COLR_ENUM;
		colr->csid = clrspctojp2(jas_image_clrspc(image));
		colr->pri = JP2_COLR_PRI;
		colr->approx = 0;
		break;
	default:
		colr->method = JP2_COLR_ICC;
		colr->pri = JP2_COLR_PRI;
		colr->approx = 0;
		iccprof = jas_iccprof_createfromcmprof(jas_image_cmprof(image));
		assert(iccprof);
		iccstream = jas_stream_memopen(0, 0);
		assert(iccstream);
		if (jas_iccprof_save(iccprof, iccstream))
			abort();
		if ((pos = jas_stream_tell(iccstream)) < 0)
			abort();
		colr->iccplen = pos;
		colr->iccp = jas_malloc(pos);
		assert(colr->iccp);
		jas_stream_rewind(iccstream);
		if (jas_stream_read(iccstream, colr->iccp, colr->iccplen) != colr->iccplen)
			abort();
		jas_stream_close(iccstream);
		jas_iccprof_destroy(iccprof);
		break;
	}
	if (jp2_box_put(box, tmpstream)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	needcdef = 1;
	switch (jas_clrspc_fam(jas_image_clrspc(image))) {
	case JAS_CLRSPC_FAM_RGB:
		if (jas_image_cmpttype(image, 0) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_R) &&
		  jas_image_cmpttype(image, 1) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_G) &&
		  jas_image_cmpttype(image, 2) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_RGB_B))
			needcdef = 0;
		break;
	case JAS_CLRSPC_FAM_YCBCR:
		if (jas_image_cmpttype(image, 0) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_Y) &&
		  jas_image_cmpttype(image, 1) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CB) &&
		  jas_image_cmpttype(image, 2) ==
		  JAS_IMAGE_CT_COLOR(JAS_CLRSPC_CHANIND_YCBCR_CR))
			needcdef = 0;
		break;
	case JAS_CLRSPC_FAM_GRAY:
		if (jas_image_cmpttype(image, 0) ==
		  JAS_IMAGE_CT_COLOR(JAS_IMAGE_CT_GRAY_Y))
			needcdef = 0;
		break;
	default:
		abort();
		break;
	}

	if (needcdef) {
		if (!(box = jp2_box_create(JP2_BOX_CDEF))) {
			goto error;
		}
		cdef = &box->data.cdef;
		cdef->numchans = jas_image_numcmpts(image);
		cdef->ents = jas_malloc(cdef->numchans * sizeof(jp2_cdefchan_t));
		for (i = 0; i < jas_image_numcmpts(image); ++i) {
			cdefchanent = &cdef->ents[i];
			cdefchanent->channo = i;
			typeasoc = jp2_gettypeasoc(jas_image_clrspc(image), jas_image_cmpttype(image, i));
			cdefchanent->type = typeasoc >> 16;
			cdefchanent->assoc = typeasoc & 0x7fff;
		}
		if (jp2_box_put(box, tmpstream)) {
			goto error;
		}
		jp2_box_destroy(box);
		box = 0;
	}

	/* Determine the total length of the JP2 header box. */

	len = jas_stream_tell(tmpstream);
	jas_stream_rewind(tmpstream);

	/*
	 * Output the JP2 header box and all of the boxes which it contains.
	 */

	if (!(box = jp2_box_create(JP2_BOX_JP2H))) {
		goto error;
	}
	box->len = len + JP2_BOX_HDRLEN;
	if (jp2_box_put(box, out)) {
		goto error;
	}
	jp2_box_destroy(box);
	box = 0;

	if (jas_stream_copy(out, tmpstream, len)) {
		goto error;
	}

	jas_stream_close(tmpstream);
	tmpstream = 0;

	return 0;
	abort();

error:

	if (box) {
		jp2_box_destroy(box);
	}
	if (tmpstream) {
		jas_stream_close(tmpstream);
	}
	return -1;
}
Пример #29
0
int main(int argc, char **argv)
{
	int fmtid;
	int id;
	char *infile;
	jas_stream_t *instream;
	jas_image_t *image;
	int width;
	int height;
	int depth;
	int numcmpts;
	int verbose;
	char *fmtname;

	if (jas_init()) {
		errprint(0, "error: cannot initialize jasper library\n");
		abort();
	}

	/* set our error callback */
	jas_set_error_cb(errprint);

	cmdname = argv[0];

	infile = 0;
	verbose = 0;

	/* Parse the command line options. */
	while ((id = jas_getopt(argc, argv, opts)) >= 0) {
		switch (id) {
		case OPT_VERBOSE:
			verbose = 1;
			break;
		case OPT_VERSION:
			printf("%s\n", JAS_VERSION);
			exit(EXIT_SUCCESS);
			break;
		case OPT_INFILE:
			infile = jas_optarg;
			break;
		case OPT_HELP:
		default:
			usage();
			break;
		}
	}

	/* Open the image file. */
	if (infile) {
		/* The image is to be read from a file. */
		if (!(instream = jas_stream_fopen(infile, "rb"))) {
			jas_eprintf("cannot open input image file %s\n", infile);
			exit(EXIT_FAILURE);
		}
	} else {
		/* The image is to be read from standard input. */
		if (!(instream = jas_stream_fdopen(0, "rb"))) {
			jas_eprintf("cannot open standard input\n");
			exit(EXIT_FAILURE);
		}
	}

	if ((fmtid = jas_image_getfmt(instream)) < 0) {
		jas_eprintf("unknown image format\n");
	}

	/* Decode the image. */
	if (!(image = jas_image_decode(instream, fmtid, 0))) {
		jas_eprintf("cannot load image\n");
		return EXIT_FAILURE;
	}

	/* Close the image file. */
	jas_stream_close(instream);

	numcmpts = jas_image_numcmpts(image);
	width = jas_image_cmptwidth(image, 0);
	height = jas_image_cmptheight(image, 0);
	depth = jas_image_cmptprec(image, 0);
	if (!(fmtname = jas_image_fmttostr(fmtid))) {
		abort();
	}
	jas_eprintf("%s %d %d %d %d %ld\n", fmtname, numcmpts, width, height, depth, (long) jas_image_rawsize(image));

	jas_image_destroy(image);
	jas_image_clearfmts();

	return EXIT_SUCCESS;
}