Example #1
0
void Widget::udpProcessPendingDatagrams()
{
    while (udpSocket->hasPendingDatagrams())
    {
        QHostAddress rAddr;
        quint16 rPort;
        QByteArray datagram;
        qint64 dataRead = 0;
        int datagramSize = udpSocket->pendingDatagramSize();
        datagram.resize(datagramSize);

        while(dataRead < datagram.size())
        {
            qint64 readNow = udpSocket->readDatagram(datagram.data()+dataRead, datagramSize, &rAddr, &rPort); // le +dataRead sur un tableau, ça décale le pointeur d'un offset de taille dataRead !
            if(readNow != -1)
            {
                dataRead += readNow; // Counts the number of bytes read in total, stop when DataRead reached pendingDatagramSize
                if (datagramSize > (datagram.size() - dataRead)) // Evite de lire après la fin du tableau en mode fragmenté, evite donc que dataSent dépasse datagramSize, sinon Overflow et envoi de données inutiles et aléatoires !!
                    datagramSize = (datagram.size() - dataRead);
                //QMessageBox::information(NULL,"SenderInfo",QString("DatagramSize : %1  sentNow : %2  dataSent : %3 Sizeof(datagram->data()) : %4").arg(QString().setNum(datagramSize),QString().setNum(sentNow),QString().setNum(dataSent),QString().setNum(datagram->size())));
            }
            else
            {
                // Here, we add a message to the udpMessages for filtering later.
                logStatusMessage(QString("Socket error: ").arg(udpSocket->errorString()), udpTag);
                return;
            }
        }

        // Add player on connection
        if ((unsigned char)datagram[0]==MsgConnect && (unsigned char)datagram[1]==0
                && (unsigned char)datagram[2]==0 && datagram.size()>=22)
        {
            QString name = dataToString(datagram.right(datagram.size()-22));
            int nameFullSize = getVUint32Size(datagram.right(datagram.size()-22))+name.size();
            QString sesskey = dataToString(datagram.right(datagram.size()-22-nameFullSize));
            //logMessage(QString("UDP: Connect detected with name : ")+name, udpTag);
            //logMessage(QString("UDP: Connect detected with sesskey : ")+sesskey, udpTag);
            //logMessage(QString("UDP: Datagram was : ")+datagram.toHex(), udpTag);

            bool is_sesskey_valid = true;

            if (enableSessKeyValidation) {
                is_sesskey_valid = QCryptographicHash::hash(QString(sesskey.right(40) + saltPassword).toLatin1(), QCryptographicHash::Md5).toHex() == sesskey.left(32);
            }

            if (is_sesskey_valid)
            {
                //logMessage("Sesskey token accepted", udpTag);

                // Create new player if needed, else just update player
                Player* newPlayer = Player::findPlayer(udpPlayers, rAddr.toString(),rPort);
                if (newPlayer->IP != rAddr.toString()) // IP:Port not found in player list
                {
                    newPlayer->resetNetwork();
                    //newPlayer->connected = true; // Not really connected until we finish the handshake
                    newPlayer->name = name;
                    newPlayer->IP = rAddr.toString();
                    newPlayer->port = rPort;

                    // Check if we have too many players connected
                    int n=0;
                    for (int i=0;i<udpPlayers.size();i++)
                        if (udpPlayers[i]->connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error: Too many players connected. Try again later.");
                    }
                    else
                        // If not add the player
                        udpPlayers << newPlayer;
                }
                else  // IP:Port found in player list
                {
                    if (newPlayer->connected) // TODO: Error, player already connected
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error: Player already connected.");
                        return;
                    }

                    // Check if we have too many players connected
                    int n=0;
                    for (int i=0;i<udpPlayers.size();i++)
                        if (udpPlayers[i]->connected)
                            n++;
                    if (n>=maxConnected)
                    {
                        sendMessage(newPlayer, MsgDisconnect, "Error: Too many players connected. Try again later.");
                    }

                    newPlayer->resetNetwork();
                    newPlayer->name = name;
                    newPlayer->IP = rAddr.toString();
                    newPlayer->port = rPort;
                    //newPlayer->connected = true; // We're not really connected until we finish the handshake
                }
            }
            else
            {
                QString badHash = QCryptographicHash::hash((QString(sesskey.right(40))
                                +saltPassword).toLatin1(), QCryptographicHash::Md5).toHex();
                logMessage("UDP: Sesskey rejected: got '"+badHash+"' instead of '"+sesskey.left(32)+"', passhash was '"+QString(sesskey.right(40)), udpTag);
                Player* newPlayer = new Player;
                newPlayer->IP = rAddr.toString();
                newPlayer->port = rPort;
                sendMessage(newPlayer, MsgDisconnect, "Error : Wrong sesskey hash.");
                return;
            }
        }

        Player* player = Player::findPlayer(udpPlayers, rAddr.toString(), rPort);
        if (player->IP == rAddr.toString() && player->port == rPort)
        {
            // Acquire data
            player->receivedDatas->append(datagram);

            // Process data
            receiveMessage(player);
        }
        else // You need to connect with TCP first
        {
            logMessage("UDP: Request from unknown peer rejected : "+rAddr.toString()+":"+QString().setNum(rPort), udpTag);
            // Send disconnect message manually, with an appropriate message.
            QString data("BITCH, YOU ARE EITHER A HACKER OR THE SERVER JUST HATES THE F**K OUT OF YOU. RELOG OR YOU AINT GETTIN ON THIS SERVER, K?");
            QByteArray msg(6,0);
            msg[0] = MsgDisconnect;
            msg[3] = (quint8)(((data.size()+1)*8)&0xFF);
            msg[4] = (quint8)((((data.size()+1)*8)>>8)&0xFF);
            msg[5] = (quint8)data.size();
            msg += data;
            win.udpSocket->writeDatagram(msg,rAddr,rPort);
        }
    }
}
//
// Load OpenSSL's list of root certificate authorities
//
void PaymentServer::LoadRootCAs(X509_STORE* _store)
{
    if (PaymentServer::certStore == NULL)
        atexit(PaymentServer::freeCertStore);
    else
        freeCertStore();

    // Unit tests mostly use this, to pass in fake root CAs:
    if (_store)
    {
        PaymentServer::certStore = _store;
        return;
    }

    // Normal execution, use either -rootcertificates or system certs:
    PaymentServer::certStore = X509_STORE_new();

    // Note: use "-system-" default here so that users can pass -rootcertificates=""
    // and get 'I don't like X.509 certificates, don't trust anybody' behavior:
    QString certFile = QString::fromStdString(GetArg("-rootcertificates", "-system-"));

    if (certFile.isEmpty())
        return; // Empty store

    QList<QSslCertificate> certList;

    if (certFile != "-system-")
    {
        certList = QSslCertificate::fromPath(certFile);
        // Use those certificates when fetching payment requests, too:
        QSslSocket::setDefaultCaCertificates(certList);
    }
    else
        certList = QSslSocket::systemCaCertificates ();

    int nRootCerts = 0;
    const QDateTime currentTime = QDateTime::currentDateTime();
    foreach (const QSslCertificate& cert, certList)
    {
        if (currentTime < cert.effectiveDate() || currentTime > cert.expiryDate()) {
            ReportInvalidCertificate(cert);
            continue;
        }
#if QT_VERSION >= 0x050000
        if (cert.isBlacklisted()) {
            ReportInvalidCertificate(cert);
            continue;
        }
#endif
        QByteArray certData = cert.toDer();
        const unsigned char *data = (const unsigned char *)certData.data();

        X509* x509 = d2i_X509(0, &data, certData.size());
        if (x509 && X509_STORE_add_cert(PaymentServer::certStore, x509))
        {
            // Note: X509_STORE_free will free the X509* objects when
            // the PaymentServer is destroyed
            ++nRootCerts;
        }
        else
        {
            ReportInvalidCertificate(cert);
            continue;
        }
    }
    qDebug() << "PaymentServer::LoadRootCAs : Loaded " << nRootCerts << " root certificates";

    // Project for another day:
    // Fetch certificate revocation lists, and add them to certStore.
    // Issues to consider:
    //   performance (start a thread to fetch in background?)
    //   privacy (fetch through tor/proxy so IP address isn't revealed)
    //   would it be easier to just use a compiled-in blacklist?
    //    or use Qt's blacklist?
    //   "certificate stapling" with server-side caching is more efficient
}
Example #3
0
int MData::Load_binary(char* filename, int depth, int width, int height, bool transpose_flag){
/*
    QFile file(filename);
    if(!file.open(QIODevice::ReadOnly)){ return -1;};;
    QDataStream in(&file);    // read the data serialized from the file

    size_x = width; size_y = height;
    if(array_2D_initial) delete [] array_2D_initial;
    array_2D_initial = new double [size_x*size_y];

    if(array_2D_processed) delete [] array_2D_processed;
    array_2D_processed = new double [size_x*size_y];
    for(int i=0; i<size_x*size_y; i++){ array_2D_initial[i] = 0; array_2D_processed[i] = 0;} //array_2D_processed[i] = 0;

    double a;
    for(int i=0; i < (size_x*size_y);i++){
         in >> a;           // extract element
         array_2D_initial[i] = a;
         array_2D_processed[i] = array_2D_initial[i];
    }

*/

    QFile file(filename);
    if (!file.open(QIODevice::ReadOnly)) return 0;
    QByteArray var = file.readAll();

    if(transpose_flag){size_y = width; size_x = height;}
    else{ size_x = width; size_y = height; }
    if(array_2D_initial) delete [] array_2D_initial;
    array_2D_initial = new double [size_x*size_y];

    if(array_2D_processed) delete [] array_2D_processed;
    array_2D_processed = new double [size_x*size_y];
    for(int i=0; i<size_x*size_y; i++){ array_2D_initial[i] = 0; array_2D_processed[i] = 0;} //array_2D_processed[i] = 0;

    unsigned int *emptyarray; emptyarray = new unsigned int [size_x*size_y];
    //int32_t *emptyarray; emptyarray = new int32_t [size_x*size_y];

    memcpy(emptyarray, var.data(), size_x*size_y*sizeof(int));

    if(transpose_flag) {
        for (int i=0;i<size_y;i++){
           for (int j=0;j<size_x;j++){
               array_2D_initial[i + j*size_y] = (double) emptyarray[j + i*size_x] / 100.0;
               array_2D_processed[i + j*size_y] = array_2D_initial[i + j*size_y];
           }
        }
    }
    else {
            for(int i=0; i<size_x*size_y; i++){ array_2D_initial[i] = (double) emptyarray[i] / 100.0; array_2D_processed[i] = (double) emptyarray[i] / 100.0;}
        }


    //if(array_2D_result) {delete [] array_2D_result; array_2D_result = NULL;}
    //array_2D_result = new double [size_x*size_y];

    file.close();
    delete [] emptyarray;

    return 1;
}
QString
ITunesDevice::LibraryPath()
{
    if ( !m_iTunesLibraryPath.isEmpty() )
        return m_iTunesLibraryPath;

    QString path;
    QString confPath;

#ifdef Q_WS_MAC
    QSettings ist( "apple.com", "iTunes" );
    path = ist.value( "AppleNavServices:ChooseObject:0:Path" ).toString();
    path = path.remove( "file://localhost" );
    qDebug() << "Found iTunes Library in:" << path;

    QFileInfo fi( path + "iTunes Music Library.xml" );
    if ( fi.exists() )
        m_iTunesLibraryPath = fi.absoluteFilePath();
    else
        m_iTunesLibraryPath = QFileInfo( QDir::homePath() + "/Music/iTunes/iTunes Music Library.xml" ).absoluteFilePath();

    return m_iTunesLibraryPath;
#endif

#ifdef WIN32
    {
        // Get path to My Music
        char acPath[MAX_PATH];
        HRESULT h = SHGetFolderPathA( NULL, CSIDL_MYMUSIC,
                                      NULL, 0, acPath );

        if ( h == S_OK )
            path = QString::fromLocal8Bit( acPath );
        else
            qWarning() << "Couldn't get My Music path";

        qDebug() << "CSIDL_MYMUSIC path: " << path;
    }

    {
        // Get path to Local App Data
        char acPath[MAX_PATH];
        HRESULT h = SHGetFolderPathA( NULL, CSIDL_LOCAL_APPDATA,
                                      NULL, 0, acPath );

        if ( h == S_OK )
            confPath = QString::fromLocal8Bit( acPath );
        else
            qWarning() << "Couldn't get Local Application Data path";

        qDebug() << "CSIDL_LOCAL_APPDATA path: " << confPath;
    }

    // Try reading iTunesPrefs.xml for custom library path
    QFile f( confPath + "/Apple Computer/iTunes/iTunesPrefs.xml" );
    if ( f.open( QIODevice::ReadOnly | QIODevice::Text ) )
    {
        qDebug() << "Found iTunesPrefs.xml";

        QByteArray content = f.readAll();

        int tagStart = content.indexOf( "iTunes Library XML Location:1" );

        if ( tagStart != -1 )
        {
            // TODO: this could fail if the XML is broken
            int dataTagStart = content.indexOf( "<data>", tagStart );
            int dataTagEnd = dataTagStart + 6;
            int dataEndTagStart = content.indexOf( "</data>", dataTagStart );
            QByteArray lp = content.mid( dataTagEnd, dataEndTagStart - dataTagEnd );

            qDebug() << "lp before trim: " << lp;

            // The file contains whitespace and linebreaks in the middle of
            // the data so need to squeeze all that out
            lp = lp.simplified();
            lp = lp.replace( ' ', "" );

            qDebug() << "lp after simplified: " << lp;

            lp = QByteArray::fromBase64( lp );

            qDebug() << "lp after base64: " << lp;

            QString sp = QString::fromUtf16( (ushort*)lp.data() );

            qDebug() << "Found iTunes Library path (after conversion to QString):" << sp;

            QFileInfo fi( sp );
            if ( fi.exists() )
            {
                qDebug() << "file exists, returning: " << fi.absoluteFilePath();
                m_iTunesLibraryPath = fi.absoluteFilePath();
                return m_iTunesLibraryPath;
            }
        }
        else
        {
            qDebug() << "No custom library location found in iTunesPrefs.xml";
        }
    }

    // Fall back to default path otherwise
    m_iTunesLibraryPath = path + "/iTunes/iTunes Music Library.xml";

    qDebug() << "Will use default iTunes Library path: " << m_iTunesLibraryPath;

    return m_iTunesLibraryPath;

#endif

    // Fallback for testing
//    m_iTunesLibraryPath = "/tmp/iTunes Music Library.xml";
//    return m_iTunesLibraryPath;
}
bool Q3Socket::flush()
{
    if ( !d->socket )
        return true;
    bool osBufferFull = false;
    int consumed = 0;
    while ( !osBufferFull && d->state >= Connecting && d->wsize > 0 ) {
#if defined(Q3SOCKET_DEBUG)
	qDebug( "Q3Socket (%s): flush: Write data to the socket", name() );
#endif
	QByteArray *a = d->wba.first();
	int nwritten;
	int i = 0;
	if ( (int)a->size() - d->windex < 1460 ) {
	    // Concatenate many smaller blocks.  the first may be
	    // partial, but each subsequent block is copied entirely
	    // or not at all.  the sizes here are picked so that we
	    // generally won't trigger nagle's algorithm in the tcp
	    // implementation: we concatenate if we'd otherwise send
	    // less than PMTU bytes (we assume PMTU is 1460 bytes),
	    // and concatenate up to the largest payload TCP/IP can
	    // carry.  with these precautions, nagle's algorithm
	    // should apply only when really appropriate.
	    QByteArray out( 65536 );
	    int j = d->windex;
	    int s = a->size() - j;
	    while ( a && i+s < (int)out.size() ) {
		memcpy( out.data()+i, a->data()+j, s );
		j = 0;
		i += s;
		a = d->wba.next();
		s = a ? a->size() : 0;
	    }
	    nwritten = d->socket->write( out.data(), i );
	    if ( d->wsn )
		d->wsn->setEnabled( false ); // the QSocketNotifier documentation says so
	} else {
	    // Big block, write it immediately
	    i = a->size() - d->windex;
	    nwritten = d->socket->write( a->data() + d->windex, i );
	    if ( d->wsn )
		d->wsn->setEnabled( false ); // the QSocketNotifier documentation says so
	}
	if ( nwritten > 0 ) {
	    if ( consumeWriteBuf( nwritten ) )
		consumed += nwritten;
	}
	if ( nwritten < i )
	    osBufferFull = true;
    }
    if ( consumed > 0 ) {
#if defined(Q3SOCKET_DEBUG)
	qDebug( "Q3Socket (%s): flush: wrote %d bytes, %d left",
		name(), consumed, (int)d->wsize );
#endif
	emit bytesWritten( consumed );
    }
    if ( d->state == Closing && d->wsize == 0 ) {
#if defined(Q3SOCKET_DEBUG)
	qDebug( "Q3Socket (%s): flush: Delayed close done. Terminating.",
		name() );
#endif
	resetStatus();
	setOpenMode(NotOpen);
	d->close();
	d->state = Idle;
	emit delayedCloseFinished();
	return true;
    }
    if ( !d->socket->isOpen() ) {
	d->connectionClosed();
	emit connectionClosed();
	return true;
    }
    if ( d->wsn )
	d->wsn->setEnabled( d->wsize > 0 ); // write if there's data
    return true;
}
void UrlGetTask::printUrl(QNetworkReply *reply)
{
    QByteArray content = reply->readAll();
    fprintf(stdout, "%s\n", content.data());
    emit finished();
}
Example #7
0
QByteArray qt_inflateGZipDataFrom(QIODevice *device)
{
    if (!device)
        return QByteArray();

    if (!device->isOpen())
        device->open(QIODevice::ReadOnly);

    Q_ASSERT(device->isOpen() && device->isReadable());

    static const int CHUNK_SIZE = 4096;
    int zlibResult = Z_OK;

    QByteArray source;
    QByteArray destination;

    // Initialize zlib stream struct
    z_stream zlibStream;
    zlibStream.next_in = Z_NULL;
    zlibStream.avail_in = 0;
    zlibStream.avail_out = 0;
    zlibStream.zalloc = Z_NULL;
    zlibStream.zfree = Z_NULL;
    zlibStream.opaque = Z_NULL;

    // Adding 16 to the window size gives us gzip decoding
    if (inflateInit2(&zlibStream, MAX_WBITS + 16) != Z_OK) {
        qWarning("Cannot initialize zlib, because: %s",
                (zlibStream.msg != NULL ? zlibStream.msg : "Unknown error"));
        return QByteArray();
    }

    bool stillMoreWorkToDo = true;
    while (stillMoreWorkToDo) {

        if (!zlibStream.avail_in) {
            source = device->read(CHUNK_SIZE);

            if (source.isEmpty())
                break;

            zlibStream.avail_in = source.size();
            zlibStream.next_in = reinterpret_cast<Bytef*>(source.data());
        }

        do {
            // Prepare the destination buffer
            int oldSize = destination.size();
            destination.resize(oldSize + CHUNK_SIZE);
            zlibStream.next_out = reinterpret_cast<Bytef*>(
                    destination.data() + oldSize - zlibStream.avail_out);
            zlibStream.avail_out += CHUNK_SIZE;

            zlibResult = inflate(&zlibStream, Z_NO_FLUSH);
            switch (zlibResult) {
                case Z_NEED_DICT:
                case Z_DATA_ERROR:
                case Z_STREAM_ERROR:
                case Z_MEM_ERROR: {
                    inflateEnd(&zlibStream);
                    qWarning("Error while inflating gzip file: %s",
                            (zlibStream.msg != NULL ? zlibStream.msg : "Unknown error"));
                    destination.chop(zlibStream.avail_out);
                    return destination;
                }
            }

        // If the output buffer still has more room after calling inflate
        // it means we have to provide more data, so exit the loop here
        } while (!zlibStream.avail_out);

        if (zlibResult == Z_STREAM_END) {
            // Make sure there are no more members to process before exiting
            if (!(zlibStream.avail_in && inflateReset(&zlibStream) == Z_OK))
                stillMoreWorkToDo = false;
        }
    }

    // Chop off trailing space in the buffer
    destination.chop(zlibStream.avail_out);

    inflateEnd(&zlibStream);
    return destination;
}
Example #8
0
QVariant LacpProtocol::fieldData(int index, FieldAttrib attrib,
                                 int streamIndex) const
{
    QString str[8]={"Activity", "Timeout", "Aggregation", "Synchronization",
                    "Collecting", "Distributing", "Defaulted", "Expired"};

    switch (index)
    {
        case lacp_subtype:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Subtype");
                case FieldValue:
                    return data.subtype();
                case FieldTextValue:
                    return QString("0x%1").arg(data.subtype(), 2, BASE_HEX,
                                               QChar('0'));
                case FieldFrameValue:
                    return QByteArray(1, (char)data.subtype());
                default:
                    break;
            }
            break;
        }
        case lacp_version_number:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Version Number");
                case FieldValue:
                    return data.version_number();
                case FieldTextValue:
                    return QString("0x%1").arg(data.version_number(), 2,
                                               BASE_HEX, QChar('0'));
                case FieldFrameValue:
                    return QByteArray(1, (char)data.version_number());
                default:
                    break;
            }
            break;
        }
//--------------------------------Actor-----------------------------------------
        case lacp_tlv_type_actor:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor Information");
                case FieldValue:
                    return data.tlv_type_actor();
                case FieldTextValue:
                    return QString("%1").arg(data.tlv_type_actor());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.tlv_type_actor());
                default:
                    break;
            }
            break;
        }
        case lacp_actor_length:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor Information Length");
                case FieldValue:
                    return data.actor_info_length();
                case FieldTextValue:
                    return QString("%1").arg(data.actor_info_length());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.actor_info_length());
                default:
                    break;
            }
            break;
        }
        case lacp_actor_system_priority:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor System Priority");
                case FieldValue:
                    return data.actor_system_priority();
                case FieldTextValue:
                    return QString("%1").arg(data.actor_system_priority());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.actor_system_priority(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_actor_system:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor System");
                case FieldValue:
                    return (quint64)data.actor_system();
                case FieldTextValue:
                    return uintToMacStr(data.actor_system());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    // 8 bytes because data.actor_system is UInt64
                    fv.resize(BYTES(8));
                    qToBigEndian(data.actor_system() , (uchar*)fv.data());
                    // remove first two bytes because actor system have 6 byte
                    // (IEEE802.1AX-2008)
                    fv.remove(0, 2);
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_actor_key:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor Key");
                case FieldValue:
                    return data.actor_key();
                case FieldTextValue:
                    return QString("%1").arg(data.actor_key());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.actor_key(), (uchar*) fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_actor_port_priority:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor Port Priority");
                case FieldValue:
                    return data.actor_port_priority();
                case FieldTextValue:
                    return QString("%1").arg(data.actor_port_priority());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.actor_port_priority(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_actor_port:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor Port");
                case FieldValue:
                    return data.actor_port();
                case FieldTextValue:
                    return QString("%1").arg(data.actor_port());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.actor_port(), (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_actor_state:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Actor State");
                case FieldValue:
                    return data.actor_state();
                case FieldTextValue:
                {
                    QString str_temp = "(";
                    if ((data.actor_state() & ONE_BIT(0)))
                        str_temp += str[0] + ", ";
                    if ((data.actor_state() & ONE_BIT(1)))
                        str_temp += str[1] + ", ";
                    if ((data.actor_state() & ONE_BIT(2)))
                        str_temp += str[2] + ", ";
                    if ((data.actor_state() & ONE_BIT(3)))
                        str_temp += str[3] + ", ";
                    if ((data.actor_state() & ONE_BIT(4)))
                        str_temp += str[4] + ", ";
                    if ((data.actor_state() & ONE_BIT(5)))
                        str_temp += str[5] + ", ";
                    if ((data.actor_state() & ONE_BIT(6)))
                        str_temp += str[6] + ", ";
                    if ((data.actor_state() & ONE_BIT(7)))
                        str_temp += str[7] + ", ";
                    str_temp += ")";
                    str_temp.replace(", )", ")");
                    return str_temp;
                }
                case FieldFrameValue:
                    return QByteArray(1, (char)data.actor_state());
                default:
                    break;
            }
            break;
        }
        case lacp_actor_reserved:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Reserved");
                case FieldValue:
                    return QString("%1").arg(data.actor_reserved(), 6,
                                             BASE_HEX, QChar('0'));
                case FieldTextValue:
                    return QString("0x%1").arg(data.actor_reserved(), 6,
                                               BASE_HEX, QChar('0'));
                case FieldFrameValue:
                {
                    QByteArray fv;
                    // must have 4 bytes because data.actor_reserved is int32
                    fv.resize(BYTES(4));
                    qToBigEndian(data.actor_reserved(), (uchar*)fv.data());
                     // remove first byte, because field actor reserved
                     // have 3 byte (IEEE802.1AX-2008)
                    fv.remove(0, 1);
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
//--------------------------------Partner---------------------------------------
        case lacp_tlv_type_partner:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner Information");
                case FieldValue:
                    return data.tlv_type_partner();
                case FieldTextValue:
                    return QString("%1").arg(data.tlv_type_partner());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.tlv_type_partner());
                default:
                    break;
            }
            break;
        }
        case lacp_partner_length:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner Information Length");
                case FieldValue:
                    return data.partner_info_length();
                case FieldTextValue:
                    return QString("%1").arg(data.partner_info_length());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.partner_info_length());
                default:
                    break;
            }
            break;
        }
        case lacp_partner_system_priority:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner System Priority");
                case FieldValue:
                    return data.partner_system_priority();
                case FieldTextValue:
                    return QString("%1").arg(data.partner_system_priority());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.partner_system_priority(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_partner_system:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner System");
                case FieldValue:
                    return (quint64)data.partner_system();
                case FieldTextValue:
                    return uintToMacStr(data.partner_system());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    // must have 8 bytes because data.partner_system is UInt64
                    fv.resize(BYTES(8));
                    qToBigEndian(data.partner_system() , (uchar*)fv.data());
                     // remove first byte, because field partner system
                     // have 6 byte (IEEE802.1AX-2008)
                    fv.remove(0, 2);
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_partner_key:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner Key");
                case FieldValue:
                    return (quint64)data.partner_key();
                case FieldTextValue:
                    return QString("%1").arg(data.partner_key());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.partner_key(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_partner_port_priority:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner Port Priority");
                case FieldValue:
                    return data.partner_port_priority();
                case FieldTextValue:
                    return QString("%1").arg(data.partner_port_priority());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.partner_port_priority(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_partner_port:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner Port");
                case FieldValue:
                    return data.partner_port();
                case FieldTextValue:
                    return QString("%1").arg(data.partner_port());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.partner_port(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_partner_state:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Partner State");
                case FieldValue:
                    return data.partner_state();
                case FieldTextValue:
                {
                    QString str_temp="(";
                    if ((data.partner_state() & ONE_BIT(0)))
                        str_temp += str[0] + ", ";
                    if ((data.partner_state() & ONE_BIT(1)))
                        str_temp += str[1] + ", ";
                    if ((data.partner_state() & ONE_BIT(2)))
                        str_temp += str[2] + ", ";
                    if ((data.partner_state() & ONE_BIT(3)))
                        str_temp += str[3] + ", ";
                    if ((data.partner_state() & ONE_BIT(4)))
                        str_temp += str[4] + ", ";
                    if ((data.partner_state() & ONE_BIT(5)))
                        str_temp += str[5] + ", ";
                    if ((data.partner_state() & ONE_BIT(6)))
                        str_temp += str[6] + ", ";
                    if ((data.partner_state() & ONE_BIT(7)))
                        str_temp += str[7] + ", ";
                    str_temp+=")";
                    str_temp.replace(", )", ")");
                    return str_temp;
                }
                case FieldFrameValue:
                    return QByteArray(1, (char)data.partner_state());
                default:
                    break;
            }
            break;
        }
        case lacp_partner_reserved:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Reserved");
                case FieldValue:
                    return data.partner_reserved();
                case FieldTextValue:
                    return QString("0x%1").arg(data.partner_reserved(), 6,
                                               BASE_HEX, QChar('0'));
               case FieldFrameValue:
                {
                    QByteArray fv;
                    // must have 4 bytes because data.partner_reserved is UInt32
                    fv.resize(4);
                    qToBigEndian(data.partner_reserved(), (uchar*)fv.data());
                    // remove first byte, because field partner reserved
                    // have 3 byte (IEEE802.1AX-2008)
                    fv.remove(0, 1);
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
//--------------------------------------------Collector-------------------------
        case lacp_tlv_type_collector:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Collector Information");
                case FieldValue:
                    return data.tlv_type_collector();
                case FieldTextValue:
                    return QString("%1").arg(data.tlv_type_collector());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.tlv_type_collector());
                default:
                    break;
            }
            break;
        }
        case lacp_collector_length:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Collector Information Length");
                case FieldValue:
                    return data.collector_info_length();
                case FieldTextValue:
                    return QString("%1").arg(data.collector_info_length());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.collector_info_length());
                default:
                    break;
            }
            break;
        }
        case lacp_collector_maxDelay:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Collector Max Delay");
                case FieldValue:
                    return data.collector_maxdelay();
                case FieldTextValue:
                    return QString("%1").
                        arg(data.collector_maxdelay());
                case FieldFrameValue:
                {
                    QByteArray fv;
                    fv.resize(BYTES(2));
                    qToBigEndian((quint16)data.collector_maxdelay(),
                                 (uchar*)fv.data());
                    return fv;
                }
                default:
                    break;
            }
            break;
        }
        case lacp_collector_reserved:
        {
            QByteArray ba;
            bool isOk = false;
            QString reserved;
            reserved.append(QString().fromStdString(data.collector_reserved()));
            //insert 0 to left side of string
            reserved.insert(0, QString().fill(QChar().fromAscii('0'),
                                              BYTES(12) * 2 - reserved.size()));
             // create Byte Array from string with HEX
            for (int i = 0; i < reserved.size(); i += 2)
                ba.append(((QString)reserved[i] +
                           (QString)reserved[i + 1]).toUInt(&isOk, BASE_HEX));
            switch (attrib)
            {
                case FieldName:
                    return QString("Reserved");
                case FieldValue:
                    return ba;
                case FieldTextValue:
                    return QString("0x%1").arg(reserved).toLower();
                case FieldFrameValue:
                    return ba;
                default:
                    break;
            }
            break;
        }
//--------------------------------------------terminator------------------------
        case lacp_tlv_type_terminator:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Terminator Information");
                case FieldValue:
                    return data.tlv_type_terminator();
                case FieldTextValue:
                    return QString("%1").arg(data.tlv_type_terminator());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.tlv_type_terminator());
                default:
                    break;
            }
            break;
        }
        case lacp_terminator_length:
        {
            switch (attrib)
            {
                case FieldName:
                    return QString("Terminator Length");
                case FieldValue:
                    return data.terminator_length();
                case FieldTextValue:
                    return QString("%1").arg(data.terminator_length());
                case FieldFrameValue:
                    return QByteArray(1, (char)data.terminator_length());
                default:
                    break;
            }
            break;
        }
        case lacp_terminator_reserved:
            {
            QByteArray ba;
            bool isOk = false;
            QString reserved;
            reserved.append(
                        QString().fromStdString(data.terminator_reserved()));
            //insert 0 to left side of string
            reserved.insert(0, QString().fill(QChar().fromAscii('0'),
                                              BYTES(50) * 2 - reserved.size()));
            // create Byte Array from string with HEX
            for (int i = 0; i < reserved.size(); i += 2)
                ba.append(((QString)reserved[i] +
                           (QString)reserved[i + 1]).toUInt(&isOk, BASE_HEX));
            switch (attrib)
            {
                case FieldName:
                    return QString("Reserved");
                case FieldValue:
                    return ba;
                case FieldTextValue:
                    return QString("0x%1").arg(reserved).toLower();
                case FieldFrameValue:
                    return ba;
                default:
                    break;
            }
            break;
        }
//------------------meta fields-------------------------------------------------
        case is_override_subtype:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_subtype();
                default:
                    break;
            }
        }
        case is_override_version:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_version_number();
                default:
                    break;
            }
        }
        case is_override_tlv_actor :
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_tlv_type_actor();
                default:
                    break;
            }
        }
        case is_override_actor_info:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_actor_info_length();
                default:
                    break;
            }
        }
        case is_override_actor_reserved:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_actor_reserved();
                default:
                    break;
            }
        }
        case is_override_tlv_partner:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_tlv_type_partner();
                default:
                    break;
            }
        }
        case is_override_partner_info:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_partner_info_length();
                default:
                    break;
            }
        }
        case is_override_partner_reserved:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_partner_reserved();
                default:
                    break;
            }
        }
        case is_override_tlv_collector:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_tlv_type_collector();
                default:
                    break;
            }
        }
        case is_override_collector_info:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_collector_info_length();
                default:
                    break;
            }
        }
        case is_override_collector_reserved:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_collector_reserved();
                default:
                    break;
            }
        }
        case is_override_tlv_terminator:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_tlv_type_terminator();
                default:
                    break;
            }
        }
        case is_override_terminator_info:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_terminator_length();
                default:
                    break;
            }
        }
        case is_override_terminator_reserved:
        {
            switch (attrib)
            {
                case FieldValue:
                    return data.is_override_terminator_reserved();
                default:
                    break;
            }
        }
        break;
        default:
            qFatal("%s: unimplemented case %d in switch", __PRETTY_FUNCTION__,
                   index);
            break;
    }
    return AbstractProtocol::fieldData(index, attrib, streamIndex);
}
void CFileHasher::run()
{
	QTime tTime;
	QByteArray baBuffer;

	const int nBufferSize = 64 * 1024;

	m_pSection.lock();

	while(!m_lQueue.isEmpty())
	{
		CSharedFilePtr pFile = m_lQueue.dequeue();
		systemLog.postLog(LogSeverity::Debug, QString("Hashing %1").arg(pFile->m_sFileName));
		//qDebug() << "Hashing" << pFile->m_sFileName;
		tTime.start();
		m_pSection.unlock();

		bool bHashed = true;

		QFile f;
		f.setFileName(pFile->m_sDirectory + QString("/") + pFile->m_sFileName);

		if(f.exists() && f.open(QFile::ReadOnly))
		{
			baBuffer.resize(nBufferSize);

			pFile->m_lHashes.append(new CHash(CHash::SHA1));

			while(!f.atEnd())
			{
				if(!m_bActive)
				{
					systemLog.postLog(LogSeverity::Debug, QString("CFileHasher aborting..."));
					//qDebug() << "CFileHasher aborting...";
					bHashed = false;
					break;
				}
				qint64 nRead = f.read(baBuffer.data(), nBufferSize);

				if(nRead < 0)
				{
					bHashed = false;
					systemLog.postLog(LogSeverity::Debug, QString("File read error: %1").arg(f.error()));
					//qDebug() << "File read error:" << f.error();
					break;
				}
				else if(nRead < nBufferSize)
				{
					baBuffer.resize(nRead);
				}

				for(int i = 0; i < pFile->m_lHashes.size(); i++)
				{
					pFile->m_lHashes[i]->AddData(baBuffer);
				}

			}

			f.close();
		}
		else
		{
			systemLog.postLog(LogSeverity::Debug, QString("File open error: %1").arg(f.error()));
			//qDebug() << "File open error: " << f.error();
			bHashed = false;
		}

		if(bHashed)
		{
			double nRate = (f.size() / (tTime.elapsed() / 1000.0)) / 1024.0 / 1024.0;
			systemLog.postLog(LogSeverity::Debug, QString("File %1 hashed at %2 MB/s").arg(pFile->m_sFileName).arg(nRate));
			//qDebug() << "File " << pFile->m_sFileName << "hashed at" << nRate << "MB/s:";
			for(int i = 0; i < pFile->m_lHashes.size(); i++)
			{
				pFile->m_lHashes[i]->Finalize();
				systemLog.postLog(LogSeverity::Debug, QString("%1").arg(pFile->m_lHashes[i]->ToURN()));
				//qDebug() << pFile->m_lHashes[i]->ToURN();
			}
			emit FileHashed(pFile);
		}

		m_pSection.lock();

		if(!m_bActive)
		{
			break;
		}

		if(bHashed && m_lQueue.isEmpty())
		{
			emit QueueEmpty();
			systemLog.postLog(LogSeverity::Debug, QString("Hasher waiting..."));
			//qDebug() << "Hasher " << this << "waiting...";
			CFileHasher::m_oWaitCond.wait(&m_pSection, 10000);
		}
	}

	for(uint i = 0; i < m_nMaxHashers; i++)
	{
		if(m_pHashers[i] == this)
		{
			m_pHashers[i] = 0;
			deleteLater();
			m_nRunningHashers--;

			if(m_nRunningHashers == 0)
			{
				delete [] m_pHashers;
				m_pHashers = 0;
			}
			break;
		}
	}

	m_pSection.unlock();

	systemLog.postLog(LogSeverity::Debug, QString("CFileHasher done. %1").arg(m_nRunningHashers));
	//qDebug() << "CFileHasher done. " << m_nRunningHashers;
}
bool PrinterUtil::initDeviceSettings(QString printerName, QByteArray& devModeA)
{
	bool done;
	uint size;
	LONG result = IDOK+1;
	Qt::HANDLE handle = NULL;
	// Get the printer handle
	done = OpenPrinterW((LPWSTR) printerName.utf16(), &handle, NULL);
	if (!done)
		return false;
	// Get size of DEVMODE structure (public + private data)
	size = DocumentPropertiesW((HWND) ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), NULL, NULL, 0);
	// Compare size with DevMode structure size
	if (devModeA.size() == size)
	{
		// Merge printer settings
		result = DocumentPropertiesW((HWND) ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), (DEVMODEW*) devModeA.data(), (DEVMODEW*) devModeA.data(), DM_IN_BUFFER | DM_OUT_BUFFER);
	}
	else
	{
		// Retrieve default settings
		devModeA.resize(size);
		result = DocumentPropertiesW((HWND) ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), (DEVMODEW*) devModeA.data(), NULL, DM_OUT_BUFFER);
	}
	done = (result == IDOK);
	// Free the printer handle
	ClosePrinter(handle);
	return done;
}
bool
FormatManager::readSubtitle(Subtitle &subtitle, bool primary, const QUrl &url, QTextCodec **codec, Format::NewLine *newLine, QString *formatName) const
{
//  if ( *codec )
//      qDebug() << "loading" << url << "script" << autodetectScript << "codec" << (*codec)->name();
//  else
//      qDebug() << "loading" << url << "script" << autodetectScript;

	FileLoadHelper fileLoadHelper(url);
	if(!fileLoadHelper.open())
		return false;
	QByteArray byteData = fileLoadHelper.file()->readAll();
	fileLoadHelper.close();

	QString stringData;

#ifdef HAVE_ICU
	if(!*codec) {
		UErrorCode status = U_ZERO_ERROR;
		UCharsetDetector *csd = ucsdet_open(&status);
		ucsdet_setText(csd, byteData.data(), byteData.length(), &status);
		int32_t matchesFound = 0;
		const UCharsetMatch **ucms = ucsdet_detectAll(csd, &matchesFound, &status);
		for(int index = 0; index < matchesFound; ++index) {
			int32_t confidence = ucsdet_getConfidence(ucms[index], &status);
			const char *name = ucsdet_getName(ucms[index], &status);
			qDebug() << "encoding" << name << "confidence" << confidence;
			bool encodingFound;
			*codec = KCharsets::charsets()->codecForName(name, encodingFound);
			if(encodingFound)
				break;
			else
				*codec = 0;
		}
		ucsdet_close(csd);
	}
#endif
	if(!*codec) {
		KEncodingProber prober(KEncodingProber::Universal);
		prober.feed(byteData);
		bool encodingFound;
		*codec = KCharsets::charsets()->codecForName(prober.encoding(), encodingFound);
	}
	if(*codec) {
		QTextStream textStream(byteData);
		textStream.setCodec(*codec);
		stringData = textStream.readAll();
	}

	if(newLine) {
		if(stringData.indexOf(QLatin1String("\r\n")) != -1)
			*newLine = Format::Windows;
		else if(stringData.indexOf('\r') != -1)
			*newLine = Format::Macintosh;
		else if(stringData.indexOf('\n') != -1)
			*newLine = Format::UNIX;
		else
			*newLine = Format::CurrentOS;
	}

	stringData.replace(QLatin1String("\r\n"), QLatin1String("\n"));
	stringData.replace('\r', '\n');

	const QString extension = QFileInfo(url.path()).suffix();

	// attempt to parse subtitles based on extension information first
	for(QMap<QString, InputFormat *>::ConstIterator it = m_inputFormats.begin(), end = m_inputFormats.end(); it != end; ++it) {
		if(it.value()->knowsExtension(extension)) {
			if(it.value()->readSubtitle(subtitle, primary, stringData)) {
				if(formatName)
					*formatName = it.value()->name();
				return true;
			}
		}
	}

	// that didn't worked, attempt to parse subtitles based on content
	for(QMap<QString, InputFormat *>::ConstIterator it = m_inputFormats.begin(), end = m_inputFormats.end(); it != end; ++it) {
		if(!it.value()->knowsExtension(extension)) {
			if(it.value()->readSubtitle(subtitle, primary, stringData)) {
				if(formatName)
					*formatName = it.value()->name();
				return true;
			}
		}
	}

	return false;
}
bool PrinterUtil::getDefaultSettings(QString printerName, QByteArray& devModeA)
{
	bool done;
	uint size;
	LONG result = IDOK+1;
	Qt::HANDLE handle = NULL;
	// Get the printer handle
	done = OpenPrinterW((LPWSTR) printerName.utf16(), &handle, NULL);
	if (!done)
		return false;
	// Get size of DEVMODE structure (public + private data)
	size = DocumentPropertiesW((HWND) ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), NULL, NULL, 0);
	// Allocate the memory needed by the DEVMODE structure
	devModeA.resize(size);
	// Retrieve printer default settings
	result = DocumentPropertiesW((HWND) ScCore->primaryMainWindow()->winId(), handle, (LPWSTR) printerName.utf16(), (DEVMODEW*) devModeA.data(), NULL, DM_OUT_BUFFER);
	// Free the printer handle
	ClosePrinter(handle);
	return (result == IDOK);
}
Example #13
0
int main(int argc, char *argv[])
{
    TWebApplication webapp(argc, argv);

    // Setup loggers
    tSetupSystemLogger();
    tSetupLoggers();
    qInstallMsgHandler(messageOutput);

#if defined(Q_OS_UNIX)
    webapp.watchUnixSignal(SIGTERM);
    webapp.ignoreUnixSignal(SIGINT);

    // Setup signal handlers for SIGSEGV, SIGILL, SIGFPE, SIGABRT and SIGBUS
    setupFailureWriter(writeFailure);
    setupSignalHandler();
#endif

    // Sets codec
    QTextCodec *codec = QTextCodec::codecForName("UTF-8");  // default value
    QByteArray codecName = webapp.treefrogSettings().value("InternalEncoding").toByteArray().trimmed();
    if (!codecName.isEmpty()) {
        QTextCodec *c = QTextCodec::codecForName(codecName);
        if (c) {
            codec = c;
        } else {
            tWarn("no codec matching the name could be found: %s", codecName.data());
        }
    }
    QTextCodec::setCodecForTr(codec);
    QTextCodec::setCodecForLocale(codec);
    tSystemDebug("setCodecForTr: %s", codec->name().data());

    if (!webapp.webRootExists()) {
        tSystemError("No such directory");
        return 1;
    }
    tSystemDebug("Web Root: %s", qPrintable(webapp.webRootPath()));

    if (!webapp.settingsFileExists()) {
        tSystemError("Settings file not found");
        return 2;
    }
  
    QHash<QString, QString> args = convertArgs(QCoreApplication::arguments());
    TApplicationServer *server = new TApplicationServer(&webapp);
    QString arg = args.value("-s");
    if (!arg.isEmpty()) {
        // Sets a listening socket descriptor
        int sd = arg.toInt();
        if (sd > 0) {
            if (server->setSocketDescriptor(sd)) {
                tSystemDebug("Set socket descriptor: %d", sd);
            } else {
                tSystemError("Failed to set socket descriptor: %d", sd);
                return 3;
            }
        } else {
            tSystemError("Invalid socket descriptor: %d", sd);
            return 4;
        }
    }
    
    server->open();
    return webapp.exec();
}
Example #14
0
int DNGWriter::convert()
{
    d->cancel = false;

    try
    {
        if (inputFile().isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: No input file to convert. Aborted..." << endl;
            return -1;
        }

        QFileInfo inputInfo(inputFile());
        QString   dngFilePath = outputFile();

        if (dngFilePath.isEmpty())
        {
            dngFilePath = QString(inputInfo.baseName() + QString(".dng"));
        }

        QFileInfo          outputInfo(dngFilePath);
        QByteArray         rawData;
        DcrawInfoContainer identify;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Loading RAW data from " << inputInfo.fileName() << endl;

        KDcraw rawProcessor;
        if (!rawProcessor.extractRAWData(inputFile(), rawData, identify))
        {
            kDebug( 51000 ) << "DNGWriter: Loading RAW data failed. Aborted..." << endl;
            return -1;
        }

        if (d->cancel) return -2;

        int width      = identify.imageSize.width();
        int height     = identify.imageSize.height();
        int pixelRange = 16;

        kDebug( 51000 ) << "DNGWriter: Raw data loaded:" << endl;
        kDebug( 51000 ) << "--- Data Size:     " << rawData.size() << " bytes" << endl;
        kDebug( 51000 ) << "--- Date:          " << identify.dateTime.toString(Qt::ISODate) << endl;
        kDebug( 51000 ) << "--- Make:          " << identify.make << endl;
        kDebug( 51000 ) << "--- Model:         " << identify.model << endl;
        kDebug( 51000 ) << "--- Size:          " << width << "x" << height << endl;
        kDebug( 51000 ) << "--- Orientation:   " << identify.orientation << endl;
        kDebug( 51000 ) << "--- Top margin:    " << identify.topMargin << endl;
        kDebug( 51000 ) << "--- Left margin:   " << identify.leftMargin << endl;
        kDebug( 51000 ) << "--- Filter:        " << identify.filterPattern << endl;
        kDebug( 51000 ) << "--- Colors:        " << identify.rawColors << endl;
        kDebug( 51000 ) << "--- Black:         " << identify.blackPoint << endl;
        kDebug( 51000 ) << "--- White:         " << identify.whitePoint << endl;
        kDebug( 51000 ) << "--- CAM->XYZ:" << endl;

        QString matrixVal;
        for(int i=0; i<12; i+=3)
        {
            kDebug( 51000 ) << "                   "
                     << QString().sprintf("%03.4f  %03.4f  %03.4f", identify.cameraXYZMatrix[0][ i ],
                                                                    identify.cameraXYZMatrix[0][i+1],
                                                                    identify.cameraXYZMatrix[0][i+2])
                     << endl;
        }

        // Check if CFA layout is supported by DNG SDK.
        int bayerMosaic;

        if (identify.filterPattern == QString("GRBGGRBGGRBGGRBG"))
        {
            bayerMosaic = 0;
        }
        else if (identify.filterPattern == QString("RGGBRGGBRGGBRGGB"))
        {
            bayerMosaic = 1;
        }
        else if (identify.filterPattern == QString("BGGRBGGRBGGRBGGR"))
        {
            bayerMosaic = 2;
        }
        else if (identify.filterPattern == QString("GBRGGBRGGBRGGBRG"))
        {
            bayerMosaic = 3;
        }
        else
        {
            kDebug( 51000 ) << "DNGWriter: Bayer mosaic not supported. Aborted..." << endl;
            return -1;
        }

        // Check if number of Raw Color components is supported.
        if (identify.rawColors != 3)
        {
            kDebug( 51000 ) << "DNGWriter: Number of Raw color components not supported. Aborted..." << endl;
            return -1;
        }

/*      // NOTE: code to hack RAW data extraction

        QString   rawdataFilePath(inputInfo.baseName() + QString(".dat"));
        QFileInfo rawdataInfo(rawdataFilePath);

        QFile rawdataFile(rawdataFilePath);
        if (!rawdataFile.open(QIODevice::WriteOnly))
        {
            kDebug( 51000 ) << "DNGWriter: Cannot open file to write RAW data. Aborted..." << endl;
            return -1;
        }
        QDataStream rawdataStream(&rawdataFile);
        rawdataStream.writeRawData(rawData.data(), rawData.size());
        rawdataFile.close();
*/
        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Formating RAW data to memory" << endl;

        std::vector<unsigned short> raw_data;
        raw_data.resize(rawData.size());
        const unsigned short* dp = (const unsigned short*)rawData.data();
        for (uint i = 0; i < raw_data.size()/2; i++)
        {
            raw_data[i] = *dp;
            *dp++;
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG memory allocation and initialization" << endl;

        dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
        dng_memory_stream stream(memalloc);
        stream.Put(&raw_data.front(), raw_data.size()*sizeof(unsigned short));

        dng_rect rect(height, width);
        DNGWriterHost host(d, &memalloc);

        // Unprocessed raw data.
        host.SetKeepStage1(true);

        // Linearized, tone curve processed data.
        host.SetKeepStage2(true);

        AutoPtr<dng_image> image(new dng_simple_image(rect, 1, ttShort, 1<<pixelRange, memalloc));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG IFD structure creation" << endl;

        dng_ifd ifd;

        ifd.fUsesNewSubFileType        = true;
        ifd.fNewSubFileType            = 0;
        ifd.fImageWidth                = width;
        ifd.fImageLength               = height;
        ifd.fBitsPerSample[0]          = pixelRange;
        ifd.fBitsPerSample[1]          = 0;
        ifd.fBitsPerSample[2]          = 0;
        ifd.fBitsPerSample[3]          = 0;
        ifd.fCompression               = ccUncompressed;
        ifd.fPredictor                 = 1;
        ifd.fCFALayout                 = 1;                 // Rectangular (or square) layout.
        ifd.fPhotometricInterpretation = piCFA;
        ifd.fFillOrder                 = 1;
        ifd.fOrientation               = identify.orientation;
        ifd.fSamplesPerPixel           = 1;
        ifd.fPlanarConfiguration       = 1;
        ifd.fXResolution               = 0.0;
        ifd.fYResolution               = 0.0;
        ifd.fResolutionUnit            = 0;

        ifd.fUsesStrips                = true;
        ifd.fUsesTiles                 = false;

        ifd.fTileWidth                 = width;
        ifd.fTileLength                = height;
        ifd.fTileOffsetsType           = 4;
        ifd.fTileOffsetsCount          = 0;

        ifd.fSubIFDsCount              = 0;
        ifd.fSubIFDsOffset             = 0;
        ifd.fExtraSamplesCount         = 0;
        ifd.fSampleFormat[0]           = 1;
        ifd.fSampleFormat[1]           = 1;
        ifd.fSampleFormat[2]           = 1;
        ifd.fSampleFormat[3]           = 1;

        ifd.fLinearizationTableType    = 0;
        ifd.fLinearizationTableCount   = 0;
        ifd.fLinearizationTableOffset  = 0;

        ifd.fBlackLevelRepeatRows      = 1;
        ifd.fBlackLevelRepeatCols      = 1;
        ifd.fBlackLevel[0][0][0]       = identify.blackPoint;
        ifd.fBlackLevelDeltaHType      = 0;
        ifd.fBlackLevelDeltaHCount     = 0;
        ifd.fBlackLevelDeltaHOffset    = 0;
        ifd.fBlackLevelDeltaVType      = 0;
        ifd.fBlackLevelDeltaVCount     = 0;
        ifd.fBlackLevelDeltaVOffset    = 0;
        ifd.fWhiteLevel[0]             = identify.whitePoint;
        ifd.fWhiteLevel[1]             = identify.whitePoint;
        ifd.fWhiteLevel[2]             = identify.whitePoint;
        ifd.fWhiteLevel[3]             = identify.whitePoint;

        ifd.fDefaultScaleH             = dng_urational(1, 1);
        ifd.fDefaultScaleV             = dng_urational(1, 1);
        ifd.fBestQualityScale          = dng_urational(1, 1);

        ifd.fCFARepeatPatternRows      = 0;
        ifd.fCFARepeatPatternCols      = 0;

        ifd.fBayerGreenSplit           = 0;
        ifd.fChromaBlurRadius          = dng_urational(0, 0);
        ifd.fAntiAliasStrength         = dng_urational(100, 100);

        ifd.fActiveArea                = rect;
        ifd.fDefaultCropOriginH        = dng_urational(0, 1);
        ifd.fDefaultCropOriginV        = dng_urational(0, 1);
        ifd.fDefaultCropSizeH          = dng_urational(width, 1);
        ifd.fDefaultCropSizeV          = dng_urational(height, 1);

        ifd.fMaskedAreaCount           = 0;
        ifd.fLosslessJPEGBug16         = false;
        ifd.fSampleBitShift            = 0;

        ifd.ReadImage(host, stream, *image.Get());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG Negative structure creation" << endl;

        AutoPtr<dng_negative> negative(host.Make_dng_negative());

        negative->SetDefaultScale(ifd.fDefaultScaleH, ifd.fDefaultScaleV);
        negative->SetDefaultCropOrigin(ifd.fDefaultCropOriginH, ifd.fDefaultCropOriginV);
        negative->SetDefaultCropSize(ifd.fDefaultCropSizeH, ifd.fDefaultCropSizeV);
        negative->SetActiveArea(ifd.fActiveArea);

        negative->SetModelName(identify.model.toAscii());
        negative->SetLocalName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());
        negative->SetOriginalRawFileName(inputInfo.fileName().toAscii());

        negative->SetColorChannels(3);
        negative->SetColorKeys(colorKeyRed, colorKeyGreen, colorKeyBlue);
        negative->SetBayerMosaic(bayerMosaic);

        negative->SetWhiteLevel(identify.whitePoint, 0);
        negative->SetWhiteLevel(identify.whitePoint, 1);
        negative->SetWhiteLevel(identify.whitePoint, 2);
        negative->SetBlackLevel(identify.blackPoint, 0);
        negative->SetBlackLevel(identify.blackPoint, 1);
        negative->SetBlackLevel(identify.blackPoint, 2);

        negative->SetBaselineExposure(0.0);
        negative->SetBaselineNoise(1.0);
        negative->SetBaselineSharpness(1.0);

        dng_orientation orientation;
        switch (identify.orientation)
        {
            case DcrawInfoContainer::ORIENTATION_180:
                orientation = dng_orientation::Rotate180();
                break;

            case DcrawInfoContainer::ORIENTATION_90CCW:
                orientation = dng_orientation::Rotate90CCW();
                break;

            case DcrawInfoContainer::ORIENTATION_90CW:
                orientation = dng_orientation::Rotate90CW();
                break;

            default:   // ORIENTATION_NONE
                orientation = dng_orientation::Normal();
                break;
        }
        negative->SetBaseOrientation(orientation);

        negative->SetAntiAliasStrength(dng_urational(100, 100));
        negative->SetLinearResponseLimit(1.0);
        negative->SetShadowScale( dng_urational(1, 1) );

        negative->SetAnalogBalance(dng_vector_3(1.0, 1.0, 1.0));

        // -------------------------------------------------------------------------------

        // Set Camera->XYZ Color matrix as profile.
        dng_matrix_3by3 matrix(1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0);
        dng_matrix_3by3 camXYZ;

        AutoPtr<dng_camera_profile> prof(new dng_camera_profile);
        prof->SetName(QString("%1 %2").arg(identify.make).arg(identify.model).toAscii());

        camXYZ[0][0] = identify.cameraXYZMatrix[0][0];
        camXYZ[0][1] = identify.cameraXYZMatrix[0][1];
        camXYZ[0][2] = identify.cameraXYZMatrix[0][2];
        camXYZ[1][0] = identify.cameraXYZMatrix[0][3];
        camXYZ[1][1] = identify.cameraXYZMatrix[1][0];
        camXYZ[1][2] = identify.cameraXYZMatrix[1][1];
        camXYZ[2][0] = identify.cameraXYZMatrix[1][2];
        camXYZ[2][1] = identify.cameraXYZMatrix[1][3];
        camXYZ[2][2] = identify.cameraXYZMatrix[2][0];

        if (camXYZ.MaxEntry() == 0.0)
            kDebug( 51000 ) << "DNGWriter: Warning, camera XYZ Matrix is null" << endl;
        else 
            matrix = camXYZ;

        prof->SetColorMatrix1((dng_matrix) matrix);
        prof->SetCalibrationIlluminant1(lsD65);
        negative->AddProfile(prof);

        // -------------------------------------------------------------------------------

        // Clear "Camera WhiteXY"
        negative->SetCameraWhiteXY(dng_xy_coord());

        // This settings break color on preview and thumbnail
        //negative->SetCameraNeutral(dng_vector_3(1.0, 1.0, 1.0));

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Updating metadata to DNG Negative" << endl;

        dng_exif *exif = negative->GetExif();
        exif->fModel.Set_ASCII(identify.model.toAscii());
        exif->fMake.Set_ASCII(identify.make.toAscii());

        // Time from original shot
        dng_date_time dt;
        dt.fYear   = identify.dateTime.date().year();
        dt.fMonth  = identify.dateTime.date().month();
        dt.fDay    = identify.dateTime.date().day();
        dt.fHour   = identify.dateTime.time().hour();
        dt.fMinute = identify.dateTime.time().minute();
        dt.fSecond = identify.dateTime.time().second();

        dng_date_time_info dti;
        dti.SetDateTime(dt);
        exif->fDateTimeOriginal  = dti;
        exif->fDateTimeDigitized = dti;
        negative->UpdateDateTime(dti);

        long int num, den;
        long     val;
        QString  str;
        KExiv2   meta;
        if (meta.load(inputFile()))
        {
            // String Tags

            str = meta.getExifTagString("Exif.Image.Software");
            if (!str.isEmpty()) exif->fSoftware.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.ImageDescription");
            if (!str.isEmpty()) exif->fImageDescription.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Artist");
            if (!str.isEmpty()) exif->fArtist.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.Copyright");
            if (!str.isEmpty()) exif->fCopyright.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Photo.UserComment");
            if (!str.isEmpty()) exif->fUserComment.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.Image.CameraSerialNumber");
            if (!str.isEmpty()) exif->fCameraSerialNumber.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLatitudeRef");
            if (!str.isEmpty()) exif->fGPSLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSLongitudeRef");
            if (!str.isEmpty()) exif->fGPSLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSatellites");
            if (!str.isEmpty()) exif->fGPSSatellites.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSStatus");
            if (!str.isEmpty()) exif->fGPSStatus.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMeasureMode");
            if (!str.isEmpty()) exif->fGPSMeasureMode.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSTrackRef");
            if (!str.isEmpty()) exif->fGPSTrackRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSSpeedRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSImgDirectionRef");
            if (!str.isEmpty()) exif->fGPSSpeedRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSMapDatum");
            if (!str.isEmpty()) exif->fGPSMapDatum.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLatitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLatitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestLongitudeRef");
            if (!str.isEmpty()) exif->fGPSDestLongitudeRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestBearingRef");
            if (!str.isEmpty()) exif->fGPSDestBearingRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDestDistanceRef");
            if (!str.isEmpty()) exif->fGPSDestDistanceRef.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSProcessingMethod");
            if (!str.isEmpty()) exif->fGPSProcessingMethod.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSAreaInformation");
            if (!str.isEmpty()) exif->fGPSAreaInformation.Set_ASCII(str.toAscii());

            str = meta.getExifTagString("Exif.GPSInfo.GPSDateStamp");
            if (!str.isEmpty()) exif->fGPSDateStamp.Set_ASCII(str.toAscii());

            // Rational Tags

            if (meta.getExifTagRational("Exif.Photo.ExposureTime", num, den))          exif->fExposureTime          = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FNumber", num, den))               exif->fFNumber               = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ShutterSpeedValue", num, den))     exif->fShutterSpeedValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ApertureValue", num, den))         exif->fApertureValue         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.BrightnessValue", num, den))       exif->fBrightnessValue       = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.ExposureBiasValue", num, den))     exif->fExposureBiasValue     = dng_srational(num, den);
            if (meta.getExifTagRational("Exif.Photo.MaxApertureValue", num, den))      exif->fMaxApertureValue      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalLength", num, den))           exif->fFocalLength           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.DigitalZoomRatio", num, den))      exif->fDigitalZoomRatio      = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.SubjectDistance", num, den))       exif->fSubjectDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Image.BatteryLevel", num, den))          exif->fBatteryLevelR         = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneXResolution", num, den)) exif->fFocalPlaneXResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.Photo.FocalPlaneYResolution", num, den)) exif->fFocalPlaneYResolution = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSAltitude", num, den))         exif->fGPSAltitude           = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDOP", num, den))              exif->fGPSDOP                = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSSpeed", num, den))            exif->fGPSSpeed              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTrack", num, den))            exif->fGPSTrack              = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSImgDirection", num, den))     exif->fGPSImgDirection       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestBearing", num, den))      exif->fGPSDestBearing        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestDistance", num, den))     exif->fGPSDestDistance       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLatitude", num, den))         exif->fGPSLatitude[0]        = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSLongitude", num, den))        exif->fGPSLongitude[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSTimeStamp", num, den))        exif->fGPSTimeStamp[0]       = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLatitude", num, den))     exif->fGPSDestLatitude[0]    = dng_urational(num, den);
            if (meta.getExifTagRational("Exif.GPSInfo.GPSDestLongitude", num, den))    exif->fGPSDestLongitude[0]   = dng_urational(num, den);

            // Integer Tags

            if (meta.getExifTagLong("Exif.Photo.ExposureProgram", val))          exif->fExposureProgram          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.MeteringMode", val))             exif->fMeteringMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.LightSource", val))              exif->fLightSource              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Flash", val))                    exif->fFlash                    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SensingMethod", val))            exif->fSensingMethod            = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FileSource", val))               exif->fFileSource               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneType", val))                exif->fSceneType                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.CustomRendered", val))           exif->fCustomRendered           = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ExposureMode", val))             exif->fExposureMode             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.WhiteBalance", val))             exif->fWhiteBalance             = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SceneCaptureType", val))         exif->fSceneCaptureType         = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.GainControl", val))              exif->fGainControl              = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Contrast", val))                 exif->fContrast                 = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Saturation", val))               exif->fSaturation               = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.Sharpness", val))                exif->fSharpness                = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.SubjectDistanceRange", val))     exif->fSubjectDistanceRange     = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalLengthIn35mmFilm", val))    exif->fFocalLengthIn35mmFilm    = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.ComponentsConfiguration", val))  exif->fComponentsConfiguration  = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelXDimension", val))          exif->fPixelXDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.PixelYDimension", val))          exif->fPixelYDimension          = (uint32)val;
            if (meta.getExifTagLong("Exif.Photo.FocalPlaneResolutionUnit", val)) exif->fFocalPlaneResolutionUnit = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSVersionID", val))           exif->fGPSVersionID             = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSAltitudeRef", val))         exif->fGPSAltitudeRef           = (uint32)val;
            if (meta.getExifTagLong("Exif.GPSInfo.GPSDifferential", val))        exif->fGPSDifferential          = (uint32)val;
        }

        // Markernote backup.

        QByteArray mkrnts = meta.getExifTagData("Exif.Photo.MakerNote");
        if (!mkrnts.isEmpty())
        {
            kDebug( 51000 ) << "DNGWriter: Backup Makernote (" << mkrnts.size() << " bytes)" << endl;

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(mkrnts.data(), mkrnts.size());
            AutoPtr<dng_memory_block> block(host.Allocate(mkrnts.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), mkrnts.size());
            negative->SetMakerNote(block);
            negative->SetMakerNoteSafety(true);
        }

        if (d->backupOriginalRawFile)
        {
            kDebug( 51000 ) << "DNGWriter: Backup Original RAW file (" << inputInfo.size() << " bytes)" << endl;

            // Compress Raw file data to Zip archive.

            QTemporaryFile zipFile;
            if (!zipFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write Zip Raw file. Aborted..." << endl;
                return -1;
            }
            KZip zipArchive(zipFile.fileName());
            zipArchive.open(QIODevice::WriteOnly);
            zipArchive.setCompression(KZip::DeflateCompression);
            zipArchive.addLocalFile(inputFile(), inputFile());
            zipArchive.close();

            // Load Zip Archive in a byte array

            QFileInfo zipFileInfo(zipFile.fileName());
            QByteArray zipRawFileData;
            zipRawFileData.resize(zipFileInfo.size());
            QDataStream dataStream(&zipFile);
            dataStream.readRawData(zipRawFileData.data(), zipRawFileData.size());
            kDebug( 51000 ) << "DNGWriter: Zipped RAW file size " << zipRawFileData.size() << " bytes" << endl;

            // Pass byte array to DNG sdk and compute MD5 fingerprint.

            dng_memory_allocator memalloc(gDefaultDNGMemoryAllocator);
            dng_memory_stream stream(memalloc);
            stream.Put(zipRawFileData.data(), zipRawFileData.size());
            AutoPtr<dng_memory_block> block(host.Allocate(zipRawFileData.size()));
            stream.SetReadPosition(0);
            stream.Get(block->Buffer(), zipRawFileData.size());

            dng_md5_printer md5;
            md5.Process(block->Buffer(), block->LogicalSize());
            negative->SetOriginalRawFileData(block);
            negative->SetOriginalRawFileDigest(md5.Result());
            negative->ValidateOriginalRawFileDigest();

            zipFile.remove();
        }

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Build DNG Negative" << endl;

        // Assign Raw image data.
        negative->SetStage1Image(image);

        // Compute linearized and range mapped image
        negative->BuildStage2Image(host);

        // Compute demosaiced image (used by preview and thumbnail)
        negative->BuildStage3Image(host);

        negative->SynchronizeMetadata();
        negative->RebuildIPTC();

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        dng_preview_list previewList;

// NOTE: something is wrong with Qt < 4.4.0 to import TIFF data as stream in QImage.
#if QT_VERSION >= 0x40400

        if (d->previewMode != DNGWriter::NONE)
        {
            kDebug( 51000 ) << "DNGWriter: DNG preview image creation" << endl;

            // Construct a preview image as TIFF format.
            AutoPtr<dng_image> tiffImage;
            dng_render tiff_render(host, *negative);
            tiff_render.SetFinalSpace(dng_space_sRGB::Get());
            tiff_render.SetFinalPixelType(ttByte);
            tiff_render.SetMaximumSize(d->previewMode == MEDIUM ? 1280 : width);
            tiffImage.Reset(tiff_render.Render());

            dng_image_writer tiff_writer;
            AutoPtr<dng_memory_stream> dms(new dng_memory_stream(gDefaultDNGMemoryAllocator));

            tiff_writer.WriteTIFF(host, *dms, *tiffImage.Get(), piRGB,
                                  ccUncompressed, negative.Get(), &tiff_render.FinalSpace());

            // Write TIFF preview image data to a temp JPEG file
            std::vector<char> tiff_mem_buffer(dms->Length());
            dms->SetReadPosition(0);
            dms->Get(&tiff_mem_buffer.front(), tiff_mem_buffer.size());
            dms.Reset();

            QImage pre_image;
            if (!pre_image.loadFromData((uchar*)&tiff_mem_buffer.front(), tiff_mem_buffer.size(), "TIFF"))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot load TIFF preview data in memory. Aborted..." << endl;
                return -1;
            }

            QTemporaryFile previewFile;
            if (!previewFile.open())
            {
                kDebug( 51000 ) << "DNGWriter: Cannot open temporary file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            if (!pre_image.save(previewFile.fileName(), "JPEG", 90))
            {
                kDebug( 51000 ) << "DNGWriter: Cannot save file to write JPEG preview. Aborted..." << endl;
                return -1;
            }

            // Load JPEG preview file data in DNG preview container.
            AutoPtr<dng_jpeg_preview> jpeg_preview;
            jpeg_preview.Reset(new dng_jpeg_preview);
            jpeg_preview->fPhotometricInterpretation = piYCbCr;
            jpeg_preview->fPreviewSize.v             = pre_image.height();
            jpeg_preview->fPreviewSize.h             = pre_image.width();
            jpeg_preview->fCompressedData.Reset(host.Allocate(previewFile.size()));

            QDataStream previewStream( &previewFile );
            previewStream.readRawData(jpeg_preview->fCompressedData->Buffer_char(), previewFile.size());

            AutoPtr<dng_preview> pp( dynamic_cast<dng_preview*>(jpeg_preview.Release()) );
            previewList.Append(pp);

            previewFile.remove();
        }

#endif /* QT_VERSION >= 0x40400 */

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: DNG thumbnail creation" << endl;

        dng_image_preview thumbnail;
        dng_render thumbnail_render(host, *negative);
        thumbnail_render.SetFinalSpace(dng_space_sRGB::Get());
        thumbnail_render.SetFinalPixelType(ttByte);
        thumbnail_render.SetMaximumSize(256);
        thumbnail.fImage.Reset(thumbnail_render.Render());

        if (d->cancel) return -2;

        // -----------------------------------------------------------------------------------------

        kDebug( 51000 ) << "DNGWriter: Creating DNG file " << outputInfo.fileName() << endl;

        dng_image_writer writer;
        dng_file_stream filestream(QFile::encodeName(dngFilePath), true);

        writer.WriteDNG(host, filestream, *negative.Get(), thumbnail, 
                        d->jpegLossLessCompression ? ccJPEG : ccUncompressed,
                        &previewList);
    }

    catch (const dng_exception &exception)
    {
        int ret = exception.ErrorCode();
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code (" << ret << ")" << endl;
        return ret;
    }

    catch (...)
    {
        kDebug( 51000 ) << "DNGWriter: DNG SDK exception code unknow" << endl;
        return dng_error_unknown;
    }

    kDebug( 51000 ) << "DNGWriter: DNG conversion complete..." << endl;

    return dng_error_none;
}
Example #15
0
int main(int argc, char *argv[])
{
    Q_INIT_RESOURCE(companion);
    QApplication app(argc, argv);
    app.setApplicationName("OpenTX Simulator");
    app.setOrganizationName("OpenTX");
    app.setOrganizationDomain("open-tx.org");

#ifdef __APPLE__
    app.setStyle(new MyProxyStyle);
#endif

    QString dir;
    if (argc) dir = QFileInfo(argv[0]).canonicalPath() + "/lang";

    /* QTranslator companionTranslator;
    companionTranslator.load(":/companion_" + locale);
    QTranslator qtTranslator;
    qtTranslator.load((QString)"qt_" + locale.left(2), QLibraryInfo::location(QLibraryInfo::TranslationsPath));
    app.installTranslator(&companionTranslator);
    app.installTranslator(&qtTranslator);
    */

    QTextCodec::setCodecForCStrings(QTextCodec::codecForName("UTF-8"));

#if defined(JOYSTICKS) || defined(SIMU_AUDIO)
    uint32_t sdlFlags = 0;
#ifdef JOYSTICKS
    sdlFlags |= SDL_INIT_JOYSTICK;
#endif
#ifdef SIMU_AUDIO
    sdlFlags |= SDL_INIT_AUDIO;
#endif
    SDL_Init(sdlFlags);
#endif

    RegisterEepromInterfaces();
    registerOpenTxFirmwares();

    SimulatorDialog *dialog;
    const char * eepromFileName;
    QString fileName;
    QByteArray path;
    QDir eedir;
    QFile file;

    QMessageBox msgBox;
    msgBox.setWindowTitle("Radio type");
    msgBox.setText("Which radio type do you want to simulate?");
    msgBox.setIcon(QMessageBox::Question);
    QAbstractButton *taranisButton = msgBox.addButton("Taranis", QMessageBox::ActionRole);
    QAbstractButton *sky9xButton = msgBox.addButton("9X-Sky9X", QMessageBox::ActionRole);
    QAbstractButton *gruvinButton = msgBox.addButton("9X-Gruvin9X", QMessageBox::ActionRole);
    QAbstractButton *proButton = msgBox.addButton("9XR-Pro", QMessageBox::ActionRole);
    msgBox.addButton("9X-M128", QMessageBox::ActionRole);
    QPushButton *exitButton = msgBox.addButton(QMessageBox::Close);

    eedir = QDir(QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation));
    if (!eedir.exists("OpenTX")) {
        eedir.mkdir("OpenTX");
    }
    eedir.cd("OpenTX");

    msgBox.exec();

    if (msgBox.clickedButton() == exitButton)
        return 0;
    else if (msgBox.clickedButton() == taranisButton) {
        current_firmware_variant = GetFirmware("opentx-taranis-haptic-en");
        fileName = eedir.filePath("eeprom-taranis.bin");
        path = fileName.toAscii();
        eepromFileName = path.data();
        dialog = new SimulatorDialogTaranis();
    }
    else if (msgBox.clickedButton() == sky9xButton) {
        current_firmware_variant = GetFirmware("opentx-sky9x-heli-templates-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-bluetooth-en");
        fileName = eedir.filePath("eeprom-sky9x.bin");
        path = fileName.toAscii();
        eepromFileName = path.data();
        dialog = new SimulatorDialog9X();
    }
    else if (msgBox.clickedButton() == gruvinButton) {
        current_firmware_variant = GetFirmware("opentx-gruvin9x-heli-templates-sdcard-voice-DSM2PPM-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-ttsen-en");
        fileName = eedir.filePath("eeprom-gruvin9x.bin");
        path = fileName.toAscii();
        eepromFileName = path.data();
        dialog = new SimulatorDialog9X();
    }
    else if (msgBox.clickedButton() == proButton) {
        current_firmware_variant = GetFirmware("opentx-9xrpro-heli-templates-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-en");
        fileName = eedir.filePath("eeprom-9xrpro.bin");
        path = fileName.toAscii();
        eepromFileName = path.data();
        dialog = new SimulatorDialog9X();
    }
    else {
        current_firmware_variant = GetFirmware("opentx-9x128-frsky-heli-templates-audio-voice-haptic-DSM2-ppmca-gvars-symlimits-autosource-autoswitch-battgraph-thrtrace-en");
        fileName = eedir.filePath("eeprom-9x128.bin");
        path = fileName.toAscii();
        eepromFileName = path.data();
        dialog = new SimulatorDialog9X();
    }

    dialog->show();
    dialog->start(eepromFileName);

    int result = app.exec();

    delete dialog;

#if defined(JOYSTICKS) || defined(SIMU_AUDIO)
    SDL_Quit();
#endif

    return result;
}
Example #16
0
bool KisTIFFWriterVisitor::saveLayerProjection(KisLayer * layer)
{
    dbgFile << "visiting on layer" << layer->name() << "";
    KisPaintDeviceSP pd = layer->projection();
    // Save depth
    int depth = 8 * pd->pixelSize() / pd->channelCount();
    TIFFSetField(image(), TIFFTAG_BITSPERSAMPLE, depth);
    // Save number of samples
    if (saveAlpha()) {
        TIFFSetField(image(), TIFFTAG_SAMPLESPERPIXEL, pd->channelCount());
        uint16 sampleinfo[1] = { EXTRASAMPLE_UNASSALPHA };
        TIFFSetField(image(), TIFFTAG_EXTRASAMPLES, 1, sampleinfo);
    } else {
        TIFFSetField(image(), TIFFTAG_SAMPLESPERPIXEL, pd->channelCount() - 1);
        TIFFSetField(image(), TIFFTAG_EXTRASAMPLES, 0);
    }
    // Save colorspace information
    uint16 color_type;
    uint16 sample_format = SAMPLEFORMAT_UINT;
    if (!writeColorSpaceInformation(image(), pd->colorSpace(), color_type, sample_format)) { // unsupported colorspace
        return false;
    }
    TIFFSetField(image(), TIFFTAG_PHOTOMETRIC, color_type);
    TIFFSetField(image(), TIFFTAG_SAMPLEFORMAT, sample_format);
    TIFFSetField(image(), TIFFTAG_IMAGEWIDTH, layer->image()->width());
    TIFFSetField(image(), TIFFTAG_IMAGELENGTH, layer->image()->height());

    // Set the compression options
    TIFFSetField(image(), TIFFTAG_COMPRESSION, m_options->compressionType);
    TIFFSetField(image(), TIFFTAG_FAXMODE, m_options->faxMode);
    TIFFSetField(image(), TIFFTAG_JPEGQUALITY, m_options->jpegQuality);
    TIFFSetField(image(), TIFFTAG_ZIPQUALITY, m_options->deflateCompress);
    TIFFSetField(image(), TIFFTAG_PIXARLOGQUALITY, m_options->pixarLogCompress);

    // Set the predictor
    TIFFSetField(image(), TIFFTAG_PREDICTOR, m_options->predictor);

    // Use contiguous configuration
    TIFFSetField(image(), TIFFTAG_PLANARCONFIG, PLANARCONFIG_CONTIG);
    // Use 8 rows per strip
    TIFFSetField(image(), TIFFTAG_ROWSPERSTRIP, 8);

    // Save profile
    const KoColorProfile* profile = pd->colorSpace()->profile();
    if (profile && profile->type() == "icc" && !profile->rawData().isEmpty()) {
        QByteArray ba = profile->rawData();
        TIFFSetField(image(), TIFFTAG_ICCPROFILE, ba.size(), ba.data());
    }
    tsize_t stripsize = TIFFStripSize(image());
    tdata_t buff = _TIFFmalloc(stripsize);
    qint32 height = layer->image()->height();
    qint32 width = layer->image()->width();
    bool r = true;
    for (int y = 0; y < height; y++) {
        KisHLineConstIteratorSP it = pd->createHLineConstIteratorNG(0, y, width);
        switch (color_type) {
        case PHOTOMETRIC_MINISBLACK: {
                quint8 poses[] = { 0, 1 };
                r = copyDataToStrips(it, buff, depth, 1, poses);
            }
            break;
        case PHOTOMETRIC_RGB: {
                quint8 poses[] = { 2, 1, 0, 3};
                r = copyDataToStrips(it, buff, depth, 3, poses);
            }
            break;
        case PHOTOMETRIC_SEPARATED: {
                quint8 poses[] = { 0, 1, 2, 3, 4 };
                r = copyDataToStrips(it, buff, depth, 4, poses);
            }
            break;
        case PHOTOMETRIC_CIELAB: {
                quint8 poses[] = { 0, 1, 2, 3 };
                r = copyDataToStrips(it, buff, depth, 3, poses);
            }
            break;
            return false;
        }
        if (!r) return false;
        TIFFWriteScanline(image(), buff, y, (tsample_t) - 1);
    }
    _TIFFfree(buff);
    TIFFWriteDirectory(image());
    return true;
}
void wrapInFunction()
{

//! [0]
QByteArray ba("Hello");
//! [0]


//! [1]
QByteArray ba;
ba.resize(5);
ba[0] = 0x3c;
ba[1] = 0xb8;
ba[2] = 0x64;
ba[3] = 0x18;
ba[4] = 0xca;
//! [1]


//! [2]
for (int i = 0; i < ba.size(); ++i) {
    if (ba.at(i) >= 'a' && ba.at(i) <= 'f')
        cout << "Found character in range [a-f]" << endl;
}
//! [2]


//! [3]
QByteArray x("and");
x.prepend("rock ");         // x == "rock and"
x.append(" roll");          // x == "rock and roll"
x.replace(5, 3, "&");       // x == "rock & roll"
//! [3]


//! [4]
QByteArray ba("We must be <b>bold</b>, very <b>bold</b>");
int j = 0;
while ((j = ba.indexOf("<b>", j)) != -1) {
    cout << "Found <b> tag at index position " << j << endl;
    ++j;
}
//! [4]


//! [5]
QByteArray().isNull();          // returns true
QByteArray().isEmpty();         // returns true

QByteArray("").isNull();        // returns false
QByteArray("").isEmpty();       // returns true

QByteArray("abc").isNull();     // returns false
QByteArray("abc").isEmpty();    // returns false
//! [5]


//! [6]
QByteArray ba("Hello");
int n = ba.size();          // n == 5
ba.data()[0];               // returns 'H'
ba.data()[4];               // returns 'o'
ba.data()[5];               // returns '\0'
//! [6]


//! [7]
QByteArray().isEmpty();         // returns true
QByteArray("").isEmpty();       // returns true
QByteArray("abc").isEmpty();    // returns false
//! [7]


//! [8]
QByteArray ba("Hello world");
char *data = ba.data();
while (*data) {
    cout << "[" << *data << "]" << endl;
    ++data;
}
//! [8]


//! [9]
QByteArray ba;
for (int i = 0; i < 10; ++i)
    ba[i] = 'A' + i;
// ba == "ABCDEFGHIJ"
//! [9]


//! [10]
QByteArray ba("Stockholm");
ba.truncate(5);             // ba == "Stock"
//! [10]


//! [11]
QByteArray ba("STARTTLS\r\n");
ba.chop(2);                 // ba == "STARTTLS"
//! [11]


//! [12]
QByteArray x("free");
QByteArray y("dom");
x += y;
// x == "freedom"
//! [12]


//! [13]
QByteArray().isNull();          // returns true
QByteArray("").isNull();        // returns false
QByteArray("abc").isNull();     // returns false
//! [13]


//! [14]
QByteArray ba("Istambul");
ba.fill('o');
// ba == "oooooooo"

ba.fill('X', 2);
// ba == "XX"
//! [14]


//! [15]
QByteArray x("ship");
QByteArray y("air");
x.prepend(y);
// x == "airship"
//! [15]


//! [16]
QByteArray x("free");
QByteArray y("dom");
x.append(y);
// x == "freedom"
//! [16]


//! [17]
QByteArray ba("Meal");
ba.insert(1, QByteArray("ontr"));
// ba == "Montreal"
//! [17]


//! [18]
QByteArray ba("Montreal");
ba.remove(1, 4);
// ba == "Meal"
//! [18]


//! [19]
QByteArray x("Say yes!");
QByteArray y("no");
x.replace(4, 3, y);
// x == "Say no!"
//! [19]


//! [20]
QByteArray ba("colour behaviour flavour neighbour");
ba.replace(QByteArray("ou"), QByteArray("o"));
// ba == "color behavior flavor neighbor"
//! [20]


//! [21]
QByteArray x("sticky question");
QByteArray y("sti");
x.indexOf(y);               // returns 0
x.indexOf(y, 1);            // returns 10
x.indexOf(y, 10);           // returns 10
x.indexOf(y, 11);           // returns -1
//! [21]


//! [22]
QByteArray ba("ABCBA");
ba.indexOf("B");            // returns 1
ba.indexOf("B", 1);         // returns 1
ba.indexOf("B", 2);         // returns 3
ba.indexOf("X");            // returns -1
//! [22]


//! [23]
QByteArray x("crazy azimuths");
QByteArray y("az");
x.lastIndexOf(y);           // returns 6
x.lastIndexOf(y, 6);        // returns 6
x.lastIndexOf(y, 5);        // returns 2
x.lastIndexOf(y, 1);        // returns -1
//! [23]


//! [24]
QByteArray ba("ABCBA");
ba.lastIndexOf("B");        // returns 3
ba.lastIndexOf("B", 3);     // returns 3
ba.lastIndexOf("B", 2);     // returns 1
ba.lastIndexOf("X");        // returns -1
//! [24]


//! [25]
QByteArray url("ftp://ftp.qt-project.org/");
if (url.startsWith("ftp:"))
    ...
//! [25]


//! [26]
QByteArray url("http://qt-project.org/doc/qt-5.0/qtdoc/index.html");
if (url.endsWith(".html"))
    ...
//! [26]


//! [27]
QByteArray x("Pineapple");
QByteArray y = x.left(4);
// y == "Pine"
//! [27]


//! [28]
QByteArray x("Pineapple");
QByteArray y = x.right(5);
// y == "apple"
//! [28]


//! [29]
QByteArray x("Five pineapples");
QByteArray y = x.mid(5, 4);     // y == "pine"
QByteArray z = x.mid(5);        // z == "pineapples"
//! [29]


//! [30]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toLower();
// y == "qt by digia"
//! [30]


//! [31]
QByteArray x("Qt by DIGIA");
QByteArray y = x.toUpper();
// y == "QT BY DIGIA"
//! [31]


//! [32]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.simplified();
// ba == "lots of whitespace";
//! [32]


//! [33]
QByteArray ba("  lots\t of\nwhitespace\r\n ");
ba = ba.trimmed();
// ba == "lots\t of\nwhitespace";
//! [33]


//! [34]
QByteArray x("apple");
QByteArray y = x.leftJustified(8, '.');   // y == "apple..."
//! [34]


//! [35]
QByteArray x("apple");
QByteArray y = x.rightJustified(8, '.');    // y == "...apple"
//! [35]


//! [36]
QByteArray str("FF");
bool ok;
int hex = str.toInt(&ok, 16);     // hex == 255, ok == true
int dec = str.toInt(&ok, 10);     // dec == 0, ok == false
//! [36]


//! [37]
QByteArray str("FF");
bool ok;
long hex = str.toLong(&ok, 16);   // hex == 255, ok == true
long dec = str.toLong(&ok, 10);   // dec == 0, ok == false
//! [37]


//! [38]
QByteArray string("1234.56");
double a = string.toDouble();   // a == 1234.56
//! [38]


//! [39]
QByteArray text("Qt is great!");
text.toBase64();        // returns "UXQgaXMgZ3JlYXQh"
//! [39]

//! [39bis]
QByteArray text("<p>Hello?</p>");
text.toBase64(QByteArray::Base64Encoding | QByteArray::OmitTrailingEquals);      // returns "PHA+SGVsbG8/PC9wPg"
text.toBase64(QByteArray::Base64Encoding);                                       // returns "PHA+SGVsbG8/PC9wPg=="
text.toBase64(QByteArray::Base64UrlEncoding);                                    // returns "PHA-SGVsbG8_PC9wPg=="
text.toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals);   // returns "PHA-SGVsbG8_PC9wPg"
//! [39bis]


//! [40]
QByteArray ba;
int n = 63;
ba.setNum(n);           // ba == "63"
ba.setNum(n, 16);       // ba == "3f"
//! [40]


//! [41]
int n = 63;
QByteArray::number(n);              // returns "63"
QByteArray::number(n, 16);          // returns "3f"
QByteArray::number(n, 16).toUpper();  // returns "3F"
//! [41]


//! [42]
QByteArray ba = QByteArray::number(12.3456, 'E', 3);
// ba == 1.235E+01
//! [42]


//! [43]
 static const char mydata[] = {
    0x00, 0x00, 0x03, 0x84, 0x78, 0x9c, 0x3b, 0x76,
    0xec, 0x18, 0xc3, 0x31, 0x0a, 0xf1, 0xcc, 0x99,
    ...
    0x6d, 0x5b
};

QByteArray data = QByteArray::fromRawData(mydata, sizeof(mydata));
QDataStream in(&data, QIODevice::ReadOnly);
...
//! [43]


//! [44]
QByteArray text = QByteArray::fromBase64("UXQgaXMgZ3JlYXQh");
text.data();            // returns "Qt is great!"
//! [44]

//! [44bis]
QByteArray::fromBase64("PHA+SGVsbG8/PC9wPg==", QByteArray::Base64Encoding); // returns "<p>Hello?</p>"
QByteArray::fromBase64("PHA-SGVsbG8_PC9wPg==", QByteArray::Base64UrlEncoding); // returns "<p>Hello?</p>"
//! [44bis]


//! [45]
QByteArray text = QByteArray::fromHex("517420697320677265617421");
text.data();            // returns "Qt is great!"
//! [45]

//! [46]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size()];
strcpy(data, text.data());
delete [] data;
//! [46]

//! [47]
QString tmp = "test";
QByteArray text = tmp.toLocal8Bit();
char *data = new char[text.size() + 1];
strcpy(data, text.data());
delete [] data;
//! [47]

//! [48]
QByteArray ba1("ca\0r\0t");
ba1.size();                     // Returns 2.
ba1.constData();                // Returns "ca" with terminating \0.

QByteArray ba2("ca\0r\0t", 3);
ba2.size();                     // Returns 3.
ba2.constData();                // Returns "ca\0" with terminating \0.

QByteArray ba3("ca\0r\0t", 4);
ba3.size();                     // Returns 4.
ba3.constData();                // Returns "ca\0r" with terminating \0.

const char cart[] = {'c', 'a', '\0', 'r', '\0', 't'};
QByteArray ba4(QByteArray::fromRawData(cart, 6));
ba4.size();                     // Returns 6.
ba4.constData();                // Returns "ca\0r\0t" without terminating \0.
//! [48]

}
static QString resolveBundlePath(const QString &bundlePath)
{
  const QFileInfo fi(bundlePath);
  if (!fi.isBundle())
    return bundlePath;

  const QByteArray utf8Bundle = fi.absoluteFilePath().toUtf8();
  CFURLRef bundleUrl = CFURLCreateFromFileSystemRepresentation(NULL, reinterpret_cast<const UInt8*>(utf8Bundle.data()), utf8Bundle.length(), true);
  CFBundleRef bundle = CFBundleCreate(NULL, bundleUrl);
  if (bundle) {
    CFURLRef url = CFBundleCopyExecutableURL(bundle);
    char executableFile[FILENAME_MAX];
    CFURLGetFileSystemRepresentation(url, true, reinterpret_cast<UInt8*>(executableFile), FILENAME_MAX);
    CFRelease(url);
    CFRelease(bundle);
    CFRelease(bundleUrl);
    return QString::fromUtf8(executableFile);
  }
  CFRelease(bundle);
  CFRelease(bundleUrl);

  return bundlePath;
}
Example #19
0
void OptionsDialog::on_comboBox_AudioDevice_activated( const QString deviceName )
{
    QByteArray charArray = deviceName.toLocal8Bit();
    const String outputDeviceName = charArray.data();

    // Get current audio settings
    AudioDeviceManager::AudioDeviceSetup config;
    m_deviceManager.getAudioDeviceSetup( config );
    String error;

    // Update audio settings
    if ( outputDeviceName != config.outputDeviceName )
    {
        tearDownMidiInputTestSynth();

        if ( outputDeviceName != getNoDeviceString().toLocal8Bit().data() )
        {
            config.outputDeviceName = outputDeviceName;
        }
        else
        {
            config.outputDeviceName = String::empty;
        }

        if ( ! isJackAudioEnabled() )
        {
            config.useDefaultOutputChannels = true;
        }
        error = m_deviceManager.setAudioDeviceSetup( config, true );

        const bool isJackMidiEnabled = outputDeviceName.startsWith( "JACK" ) && outputDeviceName.contains( "MIDI" );

        // If necessary, disable ALSA MIDI inputs as they conflict with JACK MIDI inputs
        if ( isJackMidiEnabled )
        {
            disableAlsaMidiInputs();
        }

        // When a new audio device is selected the following widgets should be updated
        updateOutputChannelComboBox();
        updateSampleRateComboBox();
        updateBufferSizeComboBox();
        updateMidiInputListWidget( isJackMidiEnabled );

        if ( error.isEmpty() )
        {
            if ( m_ui->checkBox_MidiInputTestTone->isChecked() )
            {
                setUpMidiInputTestSynth();
            }

            emit audioDeviceChanged();
        }
        else
        {
            m_ui->checkBox_MidiInputTestTone->setChecked( false );

            MessageBoxes::showWarningDialog( tr("Error when trying to open audio device!"), error.toRawUTF8() );
        }
    }
}
Example #20
0
//--------------------------------------------------------------------------------
void TBasePacket::GetStrDescItem(std::vector<std::string>& vecStr, int sizeStack)
{
  std::string tabs = "";
  for(int i = 0 ; i < sizeStack ; i++)
    tabs += "\t\t";

  int cntDesc = mMarkUp->GetCountDesc();
  for( int iDesc = 0 ; iDesc < cntDesc ; iDesc++ )
  {
    std::string name = mMarkUp->GetNameDesc(iDesc);
    QByteArray ba = WinToKoi8(name.data());
    std::string nameKOI8 = ba.data();// название секции берется из xml, там кодировка CP1251.

    int cntElem = 0;
    if(mMarkUp->GetTypeDesc(iDesc)==IMarkUpContainer::eArr)
    {
      // войти в какой-нибудь элемент и проверить что он константный
      cntElem = mMarkUp->GetCount(name.data());
      if(cntElem!=0)
      {
        bool resConst = false;
        if(mMarkUp->Enter(name.data(), 0))
        {
          resConst = ((mMarkUp->GetCountDesc()==1) && (mMarkUp->GetTypeDesc(0)==IMarkUpContainer::eConst));
          mMarkUp->Leave();
        }
        if(resConst)
        {
          std::string sConst = ": ";
          for( int iElem = 0 ; iElem < cntElem ; iElem++ )
          {
            if(mMarkUp->Enter(name.data(), iElem))
            {
              // не учел (пока намеренно) вариант когда str_const == "" т.е. когда не нужно отображать
              sConst += GetStrDescConstItem(mMarkUp->GetNameDesc(0));
              mMarkUp->Leave();
            }
          }
          vecStr.push_back(tabs + nameKOI8 + sConst);
          continue;
        }
      }
      char s[100];
      sprintf(s, "(%d):\n", cntElem);
      vecStr.push_back(tabs + nameKOI8 + s);
    }
    else
    {
      std::string str_const = GetStrDescConstItem(name);
      if(str_const.length())
      {
        std::string sConst = ": ";
        sConst += str_const;
        sConst += "\n";

        vecStr.push_back(tabs + nameKOI8 + sConst);
      }
    }
    
    for( int iElem = 0 ; iElem < cntElem ; iElem++ )
    {
      if(mMarkUp->Enter(name.data(), iElem))
      {
        GetStrDescItem(vecStr, sizeStack + 1);
        mMarkUp->Leave();
      }
    }
  }
}
void ArtNetController::processPendingPackets()
{
    while (m_UdpSocket->hasPendingDatagrams())
    {
        QByteArray datagram;
        QHostAddress senderAddress;
        datagram.resize(m_UdpSocket->pendingDatagramSize());
        m_UdpSocket->readDatagram(datagram.data(), datagram.size(), &senderAddress);
        if (senderAddress != m_ipAddr)
        {
            qDebug() << "Received packet with size: " << datagram.size() << ", host: " << senderAddress.toString();
            int opCode = -1;
            if (m_packetizer->checkPacketAndCode(datagram, opCode) == true)
            {
                switch (opCode)
                {
                    case ARTNET_POLLREPLY:
                    {
                        qDebug() << "ArtPollReply received";
                        ArtNetNodeInfo newNode;
                        if (m_packetizer->fillArtPollReplyInfo(datagram, newNode) == true)
                        {
                            if (m_nodesList.contains(senderAddress) == false)
                                m_nodesList[senderAddress] = newNode;
                        }
                        QByteArray pollReplyPacket;
                        m_packetizer->setupArtNetPollReply(pollReplyPacket, m_ipAddr, m_MACAddress);
                        m_UdpSocket->writeDatagram(pollReplyPacket.data(), pollReplyPacket.size(),
                                                   senderAddress, ARTNET_DEFAULT_PORT);
                    }
                    break;
                    case ARTNET_POLL:
                    {
                        qDebug() << "ArtPoll received";
                        QByteArray pollReplyPacket;
                        m_packetizer->setupArtNetPollReply(pollReplyPacket, m_ipAddr, m_MACAddress);
                        m_UdpSocket->writeDatagram(pollReplyPacket.data(), pollReplyPacket.size(),
                                                   senderAddress, ARTNET_DEFAULT_PORT);
                    }
                    break;
                    case ARTNET_DMX:
                    {
                        qDebug() << "DMX data received";
                        QByteArray dmxData;
                        int universe;
                        if (m_packetizer->fillDMXdata(datagram, dmxData, universe) == true)
                        {
                            if ((universe * 512) > m_dmxValues.length() || m_universes.contains(universe) == false)
                            {
                                qDebug() << "Universe " << universe << "not supported !";
                                break;
                            }
                            for (int i = 0; i < dmxData.length(); i++)
                            {
                                if (m_dmxValues.at(i + (universe * 512)) != dmxData.at(i))
                                    emit valueChanged(m_universes[universe], i, (uchar)dmxData.at(i));
                            }
                        }
                    }
                    break;
                    default:
                        qDebug() << "opCode not supported yet (" << opCode << ")";
                    break;
                }
            }
            else
                qDebug() << "Malformed packet received";
        }
     }
}
Example #22
0
/**
 * This method tries to read all lines contained in the receive buffer. A line
 * is always terminated by a newline and is taken over in the receiver queue,
 * if the checksum is valid and the GPS identifier is requested.
 */
void GpsClient::readSentenceFromBuffer()
{
    char *start = databuffer;
    char *end   = 0;

    while(strlen(start))
    {
        // Search for a newline in the receiver buffer.
        // That is the normal end of a GPS sentence.
        if( ! (end = strchr( start, '\n' )) )
        {
            // No newline in the receiver buffer, wait for more characters
            return;
        }

        if( start == end )
        {
            // skip newline and start at next position with a new search
            start++;
            continue;
        }

        // found a complete record in the buffer, it will be extracted now
        char *record = (char *) malloc( end-start + 2 );

        memset( record, 0, end-start + 2 );

        strncpy( record, start, end-start + 1);

        if( verifyCheckSum( record ) == true )
        {
            // Forward sentence to the server, if checksum is ok and
            // processing is desired.
            if( checkGpsMessageFilter( record ) == true && forwardGpsData == true )
            {
                QByteArray ba;
                ba.append( MSG_GPS_DATA );
                ba.append( ' ' );
                ba.append( record );
                writeForwardMsg( ba.data() );
            }
        }

#ifdef DEBUG_NMEA
        qDebug() << "GpsClient::read():" << record;
#endif

        free(record);
        record = 0;

        // remove queued record from receive buffer
        memmove( databuffer, end+1,
                 databuffer + sizeof(databuffer)-1 - end );

        datapointer -= (end+1 - databuffer);

        dbsize -= ( end+1 - databuffer);

        start = databuffer;

        end = 0;
    }
}
void Q3Socket::sn_read( bool force )
{
    Q_LONG maxToRead = 0;
    if ( d->readBufferSize > 0 ) {
	maxToRead = d->readBufferSize - d->rba.size();
	if ( maxToRead <= 0 ) {
	    if ( d->rsn )
		d->rsn->setEnabled( false );
	    return;
	}
    }

    // Use Q3SocketPrivate::sn_read_alreadyCalled to avoid recursive calls of
    // sn_read() (and as a result avoid emitting the readyRead() signal in a
    // slot for readyRead(), if you use bytesAvailable()).
    if ( !force && Q3SocketPrivate::sn_read_alreadyCalled.findRef(this) != -1 )
	return;
    Q3SocketPrivate::sn_read_alreadyCalled.append( this );

    char buf[4096];
    Q_LONG nbytes = d->socket->bytesAvailable();
    Q_LONG nread;
    QByteArray *a = 0;

    if ( state() == Connecting ) {
	if ( nbytes > 0 ) {
	    tryConnection();
	} else {
	    // nothing to do, nothing to care about
	    Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
	    return;
	}
    }
    if ( state() == Idle ) {
	Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
	return;
    }

    if ( nbytes <= 0 ) {			// connection closed?
	// On Windows this may happen when the connection is still open.
	// This happens when the system is heavily loaded and we have
	// read all the data on the socket before a new WSAAsyncSelect
	// event is processed. A new read operation would then block.
	// This code is also useful when Q3Socket is used without an
	// event loop.
	nread = d->socket->readBlock( buf, maxToRead ? QMIN((Q_LONG)sizeof(buf),maxToRead) : sizeof(buf) );
	if ( nread == 0 ) {			// really closed
            if ( !d->socket->isOpen() ) {
#if defined(Q3SOCKET_DEBUG)
                qDebug( "Q3Socket (%s): sn_read: Connection closed", name() );
#endif
                d->connectionClosed();
                emit connectionClosed();
            }
	    Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
	    return;
	} else {
	    if ( nread < 0 ) {
		if ( d->socket->error() == Q3SocketDevice::NoError ) {
		    // all is fine
		    Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
		    return;
		}
#if defined(Q3SOCKET_DEBUG)
		qWarning( "Q3Socket::sn_read (%s): Close error", name() );
#endif
		if ( d->rsn )
		    d->rsn->setEnabled( false );
		emit error( ErrSocketRead );
		Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
		return;
	    }
	    a = new QByteArray( nread );
	    memcpy( a->data(), buf, nread );
	}

    } else {					// data to be read
#if defined(Q3SOCKET_DEBUG)
	qDebug( "Q3Socket (%s): sn_read: %ld incoming bytes", name(), nbytes );
#endif
	if ( nbytes > (int)sizeof(buf) ) {
	    // big
	    a = new QByteArray( nbytes );
	    nread = d->socket->readBlock( a->data(), maxToRead ? QMIN(nbytes,maxToRead) : nbytes );
	} else {
	    a = 0;
	    nread = d->socket->readBlock( buf, maxToRead ? QMIN((Q_LONG)sizeof(buf),maxToRead) : sizeof(buf) );
	    if ( nread > 0 ) {
		// ##### could setRawData
		a = new QByteArray( nread );
		memcpy( a->data(), buf, nread );
	    }
	}
	if ( nread == 0 ) {
#if defined(Q3SOCKET_DEBUG)
	    qDebug( "Q3Socket (%s): sn_read: Connection closed", name() );
#endif
	    // ### we should rather ask the socket device if it is closed
	    d->connectionClosed();
	    emit connectionClosed();
	    Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
            delete a;
	    return;
	} else if ( nread < 0 ) {
            delete a;

	    if ( d->socket->error() == Q3SocketDevice::NoError ) {
		// all is fine
		Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
		return;
	    }
#if defined(QT_CHECK_RANGE)
	    qWarning( "Q3Socket::sn_read: Read error" );
#endif
	    if ( d->rsn )
		d->rsn->setEnabled( false );
	    emit error( ErrSocketRead );
	    Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
	    return;
	}
	if ( nread != (int)a->size() ) {		// unexpected
#if defined(CHECK_RANGE) && !defined(Q_OS_WIN32)
	    qWarning( "Q3Socket::sn_read: Unexpected short read" );
#endif
	    a->resize( nread );
	}
    }
    d->rba.append( a );
    if ( !force ) {
	if ( d->rsn )
	    d->rsn->setEnabled( false );
	emit readyRead();
	if ( d->rsn )
	    d->rsn->setEnabled( true );
    }

    Q3SocketPrivate::sn_read_alreadyCalled.removeRef( this );
}
void SerialPortLink::send(const QByteArray& packet)
{
    m_port->write(::separator);
    m_port->write(packet.data(), packet.size());
}
Example #25
0
void mafEventDispatcherLocal::notifyEvent(const mafEvent &event_dictionary, mafEventArgumentsList *argList, QGenericReturnArgument *returnArg) const {
    QString topic = event_dictionary[TOPIC].toString();
    mafEventItemListType items = signalItemProperty(topic);
    mafEvent *itemEventProp;

    mafEventArgumentsListPointer argListPointer = event_dictionary.argumentList();
    bool hasArgs(argListPointer->count() > 0);
    if (hasArgs) {
        // We have arguments attached to the event...
        argList = argListPointer;
    }
    const QGenericReturnArgument *retVal = event_dictionary.returnValue();
    if (retVal && retVal->data() != NULL) {
        returnArg = (QGenericReturnArgument *)retVal;
    }
    
    Qt::ConnectionType connType = event_dictionary.isSynchronous() ? Qt::DirectConnection : Qt::AutoConnection;

    Q_FOREACH(itemEventProp, items) {
        if((*itemEventProp)[SIGNATURE].toString().length() != 0) {
            QString signal_to_emit = (*itemEventProp)[SIGNATURE].toString().split("(")[0];
            QObject *obj = (*itemEventProp)[OBJECT].value<QObject *>();
            if(argList != NULL) {
                if (returnArg == NULL || returnArg->data() == NULL) { //don't use return value
                    switch (argList->count()) {
                        case 0:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType);
                            break;
                        case 1:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                            connType, argList->at(0));
                            break;
                        case 2:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                            connType, argList->at(0), argList->at(1));
                            break;
                        case 3:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                            connType, argList->at(0), argList->at(1), argList->at(2));
                            break;
                        case 4:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3));
                            break;
                        case 5:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4));
                            break;
                        case 6:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), argList->at(5));
                            break;
                        case 7:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6));
                            break;
                        case 8:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6), argList->at(7));
                            break;
                        case 9:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6), argList->at(7), argList->at(8));
                            break;
                        case 10:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), \
                             connType, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6), argList->at(7), argList->at(8), argList->at(9));
                            break;
                        default: {
                            QByteArray ba = mafTr("Number of arguments not supported. Max 10 arguments").toAscii();
                            qWarning("%s", ba.data());
                        }
                    } //switch
                 } else { //use return value
                    switch (argList->count()) {
                        case 0:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType, *returnArg);
                            break;
                        case 1:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0));
                            break;
                        case 2:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                             *returnArg, argList->at(0), argList->at(1));
                            break;
                        case 3:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0), argList->at(1), argList->at(2));
                            break;
                        case 4:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                             *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3));
                            break;
                        case 5:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4));
                            break;
                        case 6:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), argList->at(5));
                            break;
                        case 7:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6));
                            break;
                        case 8:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                             *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6), argList->at(7));
                            break;
                        case 9:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                             argList->at(5), argList->at(6), argList->at(7), argList->at(8));
                            break;
                        case 10:
                            this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType,\
                            *returnArg, argList->at(0), argList->at(1), argList->at(2), argList->at(3), argList->at(4), \
                            argList->at(5), argList->at(6), argList->at(7), argList->at(8), argList->at(9));
                            break;
                        default: {
                            QByteArray ba = mafTr("Number of arguments not supported. Max 10 arguments").toAscii();
                            qWarning("%s", ba.data());
                        }
                    } //switch
                 }
            } else {
                if (returnArg == NULL || returnArg->data() == NULL) { //don't use return value
                    this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType);
                } else {
                    this->metaObject()->invokeMethod(obj, signal_to_emit.toAscii(), connType, *returnArg);
                }
            }
        }
    }
}
qint64 SpeexInputProcessor::writeData(const char *data, qint64 maxSize) {
        int iArg;
        int i;
        float sum;
        short max;

        inputBuffer += QByteArray(data, maxSize);

        while((size_t)inputBuffer.size() > FRAME_SIZE * sizeof(qint16)) {

                QByteArray source_frame = inputBuffer.left(FRAME_SIZE * sizeof(qint16));
                short* psMic = (short *)source_frame.data();

                //let's do volume detection
                sum=1.0f;
                for (i=0;i<FRAME_SIZE;i++) {
                        sum += static_cast<float>(psMic[i] * psMic[i]);
                }
                dPeakMic = qMax(20.0f*log10f(sqrtf(sum / static_cast<float>(FRAME_SIZE)) / 32768.0f), -96.0f);

                max = 1;
                for (i=0;i<FRAME_SIZE;i++)
                        max = static_cast<short>(std::abs(psMic[i]) > max ? std::abs(psMic[i]) : max);
                dMaxMic = max;

                dPeakSpeaker = 0.0;

                QMutexLocker l(&qmSpeex);

                if (bResetProcessor) {
                        if (preprocessor)
                                speex_preprocess_state_destroy(preprocessor);

                        preprocessor = speex_preprocess_state_init(FRAME_SIZE, SAMPLING_RATE);

                        iArg = 1;
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_VAD, &iArg);
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_AGC, &iArg);
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_DENOISE, &iArg);
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_DEREVERB, &iArg);

                        iArg = 30000;
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_AGC_TARGET, &iArg);

                        iArg = -60;
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_AGC_DECREMENT, &iArg);

                        iArg = rsVOIP->getVoipiNoiseSuppress();
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg);

                        if (echo_state) {
                                iArg = SAMPLING_RATE;
                                speex_echo_ctl(echo_state, SPEEX_ECHO_SET_SAMPLING_RATE, &iArg);
                                speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_ECHO_STATE, echo_state);
                        }

                        bResetProcessor = false;
                }

                float v = 30000.0f / static_cast<float>(rsVOIP->getVoipiMinLoudness());

                iArg = iroundf(floorf(20.0f * log10f(v)));
                speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_AGC_MAX_GAIN, &iArg);

                speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_GET_AGC_GAIN, &iArg);
                float gainValue = static_cast<float>(iArg);
                iArg = rsVOIP->getVoipiNoiseSuppress() - iArg;
                speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &iArg);

                short * psSource = psMic;
                if (echo_state && rsVOIP->getVoipEchoCancel()) {
                    speex_echo_playback(echo_state, (short*)lastEchoFrame->data());
                    speex_echo_capture(echo_state,psMic,psClean);
                    psSource = psClean;
                }
                speex_preprocess_run(preprocessor, psSource);

                //we will now analize the processed signal
                sum=1.0f;
                for (i=0;i<FRAME_SIZE;i++)
                        sum += static_cast<float>(psSource[i] * psSource[i]);
                float micLevel = sqrtf(sum / static_cast<float>(FRAME_SIZE));
                dPeakSignal = qMax(20.0f*log10f(micLevel / 32768.0f), -96.0f);

                spx_int32_t prob = 0;
                speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_GET_PROB, &prob);//speech probability
                fSpeechProb = static_cast<float>(prob) / 100.0f;

                // clean microphone level: peak of filtered signal attenuated by AGC gain
                dPeakCleanMic = qMax(dPeakSignal - gainValue, -96.0f);
                dVoiceAcivityLevel = 0.4f * fSpeechProb + 0.6f * (1.0f + dPeakCleanMic / 96.0f);//ponderation for speech detection and audio amplitude

                bool bIsSpeech = false;

                if (dVoiceAcivityLevel > (static_cast<float>(rsVOIP->getVoipfVADmax()) / 32767))
                        bIsSpeech = true;
                else if (dVoiceAcivityLevel > (static_cast<float>(rsVOIP->getVoipfVADmin()) / 32767) && bPreviousVoice)
                        bIsSpeech = true;

                if (! bIsSpeech) {
                        iHoldFrames++;
                        if (iHoldFrames < rsVOIP->getVoipVoiceHold())
                                bIsSpeech = true;
                } else {
                        iHoldFrames = 0;
                }


                if (rsVOIP->getVoipATransmit() == RsVOIP::AudioTransmitContinous) {
                        bIsSpeech = true;
                }
                else if (rsVOIP->getVoipATransmit() == RsVOIP::AudioTransmitPushToTalk)
                        bIsSpeech = false;//g.s.uiDoublePush && ((g.uiDoublePush < g.s.uiDoublePush) || (g.tDoublePush.elapsed() < g.s.uiDoublePush));

                //bIsSpeech = bIsSpeech || (g.iPushToTalk > 0);

                /*if (g.s.bMute || ((g.s.lmLoopMode != RsVOIP::Local) && p && (p->bMute || p->bSuppress)) || g.bPushToMute || (g.iTarget < 0)) {
                        bIsSpeech = false;
                }*/

                if (bIsSpeech) {
                        iSilentFrames = 0;
                } else {
                        iSilentFrames++;
                }

                /*if (p) {
                        if (! bIsSpeech)
                                p->setTalking(RsVOIP::Passive);
                        else if (g.iTarget == 0)
                                p->setTalking(RsVOIP::Talking);
                        else
                                p->setTalking(RsVOIP::Shouting);
                }*/


                if (! bIsSpeech && ! bPreviousVoice) {
                        iRealTimeBitrate = 0;
                        /*if (g.s.iIdleTime && ! g.s.bDeaf && ((tIdle.elapsed() / 1000000ULL) > g.s.iIdleTime)) {
                                emit doDeaf();
                                tIdle.restart();
                        }*/
                        spx_int32_t increment = 0;
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &increment);
                } else {
                        spx_int32_t increment = 12;
                        speex_preprocess_ctl(preprocessor, SPEEX_PREPROCESS_SET_AGC_INCREMENT, &increment);
                }


                int vbr_on=0;
                //just use fixed bitrate for now
                //encryption of VBR-encoded speech may not ensure complete privacy, as phrases can still be identified, at least in a controlled setting with a small dictionary of phrases, by analysing the pattern of variation of the bit rate.
                if (rsVOIP->getVoipATransmit() == RsVOIP::AudioTransmitVAD) {//maybe we can do fixer bitrate when voice detection is active
                    vbr_on = 1;//test it on for all modes
                } else {//maybe we can do vbr for ppt and continuous
                    vbr_on = 1;
                }
                speex_encoder_ctl(enc_state,SPEEX_SET_VBR, &vbr_on);

                int br = 0;
                speex_encoder_ctl(enc_state, SPEEX_GET_VBR_MAX_BITRATE, &br);
                if (br != iMaxBitRate) {
                        br = iMaxBitRate;
                        speex_encoder_ctl(enc_state, SPEEX_SET_VBR_MAX_BITRATE, &br);
                }
                speex_encoder_ctl(enc_state, SPEEX_GET_BITRATE, &br);
                if (br != iMaxBitRate) {
                        br = iMaxBitRate;
                        speex_encoder_ctl(enc_state, SPEEX_SET_BITRATE, &br);
                }

                if (! bPreviousVoice)
                        speex_encoder_ctl(enc_state, SPEEX_RESET_STATE, NULL);

                if (bIsSpeech) {
                    speex_bits_reset(enc_bits);
                    speex_encode_int(enc_state, psSource, enc_bits);
                    QByteArray networkFrame;
                    networkFrame.resize(speex_bits_nbytes(enc_bits)+4);//add 4 for the frame timestamp for the jitter buffer
                    int packetSize = speex_bits_write(enc_bits, networkFrame.data()+4, networkFrame.size()-4);
                    ((int*)networkFrame.data())[0] = send_timestamp;

                    outputNetworkBuffer.append(networkFrame);
                    emit networkPacketReady();

                    iRealTimeBitrate = packetSize * SAMPLING_RATE / FRAME_SIZE * 8;
                } else {
                    iRealTimeBitrate = 0;
                }
                bPreviousVoice = bIsSpeech;

                //std::cerr << "iRealTimeBitrate : " << iRealTimeBitrate << std::endl;

                send_timestamp += FRAME_SIZE;
                if (send_timestamp >= INT_MAX)
                    send_timestamp = 0;

                inputBuffer = inputBuffer.right(inputBuffer.size() - FRAME_SIZE * sizeof(qint16));
	}

	return maxSize;
}
Example #27
0
rust_fun void qmlrs_variant_get_string_data(const QVariant *v, char *data) {
    QByteArray ba = v->toString().toUtf8();
    memcpy(data, ba.data(), ba.size());
}
Example #28
0
 virtual void GenerateBlock(QByteArray &data)
 {
   m_data->GenerateBlock(reinterpret_cast<byte *>(data.data()), data.size());
 }
Example #29
0
bool BDRingBuffer::OpenFile(const QString &lfilename, uint retry_ms)
{
    safefilename = lfilename;
    filename = lfilename;

        // clean path filename
    QString filename = QDir(QDir::cleanPath(lfilename)).canonicalPath();
    if (filename.isEmpty())
    {
        LOG(VB_GENERAL, LOG_ERR, LOC +
            QString("%1 nonexistent").arg(lfilename));
        filename = lfilename;
    }
    safefilename = filename;

    LOG(VB_GENERAL, LOG_INFO, LOC + QString("Opened BDRingBuffer device at %1")
            .arg(filename));

    // Ask mythiowrapper to update this object on file open progress. Opening
    // a bluray disc can involve opening several hundred files which can take
    // several minutes when the disc structure is remote. The callback allows
    // us to 'kick' the main UI - as the 'please wait' widget is still visible
    // at this stage
    mythfile_open_register_callback(filename.toLocal8Bit().data(), this,
                                    file_opened_callback);

    QMutexLocker locker(&m_infoLock);
    rwlock.lockForWrite();

    if (bdnav)
        close();

    QString keyfile = QString("%1/KEYDB.cfg").arg(GetConfDir());
    QByteArray keyarray = keyfile.toLatin1();
    const char *keyfilepath = keyarray.data();

    bdnav = bd_open(filename.toLocal8Bit().data(), keyfilepath);

    if (!bdnav)
    {
        lastError = tr("Could not open Blu-ray device: %1").arg(filename);
        rwlock.unlock();
        mythfile_open_register_callback(filename.toLocal8Bit().data(), this, NULL);
        return false;
    }

    const meta_dl *metaDiscLibrary = bd_get_meta(bdnav);

    if (metaDiscLibrary)
    {
        LOG(VB_GENERAL, LOG_INFO, LOC + QString("Disc Title: %1 (%2)")
                    .arg(metaDiscLibrary->di_name)
                    .arg(metaDiscLibrary->language_code));
        LOG(VB_GENERAL, LOG_INFO, LOC + QString("Alternative Title: %1")
                    .arg(metaDiscLibrary->di_alternative));
        LOG(VB_GENERAL, LOG_INFO, LOC + QString("Disc Number: %1 of %2")
                    .arg(metaDiscLibrary->di_set_number)
                    .arg(metaDiscLibrary->di_num_sets));
    }

    // Check disc to see encryption status, menu and navigation types.
    m_topMenuSupported   = false;
    m_firstPlaySupported = false;
    const BLURAY_DISC_INFO *discinfo = bd_get_disc_info(bdnav);

    // The following settings affect HDMV navigation
    // (default audio track selection,
    // parental controls, menu language, etc.  They are not yet used.

    // Set parental level "age" to 99 for now.  TODO: Add support for FE level
    bd_set_player_setting(bdnav, BLURAY_PLAYER_SETTING_PARENTAL, 99);

    // Set preferred language to FE guide language
    const char *langpref = gCoreContext->GetSetting(
        "ISO639Language0", "eng").toLatin1().data();
    QString QScountry  = gCoreContext->GetLocale()->GetCountryCode().toLower();
    const char *country = QScountry.toLatin1().data();
    bd_set_player_setting_str(
        bdnav, BLURAY_PLAYER_SETTING_AUDIO_LANG, langpref);

    // Set preferred presentation graphics language to the FE guide language
    bd_set_player_setting_str(bdnav, BLURAY_PLAYER_SETTING_PG_LANG, langpref);

    // Set preferred menu language to the FE guide language
    bd_set_player_setting_str(bdnav, BLURAY_PLAYER_SETTING_MENU_LANG, langpref);

    // Set player country code via MythLocale. (not a region setting)
    bd_set_player_setting_str(
        bdnav, BLURAY_PLAYER_SETTING_COUNTRY_CODE, country);

    int regioncode = 0;
    regioncode = gCoreContext->GetNumSetting("BlurayRegionCode");
    if (regioncode > 0)
        bd_set_player_setting(bdnav, BLURAY_PLAYER_SETTING_REGION_CODE,
                              regioncode);

    LOG(VB_GENERAL, LOG_INFO, LOC + QString("Using %1 as keyfile...")
            .arg(QString(keyfilepath)));

    // Return an index of relevant titles (excludes dupe clips + titles)
    LOG(VB_GENERAL, LOG_INFO, LOC + "Retrieving title list (please wait).");
    m_numTitles = bd_get_titles(bdnav, TITLES_RELEVANT, 30);
    LOG(VB_GENERAL, LOG_INFO, LOC +
        QString("Found %1 titles.").arg(m_numTitles));
    if (!m_numTitles)
    {
        // no title, no point trying any longer
        bd_close(bdnav);
        bdnav = NULL;
        lastError = tr("Unable to find any Blu-ray compatible titles");
        rwlock.unlock();
        mythfile_open_register_callback(filename.toLocal8Bit().data(), this, NULL);
        return false;
    }

    if (discinfo)
    {
        m_topMenuSupported   = discinfo->top_menu_supported;
        m_firstPlaySupported = discinfo->first_play_supported;

        LOG(VB_PLAYBACK, LOG_INFO, LOC + "*** Blu-ray Disc Information ***");
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("First Play Supported: %1")
                .arg(discinfo->first_play_supported ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Top Menu Supported: %1")
                .arg(discinfo->top_menu_supported ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Number of HDMV Titles: %1")
                .arg(discinfo->num_hdmv_titles));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("Number of BD-J Titles: %1")
                .arg(discinfo->num_bdj_titles));
        LOG(VB_PLAYBACK, LOG_INFO, LOC +
            QString("Number of Unsupported Titles: %1")
                .arg(discinfo->num_unsupported_titles));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("AACS present on disc: %1")
                .arg(discinfo->aacs_detected ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("libaacs used: %1")
                .arg(discinfo->libaacs_detected ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("AACS handled: %1")
                .arg(discinfo->aacs_handled ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("BD+ present on disc: %1")
                .arg(discinfo->bdplus_detected ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("libbdplus used: %1")
                .arg(discinfo->libbdplus_detected ? "yes" : "no"));
        LOG(VB_PLAYBACK, LOG_INFO, LOC + QString("BD+ handled: %1")
                .arg(discinfo->bdplus_handled ? "yes" : "no"));
    }
    m_mainTitle = 0;
    m_currentTitleLength = 0;
    m_titlesize = 0;
    m_currentTime = 0;
    m_currentTitleInfo = NULL;
    m_currentTitleAngleCount = 0;

    // Mostly event-driven values below
    m_currentAngle = 0;
    m_currentTitle = 0;
    m_currentPlaylist = 0;
    m_currentPlayitem = 0;
    m_currentChapter = 0;
    m_currentAudioStream = 0;
    m_currentIGStream = 0;
    m_currentPGTextSTStream = 0;
    m_currentSecondaryAudioStream = 0;
    m_currentSecondaryVideoStream = 0;
    m_PGTextSTEnabled = false;
    m_secondaryAudioEnabled = false;
    m_secondaryVideoEnabled = false;
    m_secondaryVideoIsFullscreen = false;
    m_stillMode = BLURAY_STILL_NONE;
    m_stillTime = 0;
    m_inMenu = false;

    // First, attempt to initialize the disc in HDMV navigation mode.
    // If this fails, fall back to the traditional built-in title switching
    // mode.
    if (m_tryHDMVNavigation && m_firstPlaySupported && bd_play(bdnav))
    {
        LOG(VB_GENERAL, LOG_INFO, LOC + "Using HDMV navigation mode.");
        m_isHDMVNavigation = true;

        // Register the Menu Overlay Callback
        bd_register_overlay_proc(bdnav, this, HandleOverlayCallback);
    }
    else
    {
        LOG(VB_GENERAL, LOG_INFO, LOC + "Using title navigation mode.");

        // Loop through the relevant titles and find the longest
        uint64_t titleLength = 0;
        BLURAY_TITLE_INFO *titleInfo = NULL;
        bool found = false;
        for( unsigned i = 0; i < m_numTitles; ++i)
        {
            titleInfo = GetTitleInfo(i);
            if (!titleInfo)
                continue;
            if (titleLength == 0 ||
                (titleInfo->duration > titleLength))
            {
                m_mainTitle = titleInfo->idx;
                titleLength = titleInfo->duration;
                found = true;
            }
        }

        if (!found)
        {
            // no title, no point trying any longer
            bd_close(bdnav);
            bdnav = NULL;
            lastError = tr("Unable to find any usable Blu-ray titles");
            rwlock.unlock();
            mythfile_open_register_callback(filename.toLocal8Bit().data(), this, NULL);
            return false;
        }
        SwitchTitle(m_mainTitle);
    }

    readblocksize   = BD_BLOCK_SIZE * 62;
    setswitchtonext = false;
    ateof           = false;
    commserror      = false;
    numfailures     = 0;
    rawbitrate      = 8000;
    CalcReadAheadThresh();

    rwlock.unlock();

    mythfile_open_register_callback(filename.toLocal8Bit().data(), this, NULL);
    return true;
}
Example #30
0
IMUFrame::IMUFrame(QByteArray data){
    onlyQuaternion = true;

    if(data.length()==36)
        onlyQuaternion = false;

    if(!onlyQuaternion){

        frameNumber = (data[1] << 8) | (data[0] & 0xff);

        data.remove(0,2);

        acc[0] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);
        acc[1] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);
        acc[2] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);

        gyro[0] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);
        gyro[1] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);
        gyro[2] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);

        mag[0] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);
        mag[1] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);
        mag[2] = (data[1] << 8) | (data[0] & 0xff);
        data.remove(0,2);

    }else{

        timestamp =(data[3] << 24) | ((data[2] << 16)& 0xff) | ((data[1] << 8) & 0xfff)| (data[0] & 0xffff);
        data.remove(0,4);

    }

    QByteArray temp;

    temp = data.left(4);
    quaternion[0]=*reinterpret_cast<const float*>(temp.data());
    data.remove(0,4);

    temp = data.left(4);
    quaternion[1]=*reinterpret_cast<const float*>(temp.data());
    data.remove(0,4);

    temp = data.left(4);
    quaternion[2]=*reinterpret_cast<const float*>(temp.data());
    data.remove(0,4);

    temp = data.left(4);
    quaternion[3]=*reinterpret_cast<const float*>(temp.data());
    data.remove(0,4);

    float q0 = quaternion[0];
    float q1 = quaternion[1];
    float q2 = quaternion[2];
    float q3 = quaternion[3];

    double sq0 = q0*q0;
    double sq1 = q1*q1;
    double sq2 = q2*q2;
    double sq3 = q3*q3;

    euler[0] = atan2(2 * (q0*q1 + q2*q3) , (1 - 2*(sq1 + sq2))) * (180/M_PI);
    euler[1] = asin(2*(q0*q2 - q3*q1)) * (180 / M_PI);
    euler[2] = atan2(2 * (q0*q3 + q1*q2 ) , (1 - 2*(sq2 + sq3))) * (180/M_PI);


}