void Exiv2ReadingWorker::process() {
        LOG_DEBUG << "Worker #" << m_WorkerIndex << "started";

        bool anyError = false;

        int size = m_ItemsToRead.size();
        for (int i = 0; i < size; ++i) {
            if (m_Stopped) { break; }

            Models::ArtworkMetadata *artwork = m_ItemsToRead.at(i);
            const QString &filepath = artwork->getFilepath();
            ImportDataResult importResult;

            try {
                if (readMetadata(artwork, importResult)) {
                    Q_ASSERT(!m_ImportResult.contains(filepath));
                    m_ImportResult.insert(filepath, importResult);
                }
            }
            catch(Exiv2::Error &error) {
                anyError = true;
                LOG_WARNING << "Worker" << m_WorkerIndex << "Exiv2 error:" << error.what();
            }
            catch(...) {
                anyError = true;
                LOG_WARNING << "Worker" << m_WorkerIndex << "Reading error for item" << filepath;
            }
        }

        LOG_INFO << "Worker #" << m_WorkerIndex << "finished";

        emit finished(anyError);
    }
Exemple #2
0
ContentPtr ContentFactory::createContent(const QString& uri)
{
    auto content = _makeContent(uri);
    if (!content->readMetadata())
        throw load_error("Could not read content metadata.");
    return content;
}
DsfFileReader::DsfFileReader(char* filePath) : DsdSampleReader()
{
	this->filePath = filePath;
	// first let's open the file
	file.open(filePath, fstreamPlus::in | fstreamPlus::binary);
	// throw exception if that did not work.
	if (!file.is_open()) {
		errorMsg = "could not open file";
		valid = false;
		return;
	}
	// read the header data
	if (!(valid = readHeaders()))
		return;

	// this code only works with single bit data (could be upgraded later on)
	if (samplesPerChar!=8) {
		errorMsg = "Sorry, only one bit data is supported";
		valid = false;
		return;
	}
	// read the metadata
	readMetadata();
	
	rewind(); // calls clearBuffer -> allocateBuffer
}
Exemple #4
0
// static
MusicMetadata* MetaIO::getMetadata(const QString &filename)
{

    MusicMetadata *mdata = MusicMetadata::createFromFilename(filename);
    if (mdata)
        return mdata;

    return readMetadata(filename);
}
Exemple #5
0
DirFile::DirFile(const std::string& path_)
{
	path = path_;
	if (path.size() == 0) {
		valid = false;
		return;
	}

	if (path[path.size()-1] != '/') path += "/";

	valid = readMetadata();
}
Exemple #6
0
/** \fn Decoder::getMetadata(void)
 *  \brief Get the metadata  for \p filename
 *
 *  First tries to read the metadata from the database. If there
 *  is no database entry, it'll call \p Decoder::readMetadata.
 *
 *  \returns an instance of \p Metadata owned by the caller
 */
Metadata* Decoder::getMetadata(void)
{

    Metadata *mdata = new Metadata(filename);
    if (mdata->isInDatabase())
    {
        return mdata;
    }

    delete mdata;

    return readMetadata();
}
Exemple #7
0
struct RuntimeContext *initializeRuntimeFromFile(char *filePath) {
	struct RuntimeContext *ctx = createRuntimeContext(filePath);
	struct FILE *file = fopen(ctx->file, "rb");

	fseek(file, 0, SEEK_END);
	long fileSize = ftell(file);
	//fseek(file, 0, SEEK_SET);
	rewind(file);

	char* fileBuff = (char*)malloc(fileSize);
	fread(fileBuff, 1, fileSize, file);

	readMetadata(ctx, fileBuff);
	return ctx;
}
//--------------------------------------
StreamingServicePlugin loadPlugin(const QString &directory) {
  QString metadataPath = findFileByExtension(directory, "ini");
  QString scriptPath = findFileByExtension(directory, "js");
  QString descPath = findFileByExtension(directory, "html");
  QString locale = QLocale::system().name().split("_")[0];
  QString translationPath = findTranslation(descPath, locale);
  if (!translationPath.isEmpty())
    descPath = translationPath;
  StreamingServicePlugin retVal;
  retVal.Code = readFileContent(scriptPath);
  retVal.Description = readFileContent(descPath);
  readMetadata(metadataPath, retVal);
  retVal.scriptPath = scriptPath;

  return retVal;
}
Exemple #9
0
UT_Error IE_Imp_EPUB::_loadFile(GsfInput* input)
{
    m_epub = gsf_infile_zip_new(input, NULL);

    if (m_epub == NULL)
    {
        UT_DEBUGMSG(("Can`t create gsf input zip object\n"));
        return UT_ERROR;
    }

    UT_DEBUGMSG(("Reading metadata\n"));
    if (readMetadata() != UT_OK)
    {
        UT_DEBUGMSG(("Failed to read metadata\n"));
        return UT_ERROR;
    }

    UT_DEBUGMSG(("Reading package information\n"));
    if (readPackage() != UT_OK)
    {
        UT_DEBUGMSG(("Failed to read package information\n"));
        return UT_ERROR;
    }

    UT_DEBUGMSG(("Uncompressing OPS data\n"));
    if (uncompress() != UT_OK)
    {
        UT_DEBUGMSG(("Failed to uncompress data\n"));
        return UT_ERROR;
    }

    UT_DEBUGMSG(("Reading OPS data\n"));
    if (readStructure() != UT_OK)
    {
        UT_DEBUGMSG(("Failed to read OPS data\n"));
        return UT_ERROR;
    }

    return UT_OK;

}
Exemple #10
0
int main(int argc, char *argv[])
{
  char *hdfName, *metadataName;
  FILE *metadataFile;

  /* Check for arguments. */
  if (argc !=3) 
  {
    printf("\n");
    printf("Usage: dumpmeta <input HDF file> <output metadata text file>\n");
    printf("\n");
    return EXIT_FAILURE;
  }

  /* Get HDF file name. */
  hdfName=argv[1];
  
  /* Get meta file name. */
  metadataName=argv[2];
  metadataFile=fopen(metadataName, "w");

  /* Read metadata from hdf file. Write to temporary inventory and archive
     files. */
  readMetadata(hdfName, metadataFile, "StructMetadata");
  readMetadata(hdfName, metadataFile, "structmetadata");
  readMetadata(hdfName, metadataFile, "ProductMetadata");
  readMetadata(hdfName, metadataFile, "productmetadata");
  readMetadata(hdfName, metadataFile, "CoreMetadata");
  readMetadata(hdfName, metadataFile, "coremetadata");
  readMetadata(hdfName, metadataFile, "ArchiveMetadata");
  readMetadata(hdfName, metadataFile, "archivemetadata");
  readMetadata(hdfName, metadataFile, "InventoryMetadata");
  readMetadata(hdfName, metadataFile, "inventorymetadata");
  readMetadata(hdfName, metadataFile, "Collection");
  readMetadata(hdfName, metadataFile, "collection");
  readMetadata(hdfName, metadataFile, "CollectionMetadata");
  readMetadata(hdfName, metadataFile, "collectionmetadata");

  fclose(metadataFile);
  return EXIT_SUCCESS;
}
Exemple #11
0
bool PGFLoader::load(const QString& filePath, DImgLoaderObserver* const observer)
{
    m_observer = observer;
    readMetadata(filePath, DImg::PGF);

    FILE* file = fopen(QFile::encodeName(filePath).constData(), "rb");

    if (!file)
    {
        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Could not open source file.";
        loadingFailed();
        return false;
    }

    unsigned char header[3];

    if (fread(&header, 3, 1, file) != 1)
    {
        fclose(file);
        loadingFailed();
        return false;
    }

    unsigned char pgfID[3] = { 0x50, 0x47, 0x46 };

    if (memcmp(&header[0], &pgfID, 3) != 0)
    {
        // not a PGF file
        fclose(file);
        loadingFailed();
        return false;
    }

    fclose(file);

    // -------------------------------------------------------------------
    // Initialize PGF API.

#ifdef WIN32
#ifdef UNICODE
    HANDLE fd = CreateFile((LPCWSTR)(QFile::encodeName(filePath).constData()), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
#else
    HANDLE fd = CreateFile(QFile::encodeName(filePath).constData(), GENERIC_READ, 0, 0, OPEN_EXISTING, 0, 0);
#endif

    if (fd == INVALID_HANDLE_VALUE)
    {
        loadingFailed();
        return false;
    }

#else

    int fd = open(QFile::encodeName(filePath).constData(), O_RDONLY);

    if (fd == -1)
    {
        loadingFailed();
        return false;
    }

#endif

    CPGFFileStream stream(fd);
    CPGFImage      pgf;
    int            colorModel = DImg::COLORMODELUNKNOWN;

    try
    {
        // open pgf image
        pgf.Open(&stream);

        switch (pgf.Mode())
        {
            case ImageModeRGBColor:
            case ImageModeRGB48:
                m_hasAlpha = false;
                colorModel = DImg::RGB;
                break;

            case ImageModeRGBA:
                m_hasAlpha = true;
                colorModel = DImg::RGB;
                break;

            default:
                qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Cannot load PGF image: color mode not supported (" << pgf.Mode() << ")";
                loadingFailed();
                return false;
                break;
        }

        switch (pgf.Channels())
        {
            case 3:
            case 4:
                break;

            default:
                qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Cannot load PGF image: color channels number not supported (" << pgf.Channels() << ")";
                loadingFailed();
                return false;
                break;
        }

        int bitDepth = pgf.BPP();

        switch (bitDepth)
        {
            case 24:    // RGB 8 bits.
            case 32:    // RGBA 8 bits.
                m_sixteenBit = false;
                break;

            case 48:    // RGB 16 bits.
            case 64:    // RGBA 16 bits.
                m_sixteenBit = true;
                break;

            default:
                qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Cannot load PGF image: color bits depth not supported (" << bitDepth << ")";
                loadingFailed();
                return false;
                break;
        }

        if(DIGIKAM_DIMG_LOG_PGF().isDebugEnabled()) {
            const PGFHeader* header = pgf.GetHeader();
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF width    = " << header->width;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF height   = " << header->height;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF bbp      = " << header->bpp;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF channels = " << header->channels;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF quality  = " << header->quality;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "PGF mode     = " << header->mode;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Has Alpha    = " << m_hasAlpha;
            qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Is 16 bits   = " << m_sixteenBit;
        }

        // NOTE: see bug #273765 : Loading PGF thumbs with OpenMP support through a separated thread do not work properlly with libppgf 6.11.24
        pgf.ConfigureDecoder(false);

        int width   = pgf.Width();
        int height  = pgf.Height();
        uchar* data = 0;

        QSize originalSize(width, height);

        if (m_loadFlags & LoadImageData)
        {
            // -------------------------------------------------------------------
            // Find out if we do the fast-track loading with reduced size. PGF specific.
            int level          = 0;
            QVariant attribute = imageGetAttribute(QLatin1String("scaledLoadingSize"));

            if (attribute.isValid() && pgf.Levels() > 0)
            {
                int scaledLoadingSize = attribute.toInt();
                int i, w, h;

                for (i = pgf.Levels() - 1 ; i >= 0 ; --i)
                {
                    w = pgf.Width(i);
                    h = pgf.Height(i);

                    if (qMin(w, h) >= scaledLoadingSize)
                    {
                        break;
                    }
                }

                if (i >= 0)
                {
                    width  = w;
                    height = h;
                    level  = i;
                    qCDebug(DIGIKAM_DIMG_LOG_PGF) << "Loading PGF scaled version at level " << i
                                      << " (" << w << " x " << h << ") for size "
                                      << scaledLoadingSize;
                }
            }

            if (m_sixteenBit)
            {
                data = new_failureTolerant(width, height, 8); // 16 bits/color/pixel
            }
            else
            {
                data = new_failureTolerant(width, height, 4); // 8 bits/color/pixel
            }

            // Fill all with 255 including alpha channel.
            memset(data, 0xFF, width * height * (m_sixteenBit ? 8 : 4));

            pgf.Read(level, CallbackForLibPGF, this);
            pgf.GetBitmap(m_sixteenBit ? width * 8 : width * 4,
                          (UINT8*)data,
                          m_sixteenBit ? 64 : 32,
                          NULL,
                          CallbackForLibPGF, this);

            if (observer)
            {
                observer->progressInfo(m_image, 1.0);
            }
        }

        // -------------------------------------------------------------------
        // Get ICC color profile.

        if (m_loadFlags & LoadICCData)
        {
            // TODO: Implement proper storage in PGF for color profiles
            checkExifWorkingColorSpace();
        }

        imageWidth()  = width;
        imageHeight() = height;
        imageData()   = data;
        imageSetAttribute(QLatin1String("format"),             QLatin1String("PGF"));
        imageSetAttribute(QLatin1String("originalColorModel"), colorModel);
        imageSetAttribute(QLatin1String("originalBitDepth"),   bitDepth);
        imageSetAttribute(QLatin1String("originalSize"),       originalSize);

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        return true;
    }
    catch (IOException& e)
    {
        int err = e.error;

        if (err >= AppError)
        {
            err -= AppError;
        }

        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Error: Opening and reading PGF image failed (" << err << ")!";

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        loadingFailed();
        return false;
    }
    catch (std::bad_alloc& e)
    {
        qCWarning(DIGIKAM_DIMG_LOG_PGF) << "Failed to allocate memory for loading" << filePath << e.what();

#ifdef WIN32
        CloseHandle(fd);
#else
        close(fd);
#endif

        loadingFailed();
        return false;
    }
    return true;
}
Exemple #12
0
DLL_EXPORT void execute(char *fileBuff) {
	struct RuntimeContext *ctx = createRuntimeContext(NULL);
	readMetadata(ctx, fileBuff);
	executeImpl(ctx);
}
status_t PublicVolume::doMount() {
    // TODO: expand to support mounting other filesystems
    readMetadata();

    if (mFsType != "vfat") {
        LOG(ERROR) << getId() << " unsupported filesystem " << mFsType;
        return -EIO;
    }

    if (vfat::Check(mDevPath)) {
        LOG(ERROR) << getId() << " failed filesystem check";
        return -EIO;
    }

    // Use UUID as stable name, if available
    std::string stableName = getId();
    if (!mFsUuid.empty()) {
        stableName = mFsUuid;
    }

    mRawPath = StringPrintf("/mnt/media_rw/%s", stableName.c_str());

    mFuseDefault = StringPrintf("/mnt/runtime/default/%s", stableName.c_str());
    mFuseRead = StringPrintf("/mnt/runtime/read/%s", stableName.c_str());
    mFuseWrite = StringPrintf("/mnt/runtime/write/%s", stableName.c_str());

    setInternalPath(mRawPath);
    if (getMountFlags() & MountFlags::kVisible) {
        setPath(StringPrintf("/storage/%s", stableName.c_str()));
    } else {
        setPath(mRawPath);
    }

    if (fs_prepare_dir(mRawPath.c_str(), 0700, AID_ROOT, AID_ROOT) ||
            fs_prepare_dir(mFuseDefault.c_str(), 0700, AID_ROOT, AID_ROOT) ||
            fs_prepare_dir(mFuseRead.c_str(), 0700, AID_ROOT, AID_ROOT) ||
            fs_prepare_dir(mFuseWrite.c_str(), 0700, AID_ROOT, AID_ROOT)) {
        PLOG(ERROR) << getId() << " failed to create mount points";
        return -errno;
    }

    if (vfat::Mount(mDevPath, mRawPath, false, false, false,
            AID_MEDIA_RW, AID_MEDIA_RW, 0007, true)) {
        PLOG(ERROR) << getId() << " failed to mount " << mDevPath;
        return -EIO;
    }

    if (getMountFlags() & MountFlags::kPrimary) {
        initAsecStage();
    }

    if (!(getMountFlags() & MountFlags::kVisible)) {
        // Not visible to apps, so no need to spin up FUSE
        return OK;
    }

    dev_t before = GetDevice(mFuseWrite);

    if (!(mFusePid = fork())) {
        if (getMountFlags() & MountFlags::kPrimary) {
            if (execl(kFusePath, kFusePath,
                    "-u", "1023", // AID_MEDIA_RW
                    "-g", "1023", // AID_MEDIA_RW
                    "-U", std::to_string(getMountUserId()).c_str(),
                    "-w",
                    mRawPath.c_str(),
                    stableName.c_str(),
                    NULL)) {
                PLOG(ERROR) << "Failed to exec";
            }
        } else {
            if (execl(kFusePath, kFusePath,
                    "-u", "1023", // AID_MEDIA_RW
                    "-g", "1023", // AID_MEDIA_RW
                    "-U", std::to_string(getMountUserId()).c_str(),
                    mRawPath.c_str(),
                    stableName.c_str(),
                    NULL)) {
                PLOG(ERROR) << "Failed to exec";
            }
        }

        LOG(ERROR) << "FUSE exiting";
        _exit(1);
    }

    if (mFusePid == -1) {
        PLOG(ERROR) << getId() << " failed to fork";
        return -errno;
    }

    while (before == GetDevice(mFuseWrite)) {
        LOG(VERBOSE) << "Waiting for FUSE to spin up...";
        usleep(50000); // 50ms
    }

    return OK;
}
Exemple #14
0
bool QImageLoader::load(const QString& filePath, DImgLoaderObserver* const observer)
{
    readMetadata(filePath, DImg::QIMAGE);

    // Loading is opaque to us. No support for stopping from observer,
    // progress info are only pseudo values
    QImageReader reader(filePath);
    reader.setDecideFormatFromContent(true);

    QImage image = reader.read();

    if (observer)
    {
        observer->progressInfo(m_image, 0.9F);
    }

    if (image.isNull())
    {
        qCWarning(DIGIKAM_DIMG_LOG_QIMAGE) << "Can not load \"" << filePath << "\" using DImg::QImageLoader!";
        loadingFailed();
        return false;
    }

    int colorModel    = DImg::COLORMODELUNKNOWN;
    int originalDepth = 0;

    switch (image.format())
    {
    case QImage::Format_Invalid:
    default:
        colorModel = DImg::COLORMODELUNKNOWN;
        originalDepth = 0;
        break;

    case QImage::Format_Mono:
    case QImage::Format_MonoLSB:
        colorModel = DImg::MONOCHROME;
        originalDepth = 1;
        break;

    case QImage::Format_Indexed8:
        colorModel = DImg::INDEXED;
        originalDepth = 0;
        break;

    case QImage::Format_RGB32:
        colorModel = DImg::RGB;
        originalDepth = 8;
        break;

    case QImage::Format_ARGB32:
    case QImage::Format_ARGB32_Premultiplied:
        colorModel = DImg::RGB;
        originalDepth = 8;
        break;
    }

    m_hasAlpha        = image.hasAlphaChannel();
    QImage target     = image.convertToFormat(QImage::Format_ARGB32);
    uint w            = target.width();
    uint h            = target.height();
    uchar* const data = new_failureTolerant(w, h, 4);

    if (!data)
    {
        qCWarning(DIGIKAM_DIMG_LOG_QIMAGE) << "Failed to allocate memory for loading" << filePath;
        loadingFailed();
        return false;
    }

    uint*  sptr = reinterpret_cast<uint*>(target.bits());
    uchar* dptr = data;

    for (uint i = 0 ; i < w * h ; ++i)
    {
        dptr[0] = qBlue(*sptr);
        dptr[1] = qGreen(*sptr);
        dptr[2] = qRed(*sptr);
        dptr[3] = qAlpha(*sptr);

        dptr += 4;
        sptr++;
    }

    if (observer)
    {
        observer->progressInfo(m_image, 1.0);
    }

    imageWidth()  = w;
    imageHeight() = h;
    imageData()   = data;

    // We considering that PNG is the most representative format of an image loaded by Qt
    imageSetAttribute(QLatin1String("format"),             QLatin1String("PNG"));
    imageSetAttribute(QLatin1String("originalColorModel"), colorModel);
    imageSetAttribute(QLatin1String("originalBitDepth"),   originalDepth);
    imageSetAttribute(QLatin1String("originalSize"),       QSize(w, h));

    return true;
}
Exemple #15
0
bool JP2KLoader::load(const QString& filePath, DImgLoaderObserver* observer)
{
    readMetadata(filePath, DImg::JPEG);

    FILE* file = fopen(QFile::encodeName(filePath), "rb");

    if (!file)
    {
        loadingFailed();
        return false;
    }

    unsigned char header[9];

    if (fread(&header, 9, 1, file) != 1)
    {
        fclose(file);
        loadingFailed();
        return false;
    }

    unsigned char jp2ID[5] = { 0x6A, 0x50, 0x20, 0x20, 0x0D, };
    unsigned char jpcID[2] = { 0xFF, 0x4F };

    if (memcmp(&header[4], &jp2ID, 5) != 0 &&
        memcmp(&header,    &jpcID, 2) != 0)
    {
        // not a jpeg2000 file
        fclose(file);
        loadingFailed();
        return false;
    }

    fclose(file);

    imageSetAttribute("format", "JP2K");

    if (!(m_loadFlags & LoadImageData) && !(m_loadFlags & LoadICCData))
    {
        // libjasper will load the full image in memory already when calling jas_image_decode.
        // This is bad when scanning. See bugs 215458 and 195583.
        //FIXME: Use Exiv2 or OpenJPEG to extract this info
        DMetadata metadata(filePath);
        QSize size = metadata.getImageDimensions();

        if (size.isValid())
        {
            imageWidth() = size.width();
            imageHeight() = size.height();
        }

        return true;
    }

    // -------------------------------------------------------------------
    // Initialize JPEG 2000 API.

    register long  i, x, y;
    int            components[4];
    unsigned int   maximum_component_depth, scale[4], x_step[4], y_step[4];
    unsigned long  number_components;

    jas_image_t*  jp2_image   = 0;
    jas_stream_t* jp2_stream  = 0;
    jas_matrix_t* pixels[4];

    int init = jas_init();

    if (init != 0)
    {
        kDebug() << "Unable to init JPEG2000 decoder";
        loadingFailed();
        return false;
    }

    jp2_stream = jas_stream_fopen(QFile::encodeName(filePath), "rb");

    if (jp2_stream == 0)
    {
        kDebug() << "Unable to open JPEG2000 stream";
        loadingFailed();
        return false;
    }

    jp2_image = jas_image_decode(jp2_stream, -1, 0);

    if (jp2_image == 0)
    {
        jas_stream_close(jp2_stream);
        kDebug() << "Unable to decode JPEG2000 image";
        loadingFailed();
        return false;
    }

    jas_stream_close(jp2_stream);

    // some pseudo-progress
    if (observer)
    {
        observer->progressInfo(m_image, 0.1F);
    }

    // -------------------------------------------------------------------
    // Check color space.

    int colorModel;

    switch (jas_clrspc_fam(jas_image_clrspc(jp2_image)))
    {
        case JAS_CLRSPC_FAM_RGB:
        {
            components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_R);
            components[1] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_G);
            components[2] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_RGB_B);

            if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0))
            {
                jas_image_destroy(jp2_image);
                kDebug() << "Error parsing JPEG2000 image : Missing Image Channel";
                loadingFailed();
                return false;
            }

            number_components = 3;
            components[3]     = jas_image_getcmptbytype(jp2_image, 3);

            if (components[3] > 0)
            {
                m_hasAlpha = true;
                ++number_components;
            }

            colorModel = DImg::RGB;
            break;
        }
        case JAS_CLRSPC_FAM_GRAY:
        {
            components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_GRAY_Y);

            if (components[0] < 0)
            {
                jas_image_destroy(jp2_image);
                kDebug() << "Error parsing JP2000 image : Missing Image Channel";
                loadingFailed();
                return false;
            }

            number_components = 1;
            colorModel        = DImg::GRAYSCALE;
            break;
        }
        case JAS_CLRSPC_FAM_YCBCR:
        {
            components[0] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_YCBCR_Y);
            components[1] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_YCBCR_CB);
            components[2] = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_YCBCR_CR);

            if ((components[0] < 0) || (components[1] < 0) || (components[2] < 0))
            {
                jas_image_destroy(jp2_image);
                kDebug() << "Error parsing JP2000 image : Missing Image Channel";
                loadingFailed();
                return false;
            }

            number_components = 3;
            components[3]     = jas_image_getcmptbytype(jp2_image, JAS_IMAGE_CT_UNKNOWN);

            if (components[3] > 0)
            {
                m_hasAlpha = true;
                ++number_components;
            }

            // FIXME : image->colorspace=YCbCrColorspace;
            colorModel = DImg::YCBCR;
            break;
        }
        default:
        {
            jas_image_destroy(jp2_image);
            kDebug() << "Error parsing JP2000 image : Colorspace Model Is Not Supported";
            loadingFailed();
            return false;
        }
    }

    // -------------------------------------------------------------------
    // Check image geometry.

    imageWidth()  = jas_image_width(jp2_image);
    imageHeight() = jas_image_height(jp2_image);

    for (i = 0; i < (long)number_components; ++i)
    {
        if ((((jas_image_cmptwidth(jp2_image, components[i])*
               jas_image_cmpthstep(jp2_image, components[i])) != (long)imageWidth()))  ||
            (((jas_image_cmptheight(jp2_image, components[i])*
               jas_image_cmptvstep(jp2_image, components[i])) != (long)imageHeight())) ||
            (jas_image_cmpttlx(jp2_image, components[i]) != 0)                      ||
            (jas_image_cmpttly(jp2_image, components[i]) != 0)                      ||
            (jas_image_cmptsgnd(jp2_image, components[i]) != false))
        {
            jas_image_destroy(jp2_image);
            kDebug() << "Error parsing JPEG2000 image : Irregular Channel Geometry Not Supported";
            loadingFailed();
            return false;
        }

        x_step[i] = jas_image_cmpthstep(jp2_image, components[i]);
        y_step[i] = jas_image_cmptvstep(jp2_image, components[i]);
    }

    // -------------------------------------------------------------------
    // Get image format.

    m_hasAlpha              = number_components > 3;
    maximum_component_depth = 0;

    for (i = 0; i < (long)number_components; ++i)
    {
        maximum_component_depth = qMax((long)jas_image_cmptprec(jp2_image,components[i]),
                                       (long)maximum_component_depth);
        pixels[i] = jas_matrix_create(1, ((unsigned int)imageWidth())/x_step[i]);

        if (!pixels[i])
        {
            jas_image_destroy(jp2_image);
            kDebug() << "Error decoding JPEG2000 image data : Memory Allocation Failed";
            loadingFailed();
            return false;
        }
    }

    if (maximum_component_depth > 8)
    {
        m_sixteenBit = true;
    }

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        scale[i] = 1;
        int prec = jas_image_cmptprec(jp2_image, components[i]);

        if (m_sixteenBit && prec < 16)
        {
            scale[i] = (1 << (16 - jas_image_cmptprec(jp2_image, components[i])));
        }
    }

    // -------------------------------------------------------------------
    // Get image data.

    uchar* data = 0;

    if (m_loadFlags & LoadImageData)
    {
        if (m_sixteenBit)          // 16 bits image.
        {
            data = new_failureTolerant(imageWidth()*imageHeight()*8);
        }
        else
        {
            data = new_failureTolerant(imageWidth()*imageHeight()*4);
        }

        if (!data)
        {
            kDebug() << "Error decoding JPEG2000 image data : Memory Allocation Failed";
            jas_image_destroy(jp2_image);

            for (i = 0 ; i < (long)number_components ; ++i)
            {
                jas_matrix_destroy(pixels[i]);
            }

            jas_cleanup();
            loadingFailed();
            return false;
        }

        uint   checkPoint     = 0;
        uchar* dst            = data;
        unsigned short* dst16 = (unsigned short*)data;

        for (y = 0 ; y < (long)imageHeight() ; ++y)
        {
            for (i = 0 ; i < (long)number_components; ++i)
            {
                int ret = jas_image_readcmpt(jp2_image, (short)components[i], 0,
                                             ((unsigned int) y)            / y_step[i],
                                             ((unsigned int) imageWidth()) / x_step[i],
                                             1, pixels[i]);

                if (ret != 0)
                {
                    kDebug() << "Error decoding JPEG2000 image data";
                    delete [] data;
                    jas_image_destroy(jp2_image);

                    for (i = 0 ; i < (long)number_components ; ++i)
                    {
                        jas_matrix_destroy(pixels[i]);
                    }

                    jas_cleanup();
                    loadingFailed();
                    return false;
                }
            }

            switch (number_components)
            {
                case 1: // Grayscale.
                {
                    for (x = 0 ; x < (long)imageWidth() ; ++x)
                    {
                        dst[0] = (uchar)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                        dst[1] = dst[0];
                        dst[2] = dst[0];
                        dst[3] = 0xFF;

                        dst += 4;
                    }

                    break;
                }
                case 3: // RGB.
                {
                    if (!m_sixteenBit)   // 8 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst[0] = (uchar)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst[1] = (uchar)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst[2] = (uchar)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst[3] = 0xFF;

                            dst += 4;
                        }
                    }
                    else                // 16 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst16[0] = (unsigned short)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst16[1] = (unsigned short)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst16[2] = (unsigned short)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst16[3] = 0xFFFF;

                            dst16 += 4;
                        }
                    }

                    break;
                }
                case 4: // RGBA.
                {
                    if (!m_sixteenBit)   // 8 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst[0] = (uchar)(scale[2] * jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst[1] = (uchar)(scale[1] * jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst[2] = (uchar)(scale[0] * jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst[3] = (uchar)(scale[3] * jas_matrix_getv(pixels[3], x/x_step[3]));

                            dst += 4;
                        }
                    }
                    else                // 16 bits image.
                    {
                        for (x = 0 ; x < (long)imageWidth() ; ++x)
                        {
                            // Blue
                            dst16[0] = (unsigned short)(scale[2]*jas_matrix_getv(pixels[2], x/x_step[2]));
                            // Green
                            dst16[1] = (unsigned short)(scale[1]*jas_matrix_getv(pixels[1], x/x_step[1]));
                            // Red
                            dst16[2] = (unsigned short)(scale[0]*jas_matrix_getv(pixels[0], x/x_step[0]));
                            // Alpha
                            dst16[3] = (unsigned short)(scale[3]*jas_matrix_getv(pixels[3], x/x_step[3]));

                            dst16 += 4;
                        }
                    }

                    break;
                }
            }

            // use 0-10% and 90-100% for pseudo-progress
            if (observer && y >= (long)checkPoint)
            {
                checkPoint += granularity(observer, y, 0.8F);

                if (!observer->continueQuery(m_image))
                {
                    delete [] data;
                    jas_image_destroy(jp2_image);

                    for (i = 0 ; i < (long)number_components ; ++i)
                    {
                        jas_matrix_destroy(pixels[i]);
                    }

                    jas_cleanup();

                    loadingFailed();
                    return false;
                }

                observer->progressInfo(m_image, 0.1 + (0.8 * ( ((float)y)/((float)imageHeight()) )));
            }
        }
    }

    // -------------------------------------------------------------------
    // Get ICC color profile.

    if (m_loadFlags & LoadICCData)
    {
        jas_iccprof_t* icc_profile = 0;
        jas_stream_t*  icc_stream  = 0;
        jas_cmprof_t*  cm_profile  = 0;

        cm_profile = jas_image_cmprof(jp2_image);

        if (cm_profile != 0)
        {
            icc_profile = jas_iccprof_createfromcmprof(cm_profile);
        }

        if (icc_profile != 0)
        {
            icc_stream = jas_stream_memopen(NULL, 0);

            if (icc_stream != 0)
            {
                if (jas_iccprof_save(icc_profile, icc_stream) == 0)
                {
                    if (jas_stream_flush(icc_stream) == 0)
                    {
                        jas_stream_memobj_t* blob = (jas_stream_memobj_t*) icc_stream->obj_;
                        QByteArray profile_rawdata;
                        profile_rawdata.resize(blob->len_);
                        memcpy(profile_rawdata.data(), blob->buf_, blob->len_);
                        imageSetIccProfile(profile_rawdata);
                        jas_stream_close(icc_stream);
                    }
                }
            }
        }
    }

    if (observer)
    {
        observer->progressInfo(m_image, 1.0);
    }

    imageData() = data;
    imageSetAttribute("format", "JP2K");
    imageSetAttribute("originalColorModel", colorModel);
    imageSetAttribute("originalBitDepth", maximum_component_depth);
    imageSetAttribute("originalSize", QSize(imageWidth(), imageHeight()));

    jas_image_destroy(jp2_image);

    for (i = 0 ; i < (long)number_components ; ++i)
    {
        jas_matrix_destroy(pixels[i]);
    }

    jas_cleanup();

    return true;
}
Exemple #16
0
Package::Package(QString path, QObject* parent)
    : QObject(parent),
    m_metadata(new MetaData)
{
    /*
    A package roughly looks like this:

    examplepackage/
    |-- actions
    |   |-- silk-webapp-silk-commitlog.desktop
    |   |-- silk-webapp-silk-sidebar.desktop
    |   |-- silk-webapp-silk-sourcetree.desktop
    |   `-- silk-webapp-silk-urltrigger.desktop
    |-- plugin.desktop
    |-- scripts
    |   `-- togglesidebar.js
    `-- webapp.desktop


    */
    //m_metadata->pluginName = QString("silk");
    QString installedPath = findPackage(path);
    if (!installedPath.isEmpty()) {
        m_root = installedPath;
        m_metadataFile = m_root.path() + "/" + "metadata.desktop";
        readMetadata();
        readDir();
        //kDebug() << "installed, but valid?" << isValid();
        return;
    }

    QDir _d(path);
    if (_d.isRelative()) {
        path = QDir::currentPath() + "/" + path;
    }
    
    KUrl _dir(path);

    if (path.isEmpty()) {
        kDebug() << "Empty package structure";
    } else if (path.endsWith(".selkie")) {
        //kDebug() << "Package file:" << path;
        //QString unpackPath = "/tmp/unpacked/";

        KTempDir tmp;
        tmp.setAutoRemove(false);
        //kDebug() << "TempDir:" << tmp.name();
        QString unpackPath = tmp.name();
        importPackage(path, unpackPath);
        m_root = KUrl(unpackPath);
        m_metadataFile = unpackPath + "/" + "metadata.desktop";
        readMetadata();
        readDir();
    } else if (_dir.isValid()) {
        //kDebug() << "Reading dir" << _dir;
        m_root = _dir;
        m_metadataFile = m_root.path() + "/" + "metadata.desktop";
        readMetadata();
        readDir();
    }
    //show();
}