opj_stream_t* ossimOpjCompressor::createOpjStream( std::ostream* os ) const
{
   opj_stream_t* stream = 0;
   if ( os )
   {
      // stream = opj_stream_create_default_file_stream("test.jp2", OPJ_FALSE);
   
 
      // OPJ stream:
      // stream = opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE, OPJ_FALSE);
      // stream = opj_stream_create(512, OPJ_FALSE);      
      // stream = opj_stream_create_default_file_stream("test.jp2", OPJ_FALSE); // false = output.
      stream = opj_stream_create(1048576, OPJ_FALSE);
      if ( stream )
      {
         // cout << "stream good..." << endl;
         
         // Set OPJ user stream:
         opj_stream_set_user_data(stream, os, ossim_opj_free_user_ostream_data);        
         
         // Set callbacks:
         // opj_stream_set_read_function(m_stream, ossim_opj_stream_read);
         // opj_stream_set_read_function(stream, ossim_opj_imagedata_read);
         opj_stream_set_write_function(stream, ossim_opj_ostream_write);
         opj_stream_set_skip_function(stream,  ossim_opj_ostream_skip);
         opj_stream_set_seek_function(stream,  ossim_opj_ostream_seek);
      }
   }
   return stream;

} // End: ossimOpjCompressor::createOpjStream()
Esempio n. 2
0
OpenJPEG_createIO(nrt_IOInterface* io,
                  IOControl* ioControl,
                  nrt_Off length,
                  int isInput,
                  nrt_Error *error)
{
    opj_stream_t *stream = NULL;

    stream = opj_stream_create(OPENJPEG_STREAM_SIZE, isInput);
    if (!stream)
    {
        nrt_Error_init(error, "Error creating openjpeg stream", NRT_CTXT,
                       NRT_ERR_MEMORY);
    }
    else
    {
        ioControl->io = io;
        ioControl->offset = nrt_IOInterface_tell(io, error);
        if (length > 0)
            ioControl->length = length;
        else
            ioControl->length = nrt_IOInterface_getSize(io, error)
                    - ioControl->offset;

        opj_stream_set_user_data(stream, ioControl);
        opj_stream_set_read_function(stream, implStreamRead);
        opj_stream_set_seek_function(stream, implStreamSeek);
        opj_stream_set_skip_function(stream, implStreamSkip);
        opj_stream_set_write_function(stream, implStreamWrite);
    }
    return stream;
}
Esempio n. 3
0
J2KFIO_t* 
opj_freeimage_stream_create(FreeImageIO *io, fi_handle handle, BOOL bRead) {
	if(!handle) {
		return NULL;
	}
	J2KFIO_t *fio = (J2KFIO_t*)malloc(sizeof(J2KFIO_t));
	if(fio) {
		fio->io = io;
		fio->handle = handle;

		opj_stream_t *l_stream = opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE, bRead ? OPJ_TRUE : OPJ_FALSE);
		if (l_stream) {
			opj_stream_set_user_data(l_stream, fio);
			opj_stream_set_user_data_length(l_stream, _LengthProc(fio));
			opj_stream_set_read_function(l_stream, (opj_stream_read_fn)_ReadProc);
			opj_stream_set_write_function(l_stream, (opj_stream_write_fn)_WriteProc);
			opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn)_SkipProc);
			opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn)_SeekProc);
			fio->stream = l_stream;
			return fio;
		} else {
			free(fio);
		}
	}

	return NULL;		
}
Esempio n. 4
0
static opj_stream_t *opj_stream_create_from_file(const char *filepath,
                                                 OPJ_UINT32 p_size,
                                                 OPJ_BOOL p_is_read_stream,
                                                 FILE **r_file)
{
  FILE *p_file = BLI_fopen(filepath, p_is_read_stream ? "rb" : "wb");
  if (p_file == NULL) {
    return NULL;
  }

  opj_stream_t *l_stream = opj_stream_create(p_size, p_is_read_stream);
  if (l_stream == NULL) {
    fclose(p_file);
    return NULL;
  }

  opj_stream_set_user_data(l_stream, p_file, opj_free_from_file);
  opj_stream_set_user_data_length(l_stream, opj_get_data_length_from_file(p_file));
  opj_stream_set_write_function(l_stream, opj_write_from_file);
  opj_stream_set_read_function(l_stream, opj_read_from_file);
  opj_stream_set_skip_function(l_stream, opj_skip_from_file);
  opj_stream_set_seek_function(l_stream, opj_seek_from_file);

  if (r_file) {
    *r_file = p_file;
  }
  return l_stream;
}
Esempio n. 5
0
    /* Static generator of opj_stream from file stream */
static opj_stream_t *
opjCreateStream(FILE    *fp,
                l_int32  is_read_stream)
{
opj_stream_t  *l_stream;

    PROCNAME("opjStreamCreate");

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

    l_stream = opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE, is_read_stream);
    if (!l_stream)
        return (opj_stream_t *)ERROR_PTR("stream not made", procName, NULL);

#if OPJ_VERSION_MINOR == 0
    opj_stream_set_user_data(l_stream, fp);
#else
    opj_stream_set_user_data(l_stream, fp,
                             (opj_stream_free_user_data_fn)NULL);
#endif
    opj_stream_set_user_data_length(l_stream, opj_get_user_data_length(fp));
    opj_stream_set_read_function(l_stream,
                                 (opj_stream_read_fn)opj_read_from_file);
    opj_stream_set_write_function(l_stream,
                                  (opj_stream_write_fn)opj_write_from_file);
    opj_stream_set_skip_function(l_stream,
                                 (opj_stream_skip_fn)opj_skip_from_file);
    opj_stream_set_seek_function(l_stream,
                                 (opj_stream_seek_fn)opj_seek_from_file);

    return l_stream;
}
Esempio n. 6
0
opj_stream_t* OPJ_CALLCONV opj_stream_create_memory_stream(DecodeData* p_mem,OPJ_UINT32 p_size, bool p_is_read_stream)
{
	opj_stream_t* l_stream = NULL;
	if (! p_mem)
		return NULL;

	l_stream = opj_stream_create(p_size,p_is_read_stream);
	if (!l_stream)
		return NULL;

	opj_stream_set_user_data(l_stream, p_mem, NULL);
	opj_stream_set_user_data_length(l_stream, p_mem->src_size);
	opj_stream_set_read_function(l_stream,(opj_stream_read_fn) opj_read_from_memory);
	opj_stream_set_write_function(l_stream, (opj_stream_write_fn) opj_write_from_memory);
	opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn) opj_skip_from_memory);
	opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn) opj_seek_from_memory);
	return l_stream;
}
Esempio n. 7
0
static opj_stream_t *opj_stream_create_from_buffer(struct BufInfo *p_file,
                                                   OPJ_UINT32 p_size,
                                                   OPJ_BOOL p_is_read_stream)
{
  opj_stream_t *l_stream = opj_stream_create(p_size, p_is_read_stream);
  if (l_stream == NULL) {
    return NULL;
  }
  opj_stream_set_user_data(l_stream, p_file, opj_read_from_buffer_free);
  opj_stream_set_user_data_length(l_stream, p_file->len);
  opj_stream_set_read_function(l_stream, opj_read_from_buffer);
#if 0 /* UNUSED */
  opj_stream_set_write_function(l_stream, opj_write_from_buffer);
#endif
  opj_stream_set_skip_function(l_stream, opj_skip_from_buffer);
  opj_stream_set_seek_function(l_stream, opj_seek_from_buffer);

  return l_stream;
}
Esempio n. 8
0
opj_stream_t* fx_opj_stream_create_memory_stream(DecodeData* data,
                                                 OPJ_SIZE_T p_size,
                                                 OPJ_BOOL p_is_read_stream) {
  opj_stream_t* l_stream = 00;
  if (!data || !data->src_data || data->src_size <= 0) {
    return nullptr;
  }
  l_stream = opj_stream_create(p_size, p_is_read_stream);
  if (!l_stream) {
    return nullptr;
  }
  opj_stream_set_user_data(l_stream, data, nullptr);
  opj_stream_set_user_data_length(l_stream, data->src_size);
  opj_stream_set_read_function(l_stream, opj_read_from_memory);
  opj_stream_set_write_function(l_stream, opj_write_from_memory);
  opj_stream_set_skip_function(l_stream, opj_skip_from_memory);
  opj_stream_set_seek_function(l_stream, opj_seek_from_memory);
  return l_stream;
}
Esempio n. 9
0
opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream(
    const char *fname,
    OPJ_SIZE_T p_size,
    OPJ_BOOL p_is_read_stream)
{
    opj_stream_t* l_stream = 00;
    FILE *p_file;
    const char *mode;

    if (! fname) {
        return NULL;
    }

    if (p_is_read_stream) {
        mode = "rb";
    } else {
        mode = "wb";
    }

    p_file = fopen(fname, mode);

    if (! p_file) {
        return NULL;
    }

    l_stream = opj_stream_create(p_size, p_is_read_stream);
    if (! l_stream) {
        fclose(p_file);
        return NULL;
    }

    opj_stream_set_user_data(l_stream, p_file,
                             (opj_stream_free_user_data_fn) fclose);
    opj_stream_set_user_data_length(l_stream,
                                    opj_get_data_length_from_file(p_file));
    opj_stream_set_read_function(l_stream, (opj_stream_read_fn) opj_read_from_file);
    opj_stream_set_write_function(l_stream,
                                  (opj_stream_write_fn) opj_write_from_file);
    opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn) opj_skip_from_file);
    opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn) opj_seek_from_file);

    return l_stream;
}
Esempio n. 10
0
opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream (FILE * p_file,OPJ_UINT32 p_size,bool p_is_read_stream)
{
  opj_stream_t* l_stream = 00;
  if
    (! p_file)
  {
    return 00;
  }
  l_stream = opj_stream_create(p_size,p_is_read_stream);
  if
    (! l_stream)
  {
    return 00;
  }
  opj_stream_set_user_data(l_stream,p_file);
  opj_stream_set_read_function(l_stream,(opj_stream_read_fn) opj_read_from_file);
  opj_stream_set_write_function(l_stream, (opj_stream_write_fn) opj_write_from_file);
  opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn) opj_skip_from_file);
  opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn) opj_seek_from_file);
  return l_stream;
}
Esempio n. 11
0
opj_stream_t* OPJ_CALLCONV opj_stream_create_file_stream (	FILE * p_file, 
															OPJ_SIZE_T p_size, 
															OPJ_BOOL p_is_read_stream)
{
	opj_stream_t* l_stream = 00;

	if (! p_file) {
		return NULL;
	}

	l_stream = opj_stream_create(p_size,p_is_read_stream);
	if (! l_stream) {
		return NULL;
	}

	opj_stream_set_user_data(l_stream, p_file);
	opj_stream_set_user_data_length(l_stream, opj_get_data_length_from_file(p_file));
	opj_stream_set_read_function(l_stream, (opj_stream_read_fn) opj_read_from_file);
	opj_stream_set_write_function(l_stream, (opj_stream_write_fn) opj_write_from_file);
	opj_stream_set_skip_function(l_stream, (opj_stream_skip_fn) opj_skip_from_file);
	opj_stream_set_seek_function(l_stream, (opj_stream_seek_fn) opj_seek_from_file);

	return l_stream;
}
Esempio n. 12
0
static GstFlowReturn
gst_openjpeg_enc_handle_frame (GstVideoEncoder * encoder,
    GstVideoCodecFrame * frame)
{
  GstOpenJPEGEnc *self = GST_OPENJPEG_ENC (encoder);
  GstFlowReturn ret = GST_FLOW_OK;
#ifdef HAVE_OPENJPEG_1
  opj_cinfo_t *enc;
  GstMapInfo map;
  guint length;
  opj_cio_t *io;
#else
  opj_codec_t *enc;
  opj_stream_t *stream;
  MemStream mstream;
#endif
  opj_image_t *image;
  GstVideoFrame vframe;

  GST_DEBUG_OBJECT (self, "Handling frame");

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

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

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

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

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

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

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

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

  opj_image_destroy (image);

  length = cio_tell (io);

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

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

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

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

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

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

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

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

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

  frame->output_buffer = gst_buffer_new ();

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

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

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

  ret = gst_video_encoder_finish_frame (encoder, frame);

  return ret;

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

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

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

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

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

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to allocate output buffer"), (NULL));
    return ret;
  }
#endif
}
Esempio n. 13
0
static Image *ReadJP2Image(const ImageInfo *image_info,ExceptionInfo *exception)
{
  const char
    *option;

  Image
    *image;

  int
    jp2_status;

  MagickBooleanType
    status;

  opj_codec_t
    *jp2_codec;

  opj_codestream_index_t
    *codestream_index = (opj_codestream_index_t *) NULL;

  opj_dparameters_t
    parameters;

  opj_image_t
    *jp2_image;

  opj_stream_t
    *jp2_stream;

  register ssize_t
    i;

  ssize_t
    y;

  unsigned char
    sans[4];

  /*
    Open image file.
  */
  assert(image_info != (const ImageInfo *) NULL);
  assert(image_info->signature == MagickCoreSignature);
  if (image_info->debug != MagickFalse)
    (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",
      image_info->filename);
  assert(exception != (ExceptionInfo *) NULL);
  assert(exception->signature == MagickCoreSignature);
  image=AcquireImage(image_info,exception);
  status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception);
  if (status == MagickFalse)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  /*
    Initialize JP2 codec.
  */
  if (ReadBlob(image,4,sans) != 4)
    {
      image=DestroyImageList(image);
      return((Image *) NULL);
    }
  (void) SeekBlob(image,SEEK_SET,0);
  if (LocaleCompare(image_info->magick,"JPT") == 0)
    jp2_codec=opj_create_decompress(OPJ_CODEC_JPT);
  else
    if (IsJ2K(sans,4) != MagickFalse)
      jp2_codec=opj_create_decompress(OPJ_CODEC_J2K);
    else
      jp2_codec=opj_create_decompress(OPJ_CODEC_JP2);
  opj_set_warning_handler(jp2_codec,JP2WarningHandler,exception);
  opj_set_error_handler(jp2_codec,JP2ErrorHandler,exception);
  opj_set_default_decoder_parameters(&parameters);
  option=GetImageOption(image_info,"jp2:reduce-factor");
  if (option != (const char *) NULL)
    parameters.cp_reduce=StringToInteger(option);
  option=GetImageOption(image_info,"jp2:quality-layers");
  if (option != (const char *) NULL)
    parameters.cp_layer=StringToInteger(option);
  if (opj_setup_decoder(jp2_codec,&parameters) == 0)
    {
      opj_destroy_codec(jp2_codec);
      ThrowReaderException(DelegateError,"UnableToManageJP2Stream");
    }
  jp2_stream=opj_stream_create(OPJ_J2K_STREAM_CHUNK_SIZE,1);
  opj_stream_set_read_function(jp2_stream,JP2ReadHandler);
  opj_stream_set_write_function(jp2_stream,JP2WriteHandler);
  opj_stream_set_seek_function(jp2_stream,JP2SeekHandler);
  opj_stream_set_skip_function(jp2_stream,JP2SkipHandler);
  opj_stream_set_user_data(jp2_stream,image,NULL);
  opj_stream_set_user_data_length(jp2_stream,GetBlobSize(image));
  if (opj_read_header(jp2_stream,jp2_codec,&jp2_image) == 0)
    {
      opj_stream_destroy(jp2_stream);
      opj_destroy_codec(jp2_codec);
      ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
    }
  jp2_status=1;
  if ((image->columns != 0) && (image->rows != 0))
    {
      /*
        Extract an area from the image.
      */
      jp2_status=opj_set_decode_area(jp2_codec,jp2_image,
        (OPJ_INT32) image->extract_info.x,(OPJ_INT32) image->extract_info.y,
        (OPJ_INT32) (image->extract_info.x+(ssize_t) image->columns),
        (OPJ_INT32) (image->extract_info.y+(ssize_t) image->rows));
      if (jp2_status == 0)
        {
          opj_stream_destroy(jp2_stream);
          opj_destroy_codec(jp2_codec);
          opj_image_destroy(jp2_image);
          ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
        }
    }
   if ((image_info->number_scenes != 0) && (image_info->scene != 0))
    jp2_status=opj_get_decoded_tile(jp2_codec,jp2_stream,jp2_image,
      (unsigned int) image_info->scene-1);
  else
    if (image->ping == MagickFalse)
      {
        jp2_status=opj_decode(jp2_codec,jp2_stream,jp2_image);
        if (jp2_status != 0)
          jp2_status=opj_end_decompress(jp2_codec,jp2_stream);
      }
  if (jp2_status == 0)
    {
      opj_stream_destroy(jp2_stream);
      opj_destroy_codec(jp2_codec);
      opj_image_destroy(jp2_image);
      ThrowReaderException(DelegateError,"UnableToDecodeImageFile");
    }
  opj_stream_destroy(jp2_stream);
  for (i=0; i < (ssize_t) jp2_image->numcomps; i++)
  {
    if ((jp2_image->comps[i].dx == 0) || (jp2_image->comps[i].dy == 0))
      {
        opj_destroy_codec(jp2_codec);
        opj_image_destroy(jp2_image);
        ThrowReaderException(CoderError,"IrregularChannelGeometryNotSupported")
      }
  }
Esempio n. 14
0
static int
j2k_encode_entry(Imaging im, ImagingCodecState state,
                 ImagingIncrementalCodec encoder)
{
    JPEG2KENCODESTATE *context = (JPEG2KENCODESTATE *)state->context;
    opj_stream_t *stream = NULL;
    opj_image_t *image = NULL;
    opj_codec_t *codec = NULL;
    opj_cparameters_t params;
    unsigned components;
    OPJ_COLOR_SPACE color_space;
    opj_image_cmptparm_t image_params[4];
    unsigned xsiz, ysiz;
    unsigned tile_width, tile_height;
    unsigned tiles_x, tiles_y, num_tiles;
    unsigned x, y, tile_ndx;
    unsigned n;
    j2k_pack_tile_t pack;
    int ret = -1;

    stream = opj_stream_default_create(OPJ_FALSE);

    if (!stream) {
        state->errcode = IMAGING_CODEC_BROKEN;
        state->state = J2K_STATE_FAILED;
        goto quick_exit;
    }

    opj_stream_set_write_function(stream, j2k_write);
    opj_stream_set_skip_function(stream, j2k_skip);
    opj_stream_set_seek_function(stream, j2k_seek);

    opj_stream_set_user_data(stream, encoder);

    /* Setup an opj_image */
    if (strcmp (im->mode, "L") == 0) {
        components = 1;
        color_space = OPJ_CLRSPC_GRAY;
        pack = j2k_pack_l;
    } else if (strcmp (im->mode, "LA") == 0) {
        components = 2;
        color_space = OPJ_CLRSPC_GRAY;
        pack = j2k_pack_la;
    } else if (strcmp (im->mode, "RGB") == 0) {
        components = 3;
        color_space = OPJ_CLRSPC_SRGB;
        pack = j2k_pack_rgb;
    } else if (strcmp (im->mode, "YCbCr") == 0) {
        components = 3;
        color_space = OPJ_CLRSPC_SYCC;
        pack = j2k_pack_rgb;
    } else if (strcmp (im->mode, "RGBA") == 0) {
        components = 4;
        color_space = OPJ_CLRSPC_SRGB;
        pack = j2k_pack_rgba;
    } else {
        state->errcode = IMAGING_CODEC_BROKEN;
        state->state = J2K_STATE_FAILED;
        goto quick_exit;
    }

    for (n = 0; n < components; ++n) {
        image_params[n].dx = image_params[n].dy = 1;
        image_params[n].w = im->xsize;
        image_params[n].h = im->ysize;
        image_params[n].x0 = image_params[n].y0 = 0;
        image_params[n].prec = 8;
        image_params[n].bpp = 8;
        image_params[n].sgnd = 0;
    }

    image = opj_image_create(components, image_params, color_space);

    /* Setup compression context */
    context->error_msg = NULL;

    opj_set_default_encoder_parameters(&params);

    params.image_offset_x0 = context->offset_x;
    params.image_offset_y0 = context->offset_y;

    if (context->tile_size_x && context->tile_size_y) {
        params.tile_size_on = OPJ_TRUE;
        params.cp_tx0 = context->tile_offset_x;
        params.cp_ty0 = context->tile_offset_y;
        params.cp_tdx = context->tile_size_x;
        params.cp_tdy = context->tile_size_y;

        tile_width = params.cp_tdx;
        tile_height = params.cp_tdy;
    } else {
        params.cp_tx0 = 0;
        params.cp_ty0 = 0;
        params.cp_tdx = 1;
        params.cp_tdy = 1;

        tile_width = im->xsize;
        tile_height = im->ysize;
    }

    if (context->quality_layers && PySequence_Check(context->quality_layers)) {
        Py_ssize_t len = PySequence_Length(context->quality_layers);
        Py_ssize_t n;
        float *pq;

        if (len) {
            if (len > sizeof(params.tcp_rates) / sizeof(params.tcp_rates[0]))
                len = sizeof(params.tcp_rates)/sizeof(params.tcp_rates[0]);

            params.tcp_numlayers = (int)len;

            if (context->quality_is_in_db) {
                params.cp_disto_alloc = params.cp_fixed_alloc = 0;
                params.cp_fixed_quality = 1;
                pq = params.tcp_distoratio;
            } else {
                params.cp_disto_alloc = 1;
                params.cp_fixed_alloc = params.cp_fixed_quality = 0;
                pq = params.tcp_rates;
            }

            for (n = 0; n < len; ++n) {
                PyObject *obj = PySequence_ITEM(context->quality_layers, n);
                pq[n] = PyFloat_AsDouble(obj);
            }
        }
    } else {
        params.tcp_numlayers = 1;
        params.tcp_rates[0] = 0;
        params.cp_disto_alloc = 1;
    }

    if (context->num_resolutions)
        params.numresolution = context->num_resolutions;

    if (context->cblk_width >= 4 && context->cblk_width <= 1024
            && context->cblk_height >= 4 && context->cblk_height <= 1024
            && context->cblk_width * context->cblk_height <= 4096) {
        params.cblockw_init = context->cblk_width;
        params.cblockh_init = context->cblk_height;
    }

    if (context->precinct_width >= 4 && context->precinct_height >= 4
            && context->precinct_width >= context->cblk_width
            && context->precinct_height > context->cblk_height) {
        params.prcw_init[0] = context->precinct_width;
        params.prch_init[0] = context->precinct_height;
        params.res_spec = 1;
        params.csty |= 0x01;
    }

    params.irreversible = context->irreversible;

    params.prog_order = context->progression;

    params.cp_cinema = context->cinema_mode;

    switch (params.cp_cinema) {
    case OPJ_OFF:
        params.cp_rsiz = OPJ_STD_RSIZ;
        break;
    case OPJ_CINEMA2K_24:
    case OPJ_CINEMA2K_48:
        params.cp_rsiz = OPJ_CINEMA2K;
        if (params.numresolution > 6)
            params.numresolution = 6;
        break;
    case OPJ_CINEMA4K_24:
        params.cp_rsiz = OPJ_CINEMA4K;
        if (params.numresolution > 7)
            params.numresolution = 7;
        break;
    }

    if (context->cinema_mode != OPJ_OFF)
        j2k_set_cinema_params(im, components, &params);

    /* Set up the reference grid in the image */
    image->x0 = params.image_offset_x0;
    image->y0 = params.image_offset_y0;
    image->x1 = xsiz = im->xsize + params.image_offset_x0;
    image->y1 = ysiz = im->ysize + params.image_offset_y0;

    /* Create the compressor */
    codec = opj_create_compress(context->format);

    if (!codec) {
        state->errcode = IMAGING_CODEC_BROKEN;
        state->state = J2K_STATE_FAILED;
        goto quick_exit;
    }

    opj_set_error_handler(codec, j2k_error, context);
    opj_setup_encoder(codec, &params, image);

    /* Start encoding */
    if (!opj_start_compress(codec, image, stream)) {
        state->errcode = IMAGING_CODEC_BROKEN;
        state->state = J2K_STATE_FAILED;
        goto quick_exit;
    }

    /* Write each tile */
    tiles_x = (im->xsize + (params.image_offset_x0 - params.cp_tx0)
               + tile_width - 1) / tile_width;
    tiles_y = (im->ysize + (params.image_offset_y0 - params.cp_ty0)
               + tile_height - 1) / tile_height;

    num_tiles = tiles_x * tiles_y;

    state->buffer = malloc (tile_width * tile_height * components);

    tile_ndx = 0;
    for (y = 0; y < tiles_y; ++y) {
        unsigned ty0 = params.cp_ty0 + y * tile_height;
        unsigned ty1 = ty0 + tile_height;
        unsigned pixy, pixh;

        if (ty0 < params.image_offset_y0)
            ty0 = params.image_offset_y0;
        if (ty1 > ysiz)
            ty1 = ysiz;

        pixy = ty0 - params.image_offset_y0;
        pixh = ty1 - ty0;

        for (x = 0; x < tiles_x; ++x) {
            unsigned tx0 = params.cp_tx0 + x * tile_width;
            unsigned tx1 = tx0 + tile_width;
            unsigned pixx, pixw;
            unsigned data_size;

            if (tx0 < params.image_offset_x0)
                tx0 = params.image_offset_x0;
            if (tx1 > xsiz)
                tx1 = xsiz;

            pixx = tx0 - params.image_offset_x0;
            pixw = tx1 - tx0;

            pack(im, state->buffer, pixx, pixy, pixw, pixh);

            data_size = pixw * pixh * components;

            if (!opj_write_tile(codec, tile_ndx++, state->buffer,
                                data_size, stream)) {
                state->errcode = IMAGING_CODEC_BROKEN;
                state->state = J2K_STATE_FAILED;
                goto quick_exit;
            }
        }
    }

    if (!opj_end_compress(codec, stream)) {
        state->errcode = IMAGING_CODEC_BROKEN;
        state->state = J2K_STATE_FAILED;
        goto quick_exit;
    }

    state->errcode = IMAGING_CODEC_END;
    state->state = J2K_STATE_DONE;
    ret = (int)ImagingIncrementalCodecBytesInBuffer(encoder);

quick_exit:
    if (codec)
        opj_destroy_codec(codec);
    if (image)
        opj_image_destroy(image);
    if (stream)
        opj_stream_destroy(stream);

    return ret;
}
Esempio n. 15
0
bool ossim::opj_decode( std::ifstream* in,
                        const ossimIrect& rect,
                        ossim_uint32 resLevel,
                        ossim_int32 format, // OPJ_CODEC_FORMAT
                        std::streamoff fileOffset,
                        ossimImageData* tile)
{
   static const char MODULE[] = "ossimOpjDecoder::decode";

   bool status = false;

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

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

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

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

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

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

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

      opj_stream_set_user_data_length(stream, userStream->m_length);

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

      param.decod_format = format;

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

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

      codec = opj_create_decompress( (CODEC_FORMAT)format );

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  GST_DEBUG_OBJECT (self, "Handling frame");

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

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

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

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

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

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

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

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

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

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

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

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

  gst_buffer_unmap (frame->input_buffer, &map);

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

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

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

  self->fill_frame (&vframe, image);

  gst_video_frame_unmap (&vframe);

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

  ret = gst_video_decoder_finish_frame (decoder, frame);

  return ret;

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

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

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

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

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

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

    GST_ELEMENT_ERROR (self, CORE, FAILED,
        ("Failed to map output buffer"), (NULL));
    return GST_FLOW_ERROR;
  }
}
Esempio n. 17
0
fz_pixmap *
fz_load_jpx(fz_context *ctx, unsigned char *data, int size, fz_colorspace *defcs, int indexed)
{
	fz_pixmap *img;
	fz_colorspace *origcs;
	opj_dparameters_t params;
	opj_codec_t *codec;
	opj_image_t *jpx;
	opj_stream_t *stream;
	fz_colorspace *colorspace;
	unsigned char *p;
	OPJ_CODEC_FORMAT format;
	int a, n, w, h, depth, sgnd;
	int x, y, k, v;
	stream_block sb;

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

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

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

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

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

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

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

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

	opj_stream_destroy(stream);
	opj_destroy_codec(codec);

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

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

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

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

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

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

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

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

	opj_image_destroy(jpx);

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

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

	return img;
}