Esempio n. 1
0
const char* fallbackEngineInfoLLImageJ2CImpl()
{
	static std::string version_string =
		std::string("OpenJPEG: " OPENJPEG_VERSION ", Runtime: ")
		+ opj_version();
	return version_string.c_str();
}
Esempio n. 2
0
/* -------------------------------------------------------------------------- */
static void decode_help_display(void)
{
    fprintf(stdout,"\nThis is the opj_dump utility from the OpenJPEG project.\n"
            "It dumps JPEG 2000 codestream info to stdout or a given file.\n"
            "It has been compiled against openjp2 library v%s.\n\n",opj_version());

    fprintf(stdout,"Parameters:\n");
    fprintf(stdout,"-----------\n");
    fprintf(stdout,"\n");
    fprintf(stdout,"  -ImgDir <directory>\n");
    fprintf(stdout,"	Image file Directory path \n");
    fprintf(stdout,"  -i <compressed file>\n");
    fprintf(stdout,"    REQUIRED only if an Input image directory not specified\n");
    fprintf(stdout,"    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n");
    fprintf(stdout,"    is identified based on its suffix.\n");
    fprintf(stdout,"  -o <output file>\n");
    fprintf(stdout,"    OPTIONAL\n");
    fprintf(stdout,"    Output file where file info will be dump.\n");
    fprintf(stdout,"    By default it will be in the stdout.\n");
    fprintf(stdout,"  -v "); /* FIXME WIP_MSD */
    fprintf(stdout,"    OPTIONAL\n");
    fprintf(stdout,"    Enable informative messages\n");
    fprintf(stdout,"    By default verbose mode is off.\n");
    fprintf(stdout,"\n");
}
Esempio n. 3
0
int imagetopnm(opj_image_t * image,
               QBuffer &buffer)
{
  int *red, *green, *blue, *alpha = NULL;
  int wr, hr, max;
  int i;
  unsigned int compno, ncomp;
  int adjustR, adjustG, adjustB, adjustA;
  int two, has_alpha, triple;
  int prec, v;
  char bufferLocal[1024];
  QDataStream str (&buffer);

  if((prec = (int)image->comps[0].prec) > 16)
  {
    fprintf(stderr,"%s:%d:imagetopnm\n\tprecision %d is larger than 16"
            "\n\t: refused.\n",__FILE__,__LINE__,prec);
    return 1;
  }
  two = has_alpha = 0;
  ncomp = image->numcomps;

  if (ncomp == 2 /* GRAYA */
      || (ncomp > 2 /* RGB, RGBA */
          && image->comps[0].dx == image->comps[1].dx
          && image->comps[1].dx == image->comps[2].dx
          && image->comps[0].dy == image->comps[1].dy
          && image->comps[1].dy == image->comps[2].dy
          && image->comps[0].prec == image->comps[1].prec
          && image->comps[1].prec == image->comps[2].prec
          ))
  {
    two = (prec > 8);
    triple = (ncomp > 2);
    wr = (int)image->comps[0].w; hr = (int)image->comps[0].h;
    max = (1<<prec) - 1; has_alpha = (ncomp == 4 || ncomp == 2);

    red = image->comps[0].data;

    if(triple)
    {
      green = image->comps[1].data;
      blue = image->comps[2].data;
    }
    else green = blue = NULL;

    if(has_alpha)
    {
      const char *tt = (triple?"RGB_ALPHA":"GRAYSCALE_ALPHA");

      sprintf(bufferLocal,
              "P7\n# OpenJPEG-%s\nWIDTH %d\nHEIGHT %d\nDEPTH %d\n"
              "MAXVAL %d\nTUPLTYPE %s\nENDHDR\n",
              opj_version(),
              wr,
              hr,
              ncomp,
              max,
              tt);
      str.writeRawData (bufferLocal,
                        strlen (bufferLocal));
      alpha = image->comps[ncomp - 1].data;
      adjustA = (image->comps[ncomp - 1].sgnd ?
                 1 << (image->comps[ncomp - 1].prec - 1) : 0);
    }
    else
    {
      sprintf(bufferLocal,
              "P6\n# OpenJPEG-%s\n%d %d\n%d\n",
              opj_version(),
              wr,
              hr,
              max);
      str.writeRawData (bufferLocal,
                        strlen (bufferLocal));
      adjustA = 0;
    }
    adjustR = (image->comps[0].sgnd ? 1 << (image->comps[0].prec - 1) : 0);

    if(triple)
    {
      adjustG = (image->comps[1].sgnd ? 1 << (image->comps[1].prec - 1) : 0);
      adjustB = (image->comps[2].sgnd ? 1 << (image->comps[2].prec - 1) : 0);
    }
    else adjustG = adjustB = 0;

    for(i = 0; i < wr * hr; ++i)
    {
      if(two)
      {
        v = *red + adjustR; ++red;
        if(v > 65535) v = 65535; else if(v < 0) v = 0;

        sprintf(bufferLocal,
                "%c%c",
                (unsigned char)(v>>8),
                (unsigned char)v);
        str.writeRawData (bufferLocal,
                          2);

        if(triple)
        {
          v = *green + adjustG; ++green;
          if(v > 65535) v = 65535; else if(v < 0) v = 0;

          sprintf(bufferLocal,
                  "%c%c",
                  (unsigned char)(v>>8),
                  (unsigned char)v);
          str.writeRawData  (bufferLocal,
                             2);

          v =  *blue + adjustB; ++blue;
          if(v > 65535) v = 65535; else if(v < 0) v = 0;

          sprintf(bufferLocal,
                  "%c%c",
                  (unsigned char)(v>>8),
                  (unsigned char)v);
          str.writeRawData (bufferLocal,
                            2);

        }/* if(triple) */

        if(has_alpha)
        {
          v = *alpha + adjustA; ++alpha;
          if(v > 65535) v = 65535; else if(v < 0) v = 0;

          sprintf(bufferLocal,
                  "%c%c",
                  (unsigned char)(v>>8),
                  (unsigned char)v);
          str.writeRawData (bufferLocal,
                            2);
        }
        continue;

      }	/* if(two) */

      /* prec <= 8: */
      v = *red++;
      if(v > 255) v = 255; else if(v < 0) v = 0;

      sprintf(bufferLocal,
              "%c",
              (unsigned char)v);
      str.writeRawData (bufferLocal,
                        1);
      if(triple)
      {
	v = *green++;
	if(v > 255) v = 255; else if(v < 0) v = 0;

        sprintf(bufferLocal,
                "%c",
                (unsigned char)v);
        str.writeRawData (bufferLocal,
                          1);
	v = *blue++;
	if(v > 255) v = 255; else if(v < 0) v = 0;

        sprintf(bufferLocal,
                "%c",
                (unsigned char)v);
        str.writeRawData (bufferLocal,
                          1);
      }
      if(has_alpha)
      {
	v = *alpha++;
	if(v > 255) v = 255; else if(v < 0) v = 0;

        sprintf(bufferLocal,
                "%c",
                (unsigned char)v);
        str.writeRawData (bufferLocal,
                          1);
      }
    }	/* for(i */

    return 0;
  }
/*!
 *  getImagelibVersions()
 *
 *      Return: string of version numbers; e.g.,
 *               libgif 5.0.3
 *               libjpeg 8b
 *               libpng 1.4.3
 *               libtiff 3.9.5
 *               zlib 1.2.5
 *               libwebp 0.3.0
 *               libopenjp2 2.1.0
 *
 *  Notes:
 *      (1) The caller has responsibility to free the memory.
 */
char *
getImagelibVersions()
{
char     buf[128];
l_int32  first = TRUE;

#if HAVE_LIBJPEG
    struct jpeg_compress_struct cinfo;
    struct jpeg_error_mgr err;
    char buffer[JMSG_LENGTH_MAX];
#endif
    char *tempStrP;
    char *versionNumP;
    char *nextTokenP;
    char *versionStrP = stringNew("");

#if HAVE_LIBGIF
    first = FALSE;
    stringJoinInPlace(versionStrP, "libgif ");
  #ifdef GIFLIB_MAJOR
    snprintf(buf, sizeof(buf), "%d.%d.%d", GIFLIB_MAJOR, GIFLIB_MINOR,
             GIFLIB_RELEASE);
  #else
    stringCopy(buf, "4.1.6(?)", sizeof(buf));
  #endif
    stringJoinInPlace(versionStrP, buf);
#endif

#if HAVE_LIBJPEG
    cinfo.err = jpeg_std_error(&err);
    err.msg_code = JMSG_VERSION;
    (*err.format_message) ((j_common_ptr ) &cinfo, buffer);

    if (!first) stringJoinInPlace(versionStrP, " : ");
    first = FALSE;
    stringJoinInPlace(versionStrP, "libjpeg ");
    versionNumP = strtokSafe(buffer, " ", &nextTokenP);
    stringJoinInPlace(versionStrP, versionNumP);
    FREE(versionNumP);
#endif

#if HAVE_LIBPNG
    if (!first) stringJoinInPlace(versionStrP, " : ");
    first = FALSE;
    stringJoinInPlace(versionStrP, "libpng ");
    stringJoinInPlace(versionStrP, png_get_libpng_ver(NULL));
#endif

#if HAVE_LIBTIFF
    if (!first) stringJoinInPlace(versionStrP, " : ");
    first = FALSE;
    stringJoinInPlace(versionStrP, "libtiff ");
    versionNumP = strtokSafe((char *)TIFFGetVersion(), " \n", &nextTokenP);
    FREE(versionNumP);
    versionNumP = strtokSafe(NULL, " \n", &nextTokenP);
    FREE(versionNumP);
    versionNumP = strtokSafe(NULL, " \n", &nextTokenP);
    stringJoinInPlace(versionStrP, versionNumP);
    FREE(versionNumP);
#endif

#if HAVE_LIBZ
    if (!first) stringJoinInPlace(versionStrP, " : ");
    first = FALSE;
    stringJoinInPlace(versionStrP, "zlib ");
    stringJoinInPlace(versionStrP, zlibVersion());
#endif

#if HAVE_LIBWEBP
    {
    l_int32 val;
    char buf[32];
    if (!first) stringJoinInPlace(versionStrP, " : ");
    first = FALSE;
    stringJoinInPlace(versionStrP, "libwebp ");
    val = WebPGetEncoderVersion();
    snprintf(buf, sizeof(buf), "%d.%d.%d", val >> 16, (val >> 8) & 0xff,
             val & 0xff);
    stringJoinInPlace(versionStrP, buf);
    }
#endif

#if HAVE_LIBJP2K
    {
    const char *version;
    if (!first) stringJoinInPlace(versionStrP, " : ");
    first = FALSE;
    stringJoinInPlace(versionStrP, "libopenjp2 ");
    version = opj_version();
    stringJoinInPlace(versionStrP, version);
    }
#endif

    stringJoinInPlace(versionStrP, "\n");
    return versionStrP;
}
Esempio n. 5
0
/*!
 *  getImagelibVersions()
 *
 *      Return: string of version numbers; e.g.,
 *               libgif 5.0.3
 *               libjpeg 8b (libjpeg-turbo 1.3.0)
 *               libpng 1.4.3
 *               libtiff 3.9.5
 *               zlib 1.2.5
 *               libwebp 0.3.0
 *               libopenjp2 2.1.0
 *
 *  Notes:
 *      (1) The caller must free the memory.
 */
char *
getImagelibVersions()
{
char     buf[128];
l_int32  first = TRUE;
char    *versionNumP;
char    *nextTokenP;
char    *versionStrP = NULL;

#if HAVE_LIBGIF
    first = FALSE;
    stringJoinIP(&versionStrP, "libgif ");
  #ifdef GIFLIB_MAJOR
    snprintf(buf, sizeof(buf), "%d.%d.%d", GIFLIB_MAJOR, GIFLIB_MINOR,
             GIFLIB_RELEASE);
  #else
    stringCopy(buf, "4.1.6(?)", sizeof(buf));
  #endif
    stringJoinIP(&versionStrP, buf);
#endif  /* HAVE_LIBGIF */

#if HAVE_LIBJPEG
    {
    struct jpeg_compress_struct  cinfo;
    struct jpeg_error_mgr        err;
    char                         buffer[JMSG_LENGTH_MAX];
    cinfo.err = jpeg_std_error(&err);
    err.msg_code = JMSG_VERSION;
    (*err.format_message) ((j_common_ptr ) &cinfo, buffer);

    if (!first) stringJoinIP(&versionStrP, " : ");
    first = FALSE;
    stringJoinIP(&versionStrP, "libjpeg ");
    versionNumP = strtokSafe(buffer, " ", &nextTokenP);
    stringJoinIP(&versionStrP, versionNumP);
    FREE(versionNumP);

  #if defined(LIBJPEG_TURBO_VERSION)
        /* To stringify the result of expansion of a macro argument,
         * you must use two levels of macros.  See:
         *   https://gcc.gnu.org/onlinedocs/cpp/Stringification.html  */
  #define l_xstr(s) l_str(s)
  #define l_str(s) #s
    snprintf(buf, sizeof(buf), " (libjpeg-turbo %s)",
             l_xstr(LIBJPEG_TURBO_VERSION));
    stringJoinIP(&versionStrP, buf);
  #endif  /* LIBJPEG_TURBO_VERSION */
    }
#endif  /* HAVE_LIBJPEG */

#if HAVE_LIBPNG
    if (!first) stringJoinIP(&versionStrP, " : ");
    first = FALSE;
    stringJoinIP(&versionStrP, "libpng ");
    stringJoinIP(&versionStrP, png_get_libpng_ver(NULL));
#endif  /* HAVE_LIBPNG */

#if HAVE_LIBTIFF
    if (!first) stringJoinIP(&versionStrP, " : ");
    first = FALSE;
    stringJoinIP(&versionStrP, "libtiff ");
    versionNumP = strtokSafe((char *)TIFFGetVersion(), " \n", &nextTokenP);
    FREE(versionNumP);
    versionNumP = strtokSafe(NULL, " \n", &nextTokenP);
    FREE(versionNumP);
    versionNumP = strtokSafe(NULL, " \n", &nextTokenP);
    stringJoinIP(&versionStrP, versionNumP);
    FREE(versionNumP);
#endif  /* HAVE_LIBTIFF */

#if HAVE_LIBZ
    if (!first) stringJoinIP(&versionStrP, " : ");
    first = FALSE;
    stringJoinIP(&versionStrP, "zlib ");
    stringJoinIP(&versionStrP, zlibVersion());
#endif  /* HAVE_LIBZ */

#if HAVE_LIBWEBP
    {
    l_int32 val;
    char buf[32];
    if (!first) stringJoinIP(&versionStrP, " : ");
    first = FALSE;
    stringJoinIP(&versionStrP, "libwebp ");
    val = WebPGetEncoderVersion();
    snprintf(buf, sizeof(buf), "%d.%d.%d", val >> 16, (val >> 8) & 0xff,
             val & 0xff);
    stringJoinIP(&versionStrP, buf);
    }
#endif  /* HAVE_LIBWEBP */

#if HAVE_LIBJP2K
    {
    const char *version;
    if (!first) stringJoinIP(&versionStrP, " : ");
    first = FALSE;
    stringJoinIP(&versionStrP, "libopenjp2 ");
    version = opj_version();
    stringJoinIP(&versionStrP, version);
    }
#endif  /* HAVE_LIBJP2K */

    stringJoinIP(&versionStrP, "\n");
    return versionStrP;
}
Esempio n. 6
0
/* -------------------------------------------------------------------------- */
static void decode_help_display(void) {
	fprintf(stdout,"\nThis is the opj_decompress utility from the OpenJPEG project.\n"
	               "It decompresses JPEG 2000 codestreams to various image formats.\n"
	               "It has been compiled against openjp2 library v%s.\n\n",opj_version());

	fprintf(stdout,"Parameters:\n"
	               "-----------\n"
	               "\n"
	               "  -ImgDir <directory> \n"
	               "	Image file Directory path \n"
	               "  -OutFor <PBM|PGM|PPM|PNM|PAM|PGX|PNG|BMP|TIF|RAW|RAWL|TGA>\n"
	               "    REQUIRED only if -ImgDir is used\n"
	               "	Output format for decompressed images.\n");
	fprintf(stdout,"  -i <compressed file>\n"
	               "    REQUIRED only if an Input image directory is not specified\n"
	               "    Currently accepts J2K-files, JP2-files and JPT-files. The file type\n"
	               "    is identified based on its suffix.\n");
	fprintf(stdout,"  -o <decompressed file>\n"
	               "    REQUIRED\n"
	               "    Currently accepts formats specified above (see OutFor option)\n"
	               "    Binary data is written to the file (not ascii). If a PGX\n"
	               "    filename is given, there will be as many output files as there are\n"
	               "    components: an indice starting from 0 will then be appended to the\n"
	               "    output filename, just before the \"pgx\" extension. If a PGM filename\n"
	               "    is given and there are more than one component, only the first component\n"
	               "    will be written to the file.\n");
	fprintf(stdout,"  -r <reduce factor>\n"
	               "    Set the number of highest resolution levels to be discarded. The\n"
	               "    image resolution is effectively divided by 2 to the power of the\n"
	               "    number of discarded levels. The reduce factor is limited by the\n"
	               "    smallest total number of decomposition levels among tiles.\n"
	               "  -l <number of quality layers to decode>\n"
	               "    Set the maximum number of quality layers to decode. If there are\n"
	               "    less quality layers than the specified number, all the quality layers\n"
	               "    are decoded.\n");
	fprintf(stdout,"  -x  \n"
	               "    Create an index file *.Idx (-x index_name.Idx) \n"
	               "  -d <x0,y0,x1,y1>\n"
	               "    OPTIONAL\n"
	               "    Decoding area\n"
	               "    By default all the image is decoded.\n"
	               "  -t <tile_number>\n"
	               "    OPTIONAL\n"
	               "    Set the tile number of the decoded tile. Follow the JPEG2000 convention from left-up to bottom-up\n"
	               "    By default all tiles are decoded.\n");
	fprintf(stdout,"  -p <comp 0 precision>[C|S][,<comp 1 precision>[C|S][,...]]\n"
	               "    OPTIONAL\n"
	               "    Force the precision (bit depth) of components.\n");
	fprintf(stdout,"    There shall be at least 1 value. Theres no limit on the number of values (comma separated, last values ignored if too much values).\n"
	               "    If there are less values than components, the last value is used for remaining components.\n"
	               "    If 'C' is specified (default), values are clipped.\n"
	               "    If 'S' is specified, values are scaled.\n"
	               "    A 0 value can be specified (meaning original bit depth).\n");
	fprintf(stdout,"  -force-rgb\n"
	               "    Force output image colorspace to RGB\n"
	               "  -upsample\n"
	               "    Downsampled components will be upsampled to image size\n"
	               "  -split-pnm\n"
	               "    Split output components to different files when writing to PNM\n"
	               "\n");
/* UniPG>> */
#ifdef USE_JPWL
	fprintf(stdout,"  -W <options>\n"
	               "    Activates the JPWL correction capability, if the codestream complies.\n"
	               "    Options can be a comma separated list of <param=val> tokens:\n"
	               "    c, c=numcomps\n"
	               "       numcomps is the number of expected components in the codestream\n"
	               "       (search of first EPB rely upon this, default is %d)\n", JPWL_EXPECTED_COMPONENTS);
#endif /* USE_JPWL */
/* <<UniPG */
	fprintf(stdout,"\n");
}
Esempio n. 7
0
int main(int argc, char **argv)
{
	mj2_cparameters_t mj2_parameters;	/* MJ2 compression parameters */
	opj_cparameters_t *j2k_parameters;	/* J2K compression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_cio_t *cio;
	int value;
	opj_mj2_t *movie;
	opj_image_t *img;
	int i, j;
	char *s, S1, S2, S3;
	unsigned char *buf;
	int x1, y1,  len;
	long mdat_initpos, offset;
	FILE *mj2file;
	int sampleno;  
	opj_cinfo_t* cinfo;
	opj_bool bSuccess;
	int numframes;
	int prec = 8;/* DEFAULT */
	double total_time = 0;	

	memset(&mj2_parameters, 0, sizeof(mj2_cparameters_t));
  /* default value */
  /* ------------- */
	mj2_parameters.w = 352;			/* CIF default value*/
	mj2_parameters.h = 288;			/* CIF default value*/
	mj2_parameters.CbCr_subsampling_dx = 2;	/* CIF default value*/
	mj2_parameters.CbCr_subsampling_dy = 2;	/* CIF default value*/
	mj2_parameters.frame_rate = 25;
	mj2_parameters.prec = 8; /* DEFAULT */
	mj2_parameters.enumcs = ENUMCS_SYCC; /* FIXME: ENUMCS_YUV420 */
	mj2_parameters.meth = 1; /* enumerated color space */

/*
	configure the event callbacks (not required)
	setting of each callback is optionnal
*/
	memset(&event_mgr, 0, sizeof(opj_event_mgr_t));
	event_mgr.error_handler = error_callback;
	event_mgr.warning_handler = warning_callback;
	event_mgr.info_handler = NULL;
    
	/* set J2K encoding parameters to default values */
	opj_set_default_encoder_parameters(&mj2_parameters.j2k_parameters);
	j2k_parameters = &mj2_parameters.j2k_parameters;

	/* Create comment for codestream */
	if(j2k_parameters->cp_comment == NULL) {
    const char comment[] = "Created by OpenJPEG version ";
		const size_t clen = strlen(comment);
    const char *version = opj_version();
		j2k_parameters->cp_comment = (char*)malloc(clen+strlen(version)+1);
		sprintf(j2k_parameters->cp_comment,"%s%s", comment, version);
	}

  while (1) {
    int c = opj_getopt(argc, argv,
      "i:o:r:q:f:t:n:c:b:p:s:d:P:S:E:M:R:T:C:I:W:F:D:h");
    if (c == -1)
      break;
    switch (c) {
    case 'i':			/* IN fill */
			{
				char *infile = opj_optarg;
				s = opj_optarg;
				while (*s) {
					s++;
				}
				s--;
				S3 = *s;
				s--;
				S2 = *s;
				s--;
				S1 = *s;
				
				if ((S1 == 'y' && S2 == 'u' && S3 == 'v')
					|| (S1 == 'Y' && S2 == 'U' && S3 == 'V')) {
					mj2_parameters.decod_format = YUV_DFMT;				
				}
				else {
					fprintf(stderr,
						"!! Unrecognized format for infile : %c%c%c [accept only *.yuv] !!\n\n",
						S1, S2, S3);
					return 1;
				}
				strncpy(mj2_parameters.infile, infile, sizeof(mj2_parameters.infile)-1);
			}
      break;
      /* ----------------------------------------------------- */
    case 'o':			/* OUT fill */
			{
				char *outfile = opj_optarg;
				while (*outfile) {
					outfile++;
				}
				outfile--;
				S3 = *outfile;
				outfile--;
				S2 = *outfile;
				outfile--;
				S1 = *outfile;
				
				outfile = opj_optarg;
				
				if ((S1 == 'm' && S2 == 'j' && S3 == '2')
					|| (S1 == 'M' && S2 == 'J' && S3 == '2'))
					mj2_parameters.cod_format = MJ2_CFMT;
				else {
					fprintf(stderr,
						"Unknown output format image *.%c%c%c [only *.mj2]!! \n",
						S1, S2, S3);
					return 1;
				}
				strncpy(mj2_parameters.outfile, outfile, sizeof(mj2_parameters.outfile)-1);      
      }
      break;
      /* ----------------------------------------------------- */
    case 'r':			/* rates rates/distorsion */
			{
				float rate;
				s = opj_optarg;
				while (sscanf(s, "%f", &rate) == 1) {
					j2k_parameters->tcp_rates[j2k_parameters->tcp_numlayers] = rate * 2;
					j2k_parameters->tcp_numlayers++;
					while (*s && *s != ',') {
						s++;
					}
					if (!*s)
						break;
					s++;
				}
				j2k_parameters->cp_disto_alloc = 1;
			}
      break;
      /* ----------------------------------------------------- */
    case 'q':			/* add fixed_quality */
      s = opj_optarg;
			while (sscanf(s, "%f", &j2k_parameters->tcp_distoratio[j2k_parameters->tcp_numlayers]) == 1) {
				j2k_parameters->tcp_numlayers++;
				while (*s && *s != ',') {
					s++;
				}
				if (!*s)
					break;
				s++;
			}
			j2k_parameters->cp_fixed_quality = 1;
      break;
      /* dda */
      /* ----------------------------------------------------- */
    case 'f':			/* mod fixed_quality (before : -q) */
			{
				int *row = NULL, *col = NULL;
				int numlayers = 0, numresolution = 0, matrix_width = 0;
				
				s = opj_optarg;
				sscanf(s, "%d", &numlayers);
				s++;
				if (numlayers > 9)
					s++;
				
				j2k_parameters->tcp_numlayers = numlayers;
				numresolution = j2k_parameters->numresolution;
				matrix_width = numresolution * 3;
				j2k_parameters->cp_matrice = (int *) malloc(numlayers * matrix_width * sizeof(int));
				s = s + 2;
				
				for (i = 0; i < numlayers; i++) {
					row = &j2k_parameters->cp_matrice[i * matrix_width];
					col = row;
					j2k_parameters->tcp_rates[i] = 1;
					sscanf(s, "%d,", &col[0]);
					s += 2;
					if (col[0] > 9)
						s++;
					col[1] = 0;
					col[2] = 0;
					for (j = 1; j < numresolution; j++) {
						col += 3;
						sscanf(s, "%d,%d,%d", &col[0], &col[1], &col[2]);
						s += 6;
						if (col[0] > 9)
							s++;
						if (col[1] > 9)
							s++;
						if (col[2] > 9)
							s++;
					}
					if (i < numlayers - 1)
						s++;
				}
				j2k_parameters->cp_fixed_alloc = 1;
			}
			break;
      /* ----------------------------------------------------- */
    case 't':			/* tiles */
      sscanf(opj_optarg, "%d,%d", &j2k_parameters->cp_tdx, &j2k_parameters->cp_tdy);
			j2k_parameters->tile_size_on = OPJ_TRUE;
      break;
      /* ----------------------------------------------------- */
    case 'n':			/* resolution */
      sscanf(opj_optarg, "%d", &j2k_parameters->numresolution);
      break;
      /* ----------------------------------------------------- */
    case 'c':			/* precinct dimension */
			{
				char sep;
				int res_spec = 0;

				char *s = opj_optarg;
				do {
					sep = 0;
					sscanf(s, "[%d,%d]%c", &j2k_parameters->prcw_init[res_spec],
                                 &j2k_parameters->prch_init[res_spec], &sep);
					j2k_parameters->csty |= 0x01;
					res_spec++;
					s = strpbrk(s, "]") + 2;
				}
				while (sep == ',');
				j2k_parameters->res_spec = res_spec;
			}
			break;

      /* ----------------------------------------------------- */
    case 'b':			/* code-block dimension */
			{
				int cblockw_init = 0, cblockh_init = 0;
				sscanf(opj_optarg, "%d,%d", &cblockw_init, &cblockh_init);
				if (cblockw_init * cblockh_init > 4096 || cblockw_init > 1024
					|| cblockw_init < 4 || cblockh_init > 1024 || cblockh_init < 4) {
					fprintf(stderr,
						"!! Size of code_block error (option -b) !!\n\nRestriction :\n"
            "    * width*height<=4096\n    * 4<=width,height<= 1024\n\n");
					return 1;
				}
				j2k_parameters->cblockw_init = cblockw_init;
				j2k_parameters->cblockh_init = cblockh_init;
			}
			break;
      /* ----------------------------------------------------- */
    case 'p':			/* progression order */
			{
				char progression[5];
				
				strncpy(progression, opj_optarg, 5);
				j2k_parameters->prog_order = give_progression(progression);
				if (j2k_parameters->prog_order == -1) {
					fprintf(stderr, "Unrecognized progression order "
            "[LRCP, RLCP, RPCL, PCRL, CPRL] !!\n");
					return 1;
				}
			}
			break;
      /* ----------------------------------------------------- */
    case 's':			/* subsampling factor */
      {
				if (sscanf(opj_optarg, "%d,%d", &j2k_parameters->subsampling_dx,
                                    &j2k_parameters->subsampling_dy) != 2) {
					fprintf(stderr,	"'-s' sub-sampling argument error !  [-s dx,dy]\n");
					return 1;
				}
			}
			break;
      /* ----------------------------------------------------- */
    case 'd':			/* coordonnate of the reference grid */
      {
				if (sscanf(opj_optarg, "%d,%d", &j2k_parameters->image_offset_x0,
                                    &j2k_parameters->image_offset_y0) != 2) {
					fprintf(stderr,	"-d 'coordonnate of the reference grid' argument "
            "error !! [-d x0,y0]\n");
					return 1;
				}
			}
			break;
      /* ----------------------------------------------------- */
    case 'h':			/* Display an help description */
      help_display();
      return 0;
      break;
      /* ----------------------------------------------------- */
    case 'P':			/* POC */
      {
				int numpocs = 0;		/* number of progression order change (POC) default 0 */
				opj_poc_t *POC = NULL;	/* POC : used in case of Progression order change */

				char *s = opj_optarg;
				POC = j2k_parameters->POC;

				while (sscanf(s, "T%d=%d,%d,%d,%d,%d,%4s", &POC[numpocs].tile,
					&POC[numpocs].resno0, &POC[numpocs].compno0,
					&POC[numpocs].layno1, &POC[numpocs].resno1,
					&POC[numpocs].compno1, POC[numpocs].progorder) == 7) {
					POC[numpocs].prg1 = give_progression(POC[numpocs].progorder);
					numpocs++;
					while (*s && *s != '/') {
						s++;
					}
					if (!*s) {
						break;
					}
					s++;
				}
				j2k_parameters->numpocs = numpocs;
			}
			break;
      /* ------------------------------------------------------ */
    case 'S':			/* SOP marker */
      j2k_parameters->csty |= 0x02;
      break;
      /* ------------------------------------------------------ */
    case 'E':			/* EPH marker */
      j2k_parameters->csty |= 0x04;
      break;
      /* ------------------------------------------------------ */
    case 'M':			/* Mode switch pas tous au point !! */
      if (sscanf(opj_optarg, "%d", &value) == 1) {
				for (i = 0; i <= 5; i++) {
					int cache = value & (1 << i);
					if (cache)
						j2k_parameters->mode |= (1 << i);
				}
      }
      break;
      /* ------------------------------------------------------ */
    case 'R':			/* ROI */
      {
				if (sscanf(opj_optarg, "OI:c=%d,U=%d", &j2k_parameters->roi_compno,
                                           &j2k_parameters->roi_shift) != 2) {
					fprintf(stderr, "ROI error !! [-ROI:c='compno',U='shift']\n");
					return 1;
				}
			}
			break;
      /* ------------------------------------------------------ */
    case 'T':			/* Tile offset */
			{
				if (sscanf(opj_optarg, "%d,%d", &j2k_parameters->cp_tx0, &j2k_parameters->cp_ty0) != 2) {
					fprintf(stderr, "-T 'tile offset' argument error !! [-T X0,Y0]");
					return 1;
				}
			}
			break;
      /* ------------------------------------------------------ */
    case 'C':			/* Add a comment */
			{
				j2k_parameters->cp_comment = (char*)malloc(strlen(opj_optarg) + 1);
				if(j2k_parameters->cp_comment) {
					strcpy(j2k_parameters->cp_comment, opj_optarg);
				}
			}
			break;
      /* ------------------------------------------------------ */
    case 'I':			/* reversible or not */
			{
				j2k_parameters->irreversible = 1;
			}
			break;
      /* ------------------------------------------------------ */
    case 'W':			/* Width and Height and Cb and Cr subsampling in case of YUV format files */
      if (sscanf
				(opj_optarg, "%d,%d,%d,%d", &mj2_parameters.w, &mj2_parameters.h, &mj2_parameters.CbCr_subsampling_dx,
				&mj2_parameters.CbCr_subsampling_dy) != 4) {
				fprintf(stderr, "-W argument error");
				return 1;
      }
      break;
      /* ------------------------------------------------------ */
    case 'F':			/* Video frame rate */
      if (sscanf(opj_optarg, "%d", &mj2_parameters.frame_rate) != 1) {
				fprintf(stderr, "-F argument error");
				return 1;
      }
      break;
      /* ------------------------------------------------------ */
	case 'D': /* Depth: the precision */
		if(sscanf(opj_optarg, "%d", &prec) != 1) prec = 0;
		break;

    default:
      return 1;
    }
  }
    
  /* Error messages */
  /* -------------- */
	if (!mj2_parameters.cod_format || !mj2_parameters.decod_format) {
    fprintf(stderr,
      "Usage: %s -i yuv-file -o mj2-file (+ options)\n",argv[0]);
    return 1;
  }
    if(prec < 1 || prec > 16)
  {
	fprintf(stderr, "Error: Depth %d must be in the range 8 .. 16\n",prec);
	return 1;	
  }
	if ((j2k_parameters->cp_disto_alloc || j2k_parameters->cp_fixed_alloc || j2k_parameters->cp_fixed_quality)
		&& (!(j2k_parameters->cp_disto_alloc ^ j2k_parameters->cp_fixed_alloc ^ j2k_parameters->cp_fixed_quality))) {
		fprintf(stderr, "Error: options -r -q and -f cannot be used together !!\n");
		return 1;
	}				/* mod fixed_quality */

	/* if no rate entered, lossless by default */
	if (j2k_parameters->tcp_numlayers == 0) {
		j2k_parameters->tcp_rates[0] = 0;	/* MOD antonin : losslessbug */
		j2k_parameters->tcp_numlayers++;
		j2k_parameters->cp_disto_alloc = 1;
	}

	if((j2k_parameters->cp_tx0 > j2k_parameters->image_offset_x0) || (j2k_parameters->cp_ty0 > j2k_parameters->image_offset_y0)) {
		fprintf(stderr,
			"Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
			j2k_parameters->cp_tx0, j2k_parameters->image_offset_x0, j2k_parameters->cp_ty0, j2k_parameters->image_offset_y0);
		return 1;
	}

	for (i = 0; i < j2k_parameters->numpocs; i++) {
		if (j2k_parameters->POC[i].prg == -1) {
			fprintf(stderr,
				"Unrecognized progression order in option -P (POC n %d) [LRCP, RLCP, RPCL, PCRL, CPRL] !!\n",
				i + 1);
		}
	}
  
  if (j2k_parameters->cp_tdx > mj2_parameters.Dim[0] || j2k_parameters->cp_tdy > mj2_parameters.Dim[1]) {
    fprintf(stderr,
      "Error: Tile offset dimension is unnappropriate --> TX0(%d)<=IMG_X0(%d) TYO(%d)<=IMG_Y0(%d) \n",
      j2k_parameters->cp_tdx, mj2_parameters.Dim[0], j2k_parameters->cp_tdy, mj2_parameters.Dim[1]);
    return 1;
  }
    
  /* to respect profile - 0 */
  /* ---------------------- */
  
  x1 = !mj2_parameters.Dim[0] ? (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx 
		+ 1 : mj2_parameters.Dim[0] + (mj2_parameters.w - 1) * j2k_parameters->subsampling_dx + 1;
  y1 = !mj2_parameters.Dim[1] ? (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy 
		+ 1 : mj2_parameters.Dim[1] + (mj2_parameters.h - 1) * j2k_parameters->subsampling_dy + 1;   
	mj2_parameters.numcomps = 3; /* YUV files only have 3 components */ 

	mj2_parameters.prec = prec;

	j2k_parameters->tcp_mct = 0;
    
	mj2file = fopen(mj2_parameters.outfile, "wb");
  
	if (!mj2file) {
    fprintf(stderr, "failed to open %s for writing\n", argv[2]);
    return 1;
	}
    
	/* get a MJ2 decompressor handle */
	cinfo = mj2_create_compress();
	movie = (opj_mj2_t*)cinfo->mj2_handle;
	
	/* catch events using our callbacks and give a local context */
	opj_set_event_mgr((opj_common_ptr)cinfo, &event_mgr, stderr);

	/* setup encoder parameters */
	mj2_setup_encoder(movie, &mj2_parameters);   
  
	movie->tk[0].num_samples = 
	 yuv_num_frames(&movie->tk[0],mj2_parameters.infile);

	if (movie->tk[0].num_samples == 0) {
		return 1;
	}

  /* One sample per chunk*/
	movie->tk[0].chunk = (mj2_chunk_t*) 
	 malloc(movie->tk[0].num_samples * sizeof(mj2_chunk_t));     
	movie->tk[0].sample = (mj2_sample_t*) 
	 malloc(movie->tk[0].num_samples * sizeof(mj2_sample_t));
  
	if (mj2_init_stdmovie(movie)) {
    fprintf(stderr, "Error with movie initialization");
    return 1;
	}    
  
/* Writing JP, FTYP and MDAT boxes */
/* Assuming that the JP and FTYP boxes won't be longer than 300 bytes:*/
	buf = (unsigned char*) 
	 malloc (300 * sizeof(unsigned char));

	cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, 300);

	mj2_write_jp(cio);
	mj2_write_ftyp(movie, cio);

	mdat_initpos = cio_tell(cio);
	cio_skip(cio, 4);

	cio_write(cio, MJ2_MDAT, 4);	

	fwrite(buf,cio_tell(cio),1,mj2file);

	offset = cio_tell(cio);
	opj_cio_close(cio);
	free(buf);

	for(i = 0; i < movie->num_stk + movie->num_htk + movie->num_vtk; i++) 
   {
    if(movie->tk[i].track_type != 0) 
  {
	fprintf(stderr, "Unable to write sound or hint tracks\n");
  }
	else 
  {
	mj2_tk_t *tk;
	int buflen = 0;
  
	tk = &movie->tk[i];     
	tk->num_chunks = tk->num_samples;
	numframes = tk->num_samples;
	tk->depth = prec; 

	fprintf(stderr, "Video Track number %d\n", i);

	img = mj2_image_create(tk, j2k_parameters);          

	buflen = 2 * (tk->w * tk->h * 8);
	buf = (unsigned char *) malloc(buflen*sizeof(unsigned char));	

	for(sampleno = 0; sampleno < numframes; sampleno++) 
 {
	double init_time = opj_clock();
	double elapsed_time;

		if(yuvtoimage(tk, img, sampleno, j2k_parameters, 
			mj2_parameters.infile))
	   {
		fprintf(stderr, "Error with frame number %d in YUV file\n", sampleno);
		return 1;
	   }

/* setup the encoder parameters using the current image and user parameters */
	opj_setup_encoder(cinfo, j2k_parameters, img);

	cio = opj_cio_open((opj_common_ptr)movie->cinfo, buf, buflen);
								
	cio_skip(cio, 4);
	cio_write(cio, JP2_JP2C, 4);	/* JP2C*/

/* encode the image */
	bSuccess = opj_encode(cinfo, cio, img, NULL);

	if (!bSuccess) {
	opj_cio_close(cio);
	fprintf(stderr, "failed to encode image\n");
	return 1;
	}

	len = cio_tell(cio) - 8;
	cio_seek(cio, 0);
	cio_write(cio, len+8,4);
	opj_cio_close(cio);

	tk->sample[sampleno].sample_size = len+8;				
	tk->sample[sampleno].offset = offset;
	tk->chunk[sampleno].offset = offset;	/* There is one sample per chunk */
	fwrite(buf, 1, len+8, mj2file);				
	offset += len+8;				

	elapsed_time = opj_clock()-init_time;
	fprintf(stderr, "Frame number %d/%d encoded in %.2f mseconds\n", 
		sampleno + 1, numframes, elapsed_time*1000);
	total_time += elapsed_time;
 }	/* for(sampleno */

	free(buf);
	opj_image_destroy(img);
  }
   }/* for(i */
  
	fseek(mj2file, mdat_initpos, SEEK_SET);
	
	buf = (unsigned char*) malloc(4*sizeof(unsigned char));

/* Init a cio to write box length variable in a little endian way */
	cio = opj_cio_open(NULL, buf, 4);
	cio_write(cio, offset - mdat_initpos, 4);
	fwrite(buf, 4, 1, mj2file);
	fseek(mj2file,0,SEEK_END);
	free(buf);

/* Writing MOOV box */
	buf = (unsigned char*) 
	 malloc ((TEMP_BUF+numframes*20) * sizeof(unsigned char));
	cio = opj_cio_open(movie->cinfo, buf, (TEMP_BUF+numframes*20));
	mj2_write_moov(movie, cio);
	fwrite(buf,cio_tell(cio),1,mj2file);
	free(buf);

	fprintf(stdout,"Total encoding time: %.2f s for %d frames (%.1f fps)\n",
	 total_time, numframes, (float)numframes/total_time);

  /* Ending program */
  
	fclose(mj2file);
/* free remaining compression structures */
	mj2_destroy_compress(movie);
	free(cinfo);

	if(j2k_parameters->cp_comment) free(j2k_parameters->cp_comment);
	if(j2k_parameters->cp_matrice) free(j2k_parameters->cp_matrice);
	opj_cio_close(cio);

	return 0;
}
Esempio n. 8
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;
}
Esempio n. 9
0
int main()
{
	printf("%s", opj_version());
	return 0;
}
Esempio n. 10
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);
}
Esempio n. 11
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;
}