예제 #1
0
파일: chm.cpp 프로젝트: BloodRedd/gamekit
size_t wxChmInputStream::OnSysRead(void *buffer, size_t bufsize)
{
    if ( m_pos >= m_size )
    {
        m_lasterror = wxSTREAM_EOF;
        return 0;
    }
    m_lasterror = wxSTREAM_NO_ERROR;

    // If the rest to read from the stream is less
    // than the buffer size, then only read the rest
    if ( m_pos + bufsize > m_size )
        bufsize = m_size - m_pos;

    if (m_contentStream->SeekI(m_pos) == wxInvalidOffset)
    {
        m_lasterror = wxSTREAM_EOF;
        return 0;
    }

    size_t read = m_contentStream->Read(buffer, bufsize).LastRead();
    m_pos += read;

    if (m_contentStream->SeekI(m_pos) == wxInvalidOffset)
    {
        m_lasterror = wxSTREAM_READ_ERROR;
        return 0;
    }

    if (read != bufsize)
        m_lasterror = m_contentStream->GetLastError();

    return read;
}
예제 #2
0
FbImportBook::FbImportBook(FbImportThread & owner, wxInputStream & in, const wxString & filename)
	: m_parser(NULL)
	, m_database(*owner.GetDatabase())
	, m_filename(owner.GetRelative(filename))
	, m_filepath(owner.GetAbsolute(filename))
	, m_filetype(Ext(m_filename))
	, m_message(filename)
	, m_filesize(in.GetLength())
	, m_archive(0)
	, m_ok(false)
{
	wxLogMessage(_("Import file %s"), m_filename.c_str());
	m_ok = in.IsOk();
	if (!m_ok) return;

	if (m_filetype == wxT("fb2")) {
		m_parser = new FbImportReaderFB2(in, true);
		m_md5sum = m_parser->GetMd5();
	} else if (m_filetype == wxT("epub")) {
		m_md5sum = CalcMd5(in);
		in.SeekI(0);
		wxString rootfile = FbRootReaderEPUB(in).GetRoot();
		in.SeekI(0);
		m_parser = new FbDataReaderEPUB(in, rootfile);
	} else {
		m_md5sum = CalcMd5(in);
	}
}
예제 #3
0
bool HexView::Load(wxInputStream& iStr)
{
	wxFileOffset strSize = iStr.SeekI(0, wxFromEnd);
	iStr.SeekI(0);
	unsigned char* data = new unsigned char[strSize];
	iStr.Read(data, strSize);
	Load(data, strSize);
	delete [] data;
	
	return true;
}
예제 #4
0
파일: chm.cpp 프로젝트: gitrider/wxsj2
wxFileOffset wxChmInputStream::OnSysSeek(wxFileOffset seek, wxSeekMode mode)
{
    wxString mode_str = wxEmptyString;

    if ( !m_contentStream || m_contentStream->Eof() )
    {
        m_lasterror = wxSTREAM_EOF;
        return 0;
    }
    m_lasterror = wxSTREAM_NO_ERROR;

    wxFileOffset nextpos;

    switch ( mode )
    {
        case wxFromCurrent:
            nextpos = seek + m_pos;
            break;
        case wxFromStart:
            nextpos = seek;
            break;
        case wxFromEnd:
            nextpos = m_size - 1 + seek;
            break;
        default:
            nextpos = m_pos;
            break; /* just to fool compiler, never happens */
    }
    m_pos=nextpos;

    // Set current position on stream
    m_contentStream->SeekI(m_pos);
    return m_pos;
}
예제 #5
0
파일: chm.cpp 프로젝트: gitrider/wxsj2
size_t wxChmInputStream::OnSysRead(void *buffer, size_t bufsize)
{
    if ( m_pos >= m_size )
    {
        m_lasterror = wxSTREAM_EOF;
        return 0;
    }
    m_lasterror = wxSTREAM_NO_ERROR;

    // If the rest to read from the stream is less
    // than the buffer size, than only read the rest
    if ( m_pos + bufsize > m_size )
        bufsize = m_size - m_pos;

    m_contentStream->SeekI(m_pos);
    m_contentStream->Read(buffer, bufsize);
    m_pos +=bufsize;
    m_contentStream->SeekI(m_pos);
    return bufsize;
}
예제 #6
0
FbRootReaderEPUB::FbRootReaderEPUB(wxInputStream & in)
	: m_ok(false)
{
	{
		wxZipInputStream zip(in);
		while (FbSmartPtr<wxZipEntry> entry = zip.GetNextEntry()) {
			if (entry->GetInternalName() == wxT("META-INF/container.xml")) {
				m_ok = zip.OpenEntry(*entry) && Parse(zip);
				break;
			}
		}
	}
	in.SeekI(0);
}
예제 #7
0
/** @brief Read a tokendatabase from disk
 *
 * @param tokenDatabase The tokendatabase to read into
 * @param in The wxInputStream to read from
 * @return true if the operation succeeded, false otherwise
 *
 */
bool ClTokenDatabase::ReadIn( ClTokenDatabase& tokenDatabase, wxInputStream& in )
{
    in.SeekI(4); // Magic number
    int version = 0;
    if (!ReadInt(in, version))
        return false;
    int i = 0;
    if (version != 0x01)
    {
        return false;
    }
    tokenDatabase.Clear();
    int read_count = 0;

    wxMutexLocker(tokenDatabase.m_Mutex);
    while (in.CanRead())
    {
        int packetType = 0;
        if (!ReadInt(in, packetType))
            return false;
        switch (packetType)
        {
        case ClTokenPacketType_filenames:
            if (!ClFilenameDatabase::ReadIn(tokenDatabase.m_FileDB, in))
                return false;
            break;
        case ClTokenPacketType_tokens:
            int packetCount = 0;
            if (!ReadInt(in, packetCount))
                return false;
            for (i = 0; i < packetCount; ++i)
            {
                ClAbstractToken token;
                if (!ClAbstractToken::ReadIn(token, in))
                    return false;
                if (token.fileId != -1)
                {
                    //ClTokenId tokId =
                    tokenDatabase.InsertToken(token);
                    //fprintf( stdout, " '%s' / '%s' / fId=%d location=%d:%d hash=%d dbEntryId=%d\n", (const char*)token.identifier.mb_str(), (const char*)token.displayName.mbc_str(), token.fileId, token.location.line, token.location.column,  token.tokenHash, tokId );
                    read_count++;
                }
            }
            break;
        }
    }
    return true;
}
예제 #8
0
void ArchiveTestCase<ClassFactoryT>::ExtractArchive(wxInputStream& in,
                                                    const wxString& unarchiver)
{
    // for an external unarchiver, unarchive to a tempdir
    TempDir tmpdir;

    if ((m_options & PipeIn) == 0) {
        wxFileName fn(tmpdir.GetName());
        fn.SetExt(wxT("arc"));
        wxString tmparc = fn.GetPath(wxPATH_GET_SEPARATOR) + fn.GetFullName();

        if (m_options & Stub)
            in.SeekI(STUB_SIZE * 2);

        // write the archive to a temporary file
        {
            wxFFileOutputStream out(tmparc);
            if (out.IsOk())
                out.Write(in);
        }

        // call unarchiver
        if ( system(wxString::Format(unarchiver, tmparc.c_str()).mb_str()) == -1 )
        {
            wxLogError("Failed to run unarchiver command \"%s\"", unarchiver);
        }

        wxRemoveFile(tmparc);
    }
    else {
        // for the non-seekable test, have the archiver extract "-" and
        // feed it the archive via a pipe
        PFileOutputStream out(wxString::Format(unarchiver, wxT("-")));
        if (out.IsOk())
            out.Write(in);
    }

    wxString dir = tmpdir.GetName();
    VerifyDir(dir);
}
예제 #9
0
 wxFileOffset SeekI( wxFileOffset pos, wxSeekMode mode )
     { wxASSERT(m_pStream); wxFileOffset fo = m_pStream->SeekI(pos, mode);
         Synch(); return fo; }
예제 #10
0
bool wxBMPHandler::DoLoadDib(wxImage * image, int width, int height,
                             int bpp, int ncolors, int comp,
                             wxFileOffset bmpOffset, wxInputStream& stream,
                             bool verbose, bool IsBmp, bool hasPalette)
{
    wxInt32         aDword, rmask = 0, gmask = 0, bmask = 0, amask = 0;
    int             rshift = 0, gshift = 0, bshift = 0, ashift = 0;
    int             rbits = 0, gbits = 0, bbits = 0;
    wxInt32         dbuf[4];
    wxInt8          bbuf[4];
    wxUint8         aByte;
    wxUint16        aWord;

    // allocate space for palette if needed:
    BMPPalette *cmap;

    if ( bpp < 16 )
    {
        cmap = new BMPPalette[ncolors];
        if ( !cmap )
        {
            if (verbose)
            {
                wxLogError(_("BMP: Couldn't allocate memory."));
            }
            return false;
        }
    }
    else // no palette
    {
        cmap = NULL;
    }

    wxON_BLOCK_EXIT1(&BMPPalette::Free, cmap);

    // destroy existing here instead of:
    image->Destroy();
    image->Create(width, height);

    unsigned char *ptr = image->GetData();

    if ( !ptr )
    {
        if ( verbose )
        {
            wxLogError( _("BMP: Couldn't allocate memory.") );
        }
        return false;
    }

    unsigned char *alpha;
    if ( bpp == 32 )
    {
        // tell the image to allocate an alpha buffer
        image->SetAlpha();
        alpha = image->GetAlpha();
        if ( !alpha )
        {
            if ( verbose )
            {
                wxLogError(_("BMP: Couldn't allocate memory."));
            }
            return false;
        }
    }
    else // no alpha
    {
        alpha = NULL;
    }

    // Reading the palette, if it exists:
    if ( bpp < 16 && ncolors != 0 )
    {
        unsigned char* r = new unsigned char[ncolors];
        unsigned char* g = new unsigned char[ncolors];
        unsigned char* b = new unsigned char[ncolors];
        for (int j = 0; j < ncolors; j++)
        {
            if (hasPalette)
            {
                stream.Read(bbuf, 4);
                cmap[j].b = bbuf[0];
                cmap[j].g = bbuf[1];
                cmap[j].r = bbuf[2];

                r[j] = cmap[j].r;
                g[j] = cmap[j].g;
                b[j] = cmap[j].b;
            }
            else
            {
                //used in reading .ico file mask
                r[j] = cmap[j].r =
                g[j] = cmap[j].g =
                b[j] = cmap[j].b = ( j ? 255 : 0 );
            }
        }

#if wxUSE_PALETTE
        // Set the palette for the wxImage
        image->SetPalette(wxPalette(ncolors, r, g, b));
#endif // wxUSE_PALETTE

        delete[] r;
        delete[] g;
        delete[] b;
    }
    else if ( bpp == 16 || bpp == 32 )
    {
        if ( comp == BI_BITFIELDS )
        {
            int bit;
            stream.Read(dbuf, 4 * 3);
            rmask = wxINT32_SWAP_ON_BE(dbuf[0]);
            gmask = wxINT32_SWAP_ON_BE(dbuf[1]);
            bmask = wxINT32_SWAP_ON_BE(dbuf[2]);
            // find shift amount (Least significant bit of mask)
            for (bit = bpp-1; bit>=0; bit--)
            {
                if (bmask & (1 << bit))
                    bshift = bit;
                if (gmask & (1 << bit))
                    gshift = bit;
                if (rmask & (1 << bit))
                    rshift = bit;
            }
            // Find number of bits in mask (MSB-LSB+1)
            for (bit = 0; bit < bpp; bit++)
            {
                if (bmask & (1 << bit))
                    bbits = bit-bshift+1;
                if (gmask & (1 << bit))
                    gbits = bit-gshift+1;
                if (rmask & (1 << bit))
                    rbits = bit-rshift+1;
            }
        }
        else if ( bpp == 16 )
        {
            rmask = 0x7C00;
            gmask = 0x03E0;
            bmask = 0x001F;
            rshift = 10;
            gshift = 5;
            bshift = 0;
            rbits = 5;
            gbits = 5;
            bbits = 5;
        }
        else if ( bpp == 32 )
        {
            rmask = 0x00FF0000;
            gmask = 0x0000FF00;
            bmask = 0x000000FF;
            amask = 0xFF000000;

            ashift = 24;
            rshift = 16;
            gshift = 8;
            bshift = 0;
            rbits = 8;
            gbits = 8;
            bbits = 8;
        }
    }

    /*
     * Reading the image data
     */
    if ( IsBmp )
    {
        // NOTE: seeking a positive amount in wxFromCurrent mode allows us to
        //       load even non-seekable streams (see wxInputStream::SeekI docs)!
        const wxFileOffset pos = stream.TellI();
        if (pos != wxInvalidOffset && bmpOffset > pos)
            if (stream.SeekI(bmpOffset - pos, wxFromCurrent) == wxInvalidOffset)
                return false;
        //else: icon, just carry on
    }

    unsigned char *data = ptr;

    /* set the whole image to the background color */
    if ( bpp < 16 && (comp == BI_RLE4 || comp == BI_RLE8) )
    {
        for (int i = 0; i < width * height; i++)
        {
            *ptr++ = cmap[0].r;
            *ptr++ = cmap[0].g;
            *ptr++ = cmap[0].b;
        }
        ptr = data;
    }

    int linesize = ((width * bpp + 31) / 32) * 4;

    /* BMPs are stored upside down */
    for ( int line = (height - 1); line >= 0; line-- )
    {
        int linepos = 0;
        for ( int column = 0; column < width ; )
        {
            if ( bpp < 16 )
            {
                linepos++;
                aByte = stream.GetC();
                if ( bpp == 1 )
                {
                    for (int bit = 0; bit < 8 && column < width; bit++)
                    {
                        int index = ((aByte & (0x80 >> bit)) ? 1 : 0);
                        ptr[poffset] = cmap[index].r;
                        ptr[poffset + 1] = cmap[index].g;
                        ptr[poffset + 2] = cmap[index].b;
                        column++;
                    }
                }
                else if ( bpp == 4 )
                {
                    if ( comp == BI_RLE4 )
                    {
                        wxUint8 first;
                        first = aByte;
                        aByte = stream.GetC();
                        if ( first == 0 )
                        {
                            if ( aByte == 0 )
                            {
                                if ( column > 0 )
                                    column = width;
                            }
                            else if ( aByte == 1 )
                            {
                                column = width;
                                line = -1;
                            }
                            else if ( aByte == 2 )
                            {
                                aByte = stream.GetC();
                                column += aByte;
                                linepos = column * bpp / 4;
                                aByte = stream.GetC();
                                line -= aByte; // upside down
                            }
                            else
                            {
                                int absolute = aByte;
                                wxUint8 nibble[2] ;
                                int readBytes = 0 ;
                                for (int k = 0; k < absolute; k++)
                                {
                                    if ( !(k % 2 ) )
                                    {
                                        ++readBytes ;
                                        aByte = stream.GetC();
                                        nibble[0] = (wxUint8)( (aByte & 0xF0) >> 4 ) ;
                                        nibble[1] = (wxUint8)( aByte & 0x0F ) ;
                                    }
                                    ptr[poffset    ] = cmap[nibble[k%2]].r;
                                    ptr[poffset + 1] = cmap[nibble[k%2]].g;
                                    ptr[poffset + 2] = cmap[nibble[k%2]].b;
                                    column++;
                                    if ( k % 2 )
                                        linepos++;
                                }
                                if ( readBytes & 0x01 )
                                    aByte = stream.GetC();
                            }
                        }
                        else
                        {
                            wxUint8 nibble[2] ;
                            nibble[0] = (wxUint8)( (aByte & 0xF0) >> 4 ) ;
                            nibble[1] = (wxUint8)( aByte & 0x0F ) ;

                            for ( int l = 0; l < first && column < width; l++ )
                            {
                                ptr[poffset    ] = cmap[nibble[l%2]].r;
                                ptr[poffset + 1] = cmap[nibble[l%2]].g;
                                ptr[poffset + 2] = cmap[nibble[l%2]].b;
                                column++;
                                if ( l % 2 )
                                    linepos++;
                            }
                        }
                    }
예제 #11
0
파일: imagjpeg2000.cpp 프로젝트: ares89/vlc
// load the jpeg2000 file format
bool wxJPEG2000Handler::LoadFile(wxImage *image, wxInputStream& stream, bool verbose, int index)
{
	opj_dparameters_t parameters;	/* decompression parameters */
	opj_event_mgr_t event_mgr;		/* event manager */
	opj_image_t *opjimage = NULL;
	unsigned char *src = NULL;
    unsigned char *ptr;
	int file_length, jp2c_point, jp2h_point;
	unsigned long int jp2hboxlen, jp2cboxlen;
	opj_codestream_info_t cstr_info;  /* Codestream information structure */
    unsigned char hdr[24];
	int jpfamform;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	/*

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

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

	*/
	{
		int shiftbpp;
		int c, tempcomps;

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

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

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

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

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

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

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

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

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

					}
				}

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

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

						*(ptr++) = *(r++);
						*(ptr++) = *(g++);
						*(ptr++) = *(b++);
					
					}
				}
			}
		}
예제 #12
0
파일: imagjpeg2000.cpp 프로젝트: ares89/vlc
/* internal mini-search for a box signature */
int
jpeg2000_file_parse(wxInputStream& stream, unsigned long int filepoint, unsigned long int filelimit, int level,
					char *scansign, unsigned long int *scanpoint)
{
	unsigned long int       LBox = 0x00000000;
	char                    TBox[5] = "\0\0\0\0";
	int8byte                XLBox = 0x0000000000000000;
	unsigned long int       box_length = 0;
	int                     last_box = 0, box_num = 0;
	int                     box_type = ANY_BOX;
	unsigned char           fourbytes[4];
	int                     box_number = 0;

	/* cycle all over the file */
	box_num = 0;
	last_box = 0;
	while (!last_box) {

		/* do not exceed file limit */
		if (filepoint >= filelimit)
			return (0);

		/* seek on file */
		if (stream.SeekI(filepoint, wxFromStart) == wxInvalidOffset)
			return (-1);

		/* read the mandatory LBox, 4 bytes */
		if (!stream.Read(fourbytes, 4)) {
			wxLogError(wxT("Problem reading LBox from the file (file ended?)"));
			return -1;
		};
		LBox = STREAM_TO_UINT32(fourbytes, 0);

		/* read the mandatory TBox, 4 bytes */
		if (!stream.Read(TBox, 4)) {
			wxLogError(wxT("Problem reading TBox from the file (file ended?)"));
			return -1;
		};

		/* look if scansign is got */
		if ((scansign != NULL) && (memcmp(TBox, scansign, 4) == 0)) {
			/* hack/exploit */
			// stop as soon as you find the level-th codebox
			if (box_number == level) {
				memcpy(scansign, "    ", 4);
				*scanpoint = filepoint;
				return (0);
			} else
				box_number++;

		};

		/* determine the box type */
		for (box_type = JP_BOX; box_type < UNK_BOX; box_type++)
			if (memcmp(TBox, jpeg2000box[box_type].value, 4) == 0)
				break;	

		/* read the optional XLBox, 8 bytes */
		if (LBox == 1) {

			if (!stream.Read(&XLBox, 8)) {
				wxLogError(wxT("Problem reading XLBox from the file (file ended?)"));
				return -1;
			};
			box_length = (unsigned long int) BYTE_SWAP8(XLBox);

		} else if (LBox == 0x00000000) {

			/* last box in file */
			last_box = 1; 
			box_length = filelimit - filepoint;

		} else

			box_length = LBox;


		/* go deep in the box */
		jpeg2000_box_handler_function((jpeg2000boxtype) box_type,
			stream, (LBox == 1) ? (filepoint + 16) : (filepoint + 8),
			filepoint + box_length, level, scansign, scanpoint);

		/* if it's a superbox go inside it */
		if (jpeg2000box[box_type].sbox)
			jpeg2000_file_parse(stream, (LBox == 1) ? (filepoint + 16) : (filepoint + 8), filepoint + box_length,
				level, scansign, scanpoint);

		/* increment box number and filepoint*/
		box_num++;
		filepoint += box_length;

	};

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

}